Example #1
0
med_int 
nmfdfnfd(med_int *fid)
#endif
{
  med_int _ret; 
  
  _ret = (med_int) MEDnField((const med_idt) *fid); 

  return(_ret); 
}
void MAJ_236_300_champs(med_idt fid)
{
  med_err lret,ret;
  /*   med_idt         _datagroup=0; */
  med_field_type   typcha;
  char nomcha    [MED_NAME_SIZE+1]="";
  char _meshname [MED_NAME_SIZE+1]="";
  char _dtunit   [MED_SNAME_SIZE+1]="";
  char *comp= NULL, *unit= NULL;
  med_int   ncomp,ncha;
  med_int  _ncstp=0;
  med_bool _local=MED_FALSE;
  htri_t   _datasetexist;
  char _pathi[MED_TAILLE_CHA+1+MED_NAME_SIZE+1]=MED_CHA;
  char _pathf[MED_TAILLE_CHA+2+MED_NAME_SIZE+1]="/CHA_/";
  char _pathtmp[MED_TAILLE_CHA+3]="/CHA__/";
  int i,j;

  char nomlien[MED_NAME_SIZE+1]="";
  char * lien = NULL;
  med_int nln,nval;

  med_int  _nloc,_intgeotype,_sdim;
  char     _pathloc[MED_TAILLE_GAUSS+MED_NAME_SIZE+1]=MED_GAUSS;

  med_int  _npar,_numdt,_numit;
  char     _pathpari[MED_TAILLE_NUM_DATA+MED_NAME_SIZE+1+2*MED_MAX_PARA+1+1]=MED_NUM_DATA;
  char     _pathparf[MED_TAILLE_NUM_DATA+MED_NAME_SIZE+1+2*MED_MAX_PARA+1+1]=MED_NUM_DATA;
  int      _pathparlen;
  med_size _n=0;
  char     _cpstnamei[2*MED_MAX_PARA+1]="";
  char     _cpstnamef[2*MED_MAX_PARA+1]="";
  char     _uniname[MED_SNAME_SIZE+1]="";
/*   hid_t    _lac_plist_id; */
  hid_t    _lcp_plist_id;
  hid_t    _ocp_plist_id;
  med_bool _createunt = MED_TRUE;

  MAJ_version_num(fid,2,3,6);

  /* MAJ des varaibles scalaires */
  _npar = MEDnParameter(fid);
  if (_npar > 0) {
    fprintf(stdout,"  >>> Normalisation des paramètres scalaires\n");
    _pathparf[MED_TAILLE_NUM_DATA-2]='_';
/*     _lac_plist_id = H5Pcreate( H5P_LINK_ACCESS ); */
    _ocp_plist_id = H5Pcreate( H5P_OBJECT_COPY );
    _lcp_plist_id = H5Pcreate( H5P_LINK_CREATE );
    H5Pset_create_intermediate_group( _lcp_plist_id, 1 );
    H5Pset_copy_object( _ocp_plist_id, H5O_COPY_SHALLOW_HIERARCHY_FLAG);
  }

  for (i=0 ; i < _npar ; i++ ) {

    MED_ERR_EXIT_IF (_MEDobjectGetName(fid, _pathpari ,i, &_pathpari[MED_TAILLE_NUM_DATA]) < 0,
		     MED_ERR_ACCESS,MED_ERR_DATAGROUP,_pathpari);


    strcpy(&_pathparf[MED_TAILLE_NUM_DATA],&_pathpari[MED_TAILLE_NUM_DATA]);
/*     SSCRUTE(_pathparf); */
/*     SSCRUTE(_pathpari); */

    /*Copie le group avec ses attributs et les objets de premier niveau.*/
    ret =  H5Ocopy(fid,_pathpari,fid,_pathparf,_ocp_plist_id,_lcp_plist_id);
/*     ret =  H5Lcopy(fid,_pathpari,fid,_pathparf,_lcp_plist_id,_lac_plist_id); */
    EXIT_IF(ret < 0,"Copie du datagroup",_pathpari);

    _pathparlen=strlen(_pathpari);
    _pathpari[_pathparlen]='/';_pathparf[_pathparlen]='/';
    ++_pathparlen;
    _pathpari[_pathparlen]='\0';_pathparf[_pathparlen]='\0';

/*     SSCRUTE(_pathparf); */
/*     SSCRUTE(_pathpari); */

    ret =_MEDnObjects(fid,_pathpari, &_n);
    MED_ERR_EXIT_IF( (ret == (MED_ERR_COUNT + MED_ERR_DATAGROUP)), MED_ERR_COUNT,MED_ERR_PARAMETER,_pathpari);

    for (j=0 ; j < _n ; ++j ) {
      MED_ERR_EXIT_IF (_MEDobjectGetName(fid, _pathpari ,j, &_pathpari[_pathparlen]) < 0,
		       MED_ERR_ACCESS,MED_ERR_DATAGROUP,_pathpari);

      MED_ERR_EXIT_IF (_MEDattributeNumRdByName(fid,_pathpari,MED_NOM_NOR,
						MED_INTERNAL_INT,(unsigned char * const ) &_numit) < 0,
		       MED_ERR_READ,MED_ERR_ATTRIBUTE,MED_NOM_NOR);

      MED_ERR_EXIT_IF (_MEDattributeNumRdByName(fid,_pathpari,MED_NOM_NDT,
						MED_INTERNAL_INT,(unsigned char * const ) &_numdt) < 0,
		       MED_ERR_READ,MED_ERR_ATTRIBUTE,MED_NOM_NDT);
      
      MED_ERR_EXIT_IF (_MEDattributeStringRdByName(fid,_pathpari,MED_NOM_UNI,
						MED_SNAME_SIZE,_uniname) < 0,
		       MED_ERR_READ,MED_ERR_ATTRIBUTE,MED_NOM_NDT);
      
      _MEDgetComputationStepName(MED_SORT_DTIT,_numdt,_numit,&_pathparf[_pathparlen]);
/*       strcat(_pathpari,"/"); */
/*       strcat(_pathparf,"/"); */
/*       SSCRUTE(_pathparf); */
/*       SSCRUTE(_pathpari); */

/*       ret =  H5Ocopy(fid,_pathpari,fid,_pathparf,_ocp_plist_id,_lcp_plist_id); */
/*       ret =  H5Lcopy(fid,_pathpari,fid,_pathparf,_lcp_plist_id,_lac_plist_id); */
/*       H5Eprint1(stderr); */
/*       EXIT_IF(ret < 0,"Copie d'une étape de calcul du paramètre scalaire ",_pathpari); */

      /*On modifie temporairement _pathpari pour pointer dans _pathparf*/
      _pathpari[MED_TAILLE_NUM_DATA-2]='_';
/*       SSCRUTE(_pathparf); */
/*       SSCRUTE(_pathpari); */
      ret = H5Gmove(fid, _pathpari, _pathparf  );
      EXIT_IF(ret < 0,"Renommage de l'étape de calcul",_pathpari);
      _pathpari[MED_TAILLE_NUM_DATA-2]='A';


      MED_ERR_EXIT_IF(H5Adelete_by_name( fid, _pathparf, MED_NOM_UNI, H5P_DEFAULT ) < 0,
		      MED_ERR_DELETE,MED_ERR_ATTRIBUTE,_pathparf);

      _pathparf[_pathparlen]='\0';
      _pathpari[_pathparlen]='\0';
      if ( _createunt ) {
	MED_ERR_EXIT_IF (_MEDattributeStringWrByName(fid,_pathparf,MED_NOM_UNT, MED_SNAME_SIZE,_uniname) < 0,
			 MED_ERR_WRITE,MED_ERR_ATTRIBUTE,MED_NOM_UNT);
	_createunt = MED_FALSE;
      }
    }
    _createunt = MED_TRUE;
    _pathpari[MED_TAILLE_NUM_DATA]='\0';
  }

  if ( _npar > 0 ) {

    _pathpari[MED_TAILLE_NUM_DATA]='\0';
    _pathparf[MED_TAILLE_NUM_DATA]='\0';
    MED_ERR_EXIT_IF ( H5Ldelete(fid,_pathpari,H5P_DEFAULT) < 0 ,
		      MED_ERR_DELETE,MED_ERR_LINK,_pathpari);

    ret = H5Gmove(fid, _pathparf, _pathpari  );
    EXIT_IF(ret < 0,"Renommage du group de paramètres scalaires",_pathparf);

  }

  /* MAJ des localisations */
  _nloc = MEDnLocalization(fid);
/*   ISCRUTE(_nloc); */
  if (_nloc > 0)
    fprintf(stdout,"  >>> Normalisation des localisations des points d'intégration\n");
  for (i=0 ; i < _nloc ; i++ ) {

/*     SSCRUTE(_pathloc); */
    MED_ERR_EXIT_IF (_MEDobjectGetName(fid, _pathloc ,i, &_pathloc[MED_TAILLE_GAUSS]) < 0,
		     MED_ERR_ACCESS,MED_ERR_DATAGROUP,_pathloc);
/*     SSCRUTE(_pathloc); */
    MED_ERR_EXIT_IF (_MEDattributeNumRdByName(fid,_pathloc,MED_NOM_GEO,
					      MED_INTERNAL_INT,(unsigned char * const ) &_intgeotype) < 0,
		     MED_ERR_READ,MED_ERR_ATTRIBUTE,MED_NOM_GEO);
    _sdim = (_intgeotype/100);

    MED_ERR_EXIT_IF (_MEDattributeNumWrByName(fid,_pathloc,MED_NOM_DIM,
					      MED_INTERNAL_INT,(const unsigned char * const) &_sdim) < 0,
		     MED_ERR_WRITE,MED_ERR_ATTRIBUTE,MED_NOM_DIM);

    MED_ERR_EXIT_IF ( _MEDattributeStringWrByName(fid,_pathloc,MED_NOM_INM,MED_NAME_SIZE,"") < 0,
		      MED_ERR_WRITE,MED_ERR_ATTRIBUTE,MED_NOM_INM);
    _pathloc[MED_TAILLE_GAUSS]='\0';

  }

  /* MAJ des liens */
  nln = MEDnLink(fid);
  if (nln > 0)
    fprintf(stdout,"  >>> Normalisation des liens\n");
  for (i=1 ; i <= nln ; i++ ) {


    ret =  MEDlinkInfo(fid, i, nomlien, &nval);
    EXIT_IF(ret,"Erreur a la demande d'information sur le lien",NULL);

/*     printf("\t- Lien n°%i de nom |%s| et de taille "IFORMAT"\n",i,nomlien,nval); */

    lien = (char *) malloc((nval+1)*sizeof(char));
    EXIT_IF(lien == NULL,NULL,NULL);

    ret = MEDlinkRd(fid, nomlien, lien );
    EXIT_IF(ret,"Erreur a la lecture du lien : ",nomlien);

    MAJ_version_num(fid,3,0,8);
    ret = MED30linkWr(fid,nomlien,lien);
    EXIT_IF(ret,"Erreur a l'écrtiure du lien : ",nomlien);
    MAJ_version_num(fid,2,3,6);
 
    lien[nval] = '\0';
/*     printf("\t\t|%s|\n\n",lien); */

    free(lien);
  }

  /* combien de champs dans le fichier */
  ncha = MEDnField(fid);
  EXIT_IF(ncha < 0,"lors de la lecture du nombre de champs",NULL);

  /* MAJ des champs */
  for (i =0;i<ncha;i++) {
    lret = 0;

    /* Lecture du nombre de composantes */
    ncomp = MEDfieldnComponent(fid,i+1);
    if (ncomp < 0) {
      MESSAGE("Erreur à la lecture du nombre de composantes : "); ISCRUTE(ncomp);
      exit(1);
    }

    /* Lecture du type du champ, des noms des composantes et du nom de l'unité*/
    comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
    EXIT_IF(comp == NULL,NULL,NULL);
    unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
    EXIT_IF(unit == NULL,NULL,NULL);

    /*     ret = MED231champInfoEtRen(fid,i+1,nomcha,&typcha,comp,unit,ncomp); */
    ret = MEDfieldInfo(fid,i+1,nomcha,_meshname,&_local,&typcha,comp,unit,_dtunit,&_ncstp);
    MED_ERR_EXIT_IF(ret,MED_ERR_ACCESS,MED_ERR_FIELD,nomcha);

    /* creation du champ destination */
    MAJ_version_num(fid,3,0,8);

    EXIT_IF( H5Gmove(fid, _pathi, _pathtmp  ) < 0,"Switch to ",_pathtmp);
    _datasetexist=H5Lexists( fid, _pathf, H5P_DEFAULT );
    if (_datasetexist ) { EXIT_IF( (H5Gmove(fid, _pathf, _pathi  ) < 0) ,"Switch to ",_pathi); }

    MED_ERR_EXIT_IF( MEDfieldCr(fid,nomcha,typcha,ncomp,comp,unit,_dtunit,_meshname ) < 0,
		     MED_ERR_CREATE,MED_ERR_FIELD,_pathf);
    EXIT_IF( H5Gmove(fid, _pathi  , _pathf  ) < 0,"Switch to ",_pathf);
    EXIT_IF( H5Gmove(fid, _pathtmp, _pathi  ) < 0,"Switch to ",_pathi);

    MAJ_version_num(fid,2,3,6);

    free(comp);
    free(unit);

    lret = MAJ_236_300_fieldOnEntity( fid, nomcha, _meshname, typcha, ncomp, MED_NODE,_ncstp, _pathi, _pathf);
    if (lret != 0) {
      MESSAGE("Erreur à la lecture des champs aux noeuds "); exit(1);
    }

    lret = MAJ_236_300_fieldOnEntity( fid, nomcha, _meshname, typcha, ncomp, MED_CELL,_ncstp, _pathi, _pathf);
    if (lret != 0) {
      MESSAGE("Erreur à la lecture des champs aux mailles "); exit(1);
    }

    lret = MAJ_236_300_fieldOnEntity( fid, nomcha, _meshname, typcha, ncomp, MED_DESCENDING_FACE,_ncstp, _pathi, _pathf);
    if (lret != 0) {
      MESSAGE("Erreur à la lecture des champs aux faces "); exit(1);
    }

    lret = MAJ_236_300_fieldOnEntity( fid, nomcha, _meshname, typcha, ncomp, MED_DESCENDING_EDGE,_ncstp, _pathi, _pathf);
    if (lret != 0) {
      MESSAGE("Erreur à la lecture des champs aux aretes "); exit(1);
    }

    lret = MAJ_236_300_fieldOnEntity( fid, nomcha, _meshname, typcha, ncomp, MED_NODE_ELEMENT,_ncstp, _pathi, _pathf);
    if (lret != 0) {
      MESSAGE("Erreur à la lecture des champs aux aretes "); exit(1);
    }

  }
  _datasetexist=H5Lexists( fid, _pathf, H5P_DEFAULT );

  if (_datasetexist ) {
    EXIT_IF( (H5Ldelete(fid,_pathi, H5P_DEFAULT) < 0) ,"Delete ",_pathi);
    EXIT_IF( (H5Gmove(fid, _pathf, _pathi  ) < 0) ,"Switch to ",_pathf);
  }


}
int main (int argc, char **argv) {
  med_idt fid;
  med_idt nfield, i, j;
  char meshname[MED_NAME_SIZE+1]="";
  med_bool localmesh;
  char fieldname[MED_NAME_SIZE+1]="";
  med_field_type fieldtype;
  char *componentname = NULL;
  char *componentunit = NULL;
  char dtunit[MED_SNAME_SIZE+1]="";
  med_float *values = NULL;
  med_int nstep, nvalues;
  med_int ncomponent;
  med_int csit, numit, numdt, meshnumit, meshnumdt, it;
  med_float dt;
  med_geometry_type geotype;
  med_geometry_type *geotypes = MED_GET_CELL_GEOMETRY_TYPE;
  int k;
  int ret=-1;

  /* open file */
  fid = MEDfileOpen("UsesCase_MEDfield_4.med",MED_ACC_RDONLY);
  if (fid < 0) {
    MESSAGE("ERROR : open file ...");
    goto ERROR;
  }

  /*
   * generic approach : how many fields in the file and identification
   * of each field.
   */
  if ((nfield = MEDnField(fid)) < 0) {
    MESSAGE("ERROR : How many fields in the file ...");
    goto ERROR;
  }

  /* 
   * read values for each field
   */
  for (i=0; i<nfield; i++) {

    if ((ncomponent = MEDfieldnComponent(fid,i+1)) < 0) {
      MESSAGE("ERROR : number of field component ...");
      goto ERROR;
    }

    if ((componentname = (char *) malloc(ncomponent*MED_SNAME_SIZE+1)) == NULL) {
      MESSAGE("ERROR : memory allocation ...");
      goto ERROR;
    }

    if ((componentunit = (char *) malloc(ncomponent*MED_SNAME_SIZE+1)) == NULL) {
      MESSAGE("ERROR : memory allocation ...");
      goto ERROR;
    }    

    if (MEDfieldInfo(fid, i+1, fieldname, meshname, &localmesh, &fieldtype,
		     componentname, componentunit, dtunit, &nstep) < 0) {
      MESSAGE("ERROR : Field info ...");
      free(componentname);
      free(componentunit);
      goto ERROR;
    }
    free(componentname);
    free(componentunit);

    /*
     * Read field values for each computing step 
     */ 
    for (csit=0; csit<nstep; csit++) {

      if (MEDfieldComputingStepMeshInfo(fid, fieldname, csit+1, &numdt, &numit, &dt, 
					&meshnumdt, &meshnumit) < 0) {
	MESSAGE("ERROR : Computing step info ...");
	goto ERROR;
      }

      /* 
       * ... In our case, we suppose that the field values are only defined on cells ... 
       */
      for (it=1; it<=MED_N_CELL_FIXED_GEO; it++) {

	geotype = geotypes[it];
	if ((nvalues = MEDfieldnValue(fid, fieldname, numdt, numit, MED_CELL, geotype)) < 0) {
	  MESSAGE("ERROR : read number of values ...");
	  goto ERROR;
	} 
	if (nvalues) {
	  if ((values = (med_float *) malloc(sizeof(med_float)*nvalues*ncomponent)) == NULL) {
	    MESSAGE("ERROR : memory allocation ...");
	  goto ERROR;
	  }
	  if (MEDfieldValueRd(fid, fieldname, numdt, numit, MED_CELL, geotype,
			      MED_FULL_INTERLACE, MED_ALL_CONSTITUENT, (unsigned char*) values) < 0) {
	    MESSAGE("ERROR : read fields values for cells ..."); 
	    free(values);
	    goto ERROR; 
	  } 
	  free(values);
	}

      }
    }
  }

  ret=0;
 ERROR:
  
  /* close file */
  if (MEDfileClose(fid) < 0) {
    MESSAGE("ERROR : close file ...");             
    ret=-1; 
  } 
  
  return ret;
}
Example #4
0
int GModel::readMED(const std::string &name)
{
  med_idt fid = MEDouvrir((char*)name.c_str(), MED_LECTURE);
  if(fid < 0) {
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  med_int v[3], vf[3];
  MEDversionDonner(&v[0], &v[1], &v[2]);
  MEDversionLire(fid, &vf[0], &vf[1], &vf[2]);
  Msg::Info("Reading MED file V%d.%d.%d using MED library V%d.%d.%d",
            vf[0], vf[1], vf[2], v[0], v[1], v[2]);
  if(vf[0] < 2 || (vf[0] == 2 && vf[1] < 2)){
    Msg::Error("Cannot read MED file older than V2.2");
    return 0;
  }

  std::vector<std::string> meshNames;
  for(int i = 0; i < MEDnMaa(fid); i++){
    char meshName[MED_TAILLE_NOM + 1], meshDesc[MED_TAILLE_DESC + 1];
    med_int spaceDim;
    med_maillage meshType;
#if (MED_MAJOR_NUM == 3)
    med_int meshDim, nStep;
    char dtUnit[MED_SNAME_SIZE + 1];
    char axisName[3 * MED_SNAME_SIZE + 1], axisUnit[3 * MED_SNAME_SIZE + 1];
    med_sorting_type sortingType;
    med_axis_type axisType;
    if(MEDmeshInfo(fid, i + 1, meshName, &spaceDim, &meshDim, &meshType, meshDesc,
                   dtUnit, &sortingType, &nStep, &axisType, axisName, axisUnit) < 0){
#else
    if(MEDmaaInfo(fid, i + 1, meshName, &spaceDim, &meshType, meshDesc) < 0){
#endif
      Msg::Error("Unable to read mesh information");
      return 0;
    }
    meshNames.push_back(meshName);
  }

  if(MEDfermer(fid) < 0){
    Msg::Error("Unable to close file '%s'", (char*)name.c_str());
    return 0;
  }

  int ret = 1;
  for(unsigned int i = 0; i < meshNames.size(); i++){
    // we use the filename as a kind of "partition" indicator, allowing to
    // complete a model part by part (used e.g. in DDM, since MED does not store
    // a partition index)
    GModel *m = findByName(meshNames[i], name);
    if(!m) m = new GModel(meshNames[i]);
    ret = m->readMED(name, i);
    if(!ret) return 0;
  }
  return ret;
}

int GModel::readMED(const std::string &name, int meshIndex)
{
  med_idt fid = MEDouvrir((char*)name.c_str(), MED_LECTURE);
  if(fid < 0){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  int numMeshes = MEDnMaa(fid);
  if(meshIndex >= numMeshes){
    Msg::Info("Could not find mesh %d in MED file", meshIndex);
    return 0;
  }

  checkPointMaxNumbers();
  GModel::setCurrent(this); // make sure we increment max nums in this model

  // read mesh info
  char meshName[MED_TAILLE_NOM + 1], meshDesc[MED_TAILLE_DESC + 1];
  med_int spaceDim, nStep = 1;
  med_maillage meshType;
#if (MED_MAJOR_NUM == 3)
  med_int meshDim;
  char dtUnit[MED_SNAME_SIZE + 1];
  char axisName[3 * MED_SNAME_SIZE + 1], axisUnit[3 * MED_SNAME_SIZE + 1];
  med_sorting_type sortingType;
  med_axis_type axisType;
  if(MEDmeshInfo(fid, meshIndex + 1, meshName, &spaceDim, &meshDim, &meshType, meshDesc,
                 dtUnit, &sortingType, &nStep, &axisType, axisName, axisUnit) < 0){
#else
  if(MEDmaaInfo(fid, meshIndex + 1, meshName, &spaceDim, &meshType, meshDesc) < 0){
#endif
    Msg::Error("Unable to read mesh information");
    return 0;
  }

  // FIXME: we should support multi-step MED3 meshes (probably by
  // storing each mesh as a separate model, with a naming convention
  // e.g. meshName_step%d). This way we could also handle multi-mesh
  // time sequences in MED3.
  if(nStep > 1)
    Msg::Warning("Discarding %d last meshes in multi-step MED mesh", nStep - 1);

  setName(meshName);
  setFileName(name);
  if(meshType == MED_NON_STRUCTURE){
    Msg::Info("Reading %d-D unstructured mesh <<%s>>", spaceDim, meshName);
  }
  else{
    Msg::Error("Reading structured MED meshes is not supported");
    return 0;
  }
  med_int vf[3];
  MEDversionLire(fid, &vf[0], &vf[1], &vf[2]);

  // read nodes
#if (MED_MAJOR_NUM == 3)
  med_bool changeOfCoord, geoTransform;
  med_int numNodes = MEDmeshnEntity(fid, meshName, MED_NO_DT, MED_NO_IT, MED_NODE,
                                    MED_NO_GEOTYPE, MED_COORDINATE, MED_NO_CMODE,
                                    &changeOfCoord, &geoTransform);
#else
  med_int numNodes = MEDnEntMaa(fid, meshName, MED_COOR, MED_NOEUD, MED_NONE,
                                MED_NOD);
#endif
  if(numNodes < 0){
    Msg::Error("Could not read number of MED nodes");
    return 0;
  }
  if(numNodes == 0){
    Msg::Error("No nodes in MED mesh");
    return 0;
  }
  std::vector<MVertex*> verts(numNodes);
  std::vector<med_float> coord(spaceDim * numNodes);
#if (MED_MAJOR_NUM == 3)
  if(MEDmeshNodeCoordinateRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_FULL_INTERLACE,
                             &coord[0]) < 0){
#else
  std::vector<char> coordName(spaceDim * MED_TAILLE_PNOM + 1);
  std::vector<char> coordUnit(spaceDim * MED_TAILLE_PNOM + 1);
  med_repere rep;
  if(MEDcoordLire(fid, meshName, spaceDim, &coord[0], MED_FULL_INTERLACE,
                  MED_ALL, 0, 0, &rep, &coordName[0], &coordUnit[0]) < 0){
#endif
    Msg::Error("Could not read MED node coordinates");
    return 0;
  }

  std::vector<med_int> nodeTags(numNodes);
#if (MED_MAJOR_NUM == 3)
  if(MEDmeshEntityNumberRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_NODE,
                           MED_NO_GEOTYPE, &nodeTags[0]) < 0)
#else
  if(MEDnumLire(fid, meshName, &nodeTags[0], numNodes, MED_NOEUD, MED_NONE) < 0)
#endif
    nodeTags.clear();

  for(int i = 0; i < numNodes; i++)
    verts[i] = new MVertex(coord[spaceDim * i],
                           (spaceDim > 1) ? coord[spaceDim * i + 1] : 0.,
                           (spaceDim > 2) ? coord[spaceDim * i + 2] : 0.,
                           0, nodeTags.empty() ? 0 : nodeTags[i]);

  // read elements (loop over all possible MSH element types)
  for(int mshType = 0; mshType < MSH_NUM_TYPE; mshType++){
    med_geometrie_element type = msh2medElementType(mshType);
    if(type == MED_NONE) continue;
#if (MED_MAJOR_NUM == 3)
    med_bool changeOfCoord;
    med_bool geoTransform;
    med_int numEle = MEDmeshnEntity(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                                    type, MED_CONNECTIVITY, MED_NODAL, &changeOfCoord,
                                    &geoTransform);
#else
    med_int numEle = MEDnEntMaa(fid, meshName, MED_CONN, MED_MAILLE, type, MED_NOD);
#endif
    if(numEle <= 0) continue;
    int numNodPerEle = type % 100;
    std::vector<med_int> conn(numEle * numNodPerEle);
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshElementConnectivityRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                                    type, MED_NODAL, MED_FULL_INTERLACE, &conn[0]) < 0){
#else
    if(MEDconnLire(fid, meshName, spaceDim, &conn[0], MED_FULL_INTERLACE, 0, MED_ALL,
                   MED_MAILLE, type, MED_NOD) < 0){
#endif
      Msg::Error("Could not read MED elements");
      return 0;
    }
    std::vector<med_int> fam(numEle, 0);
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshEntityFamilyNumberRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                                   type, &fam[0]) < 0){
#else
    if(MEDfamLire(fid, meshName, &fam[0], numEle, MED_MAILLE, type) < 0){
#endif
      Msg::Info("No family number for elements: using 0 as default family number");
    }
    std::vector<med_int> eleTags(numEle);
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshEntityNumberRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                             type, &eleTags[0]) < 0)
#else
    if(MEDnumLire(fid, meshName, &eleTags[0], numEle, MED_MAILLE, type) < 0)
#endif
      eleTags.clear();
    std::map<int, std::vector<MElement*> > elements;
    MElementFactory factory;
    for(int j = 0; j < numEle; j++){
      std::vector<MVertex*> v(numNodPerEle);
      for(int k = 0; k < numNodPerEle; k++)
        v[k] = verts[conn[numNodPerEle * j + med2mshNodeIndex(type, k)] - 1];
      MElement *e = factory.create(mshType, v, eleTags.empty() ? 0 : eleTags[j]);
      if(e) elements[-fam[j]].push_back(e);
    }
    _storeElementsInEntities(elements);
  }
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(verts);

  // read family info
  med_int numFamilies = MEDnFam(fid, meshName);
  if(numFamilies < 0){
    Msg::Error("Could not read MED families");
    return 0;
  }
  for(int i = 0; i < numFamilies; i++){
#if (MED_MAJOR_NUM == 3)
    med_int numAttrib = (vf[0] == 2) ? MEDnFamily23Attribute(fid, meshName, i + 1) : 0;
    med_int numGroups = MEDnFamilyGroup(fid, meshName, i + 1);
#else
    med_int numAttrib = MEDnAttribut(fid, meshName, i + 1);
    med_int numGroups = MEDnGroupe(fid, meshName, i + 1);
#endif
    if(numAttrib < 0 || numGroups < 0){
      Msg::Error("Could not read MED groups or attributes");
      return 0;
    }
    std::vector<med_int> attribId(numAttrib + 1);
    std::vector<med_int> attribVal(numAttrib + 1);
    std::vector<char> attribDes(MED_TAILLE_DESC * numAttrib + 1);
    std::vector<char> groupNames(MED_TAILLE_LNOM * numGroups + 1);
    char familyName[MED_TAILLE_NOM + 1];
    med_int familyNum;
#if (MED_MAJOR_NUM == 3)
    if(vf[0] == 2){ // MED2 file
      if(MEDfamily23Info(fid, meshName, i + 1, familyName, &attribId[0],
                         &attribVal[0], &attribDes[0], &familyNum,
                         &groupNames[0]) < 0){
        Msg::Error("Could not read info for MED2 family %d", i + 1);
        continue;
      }
    }
    else{
      if(MEDfamilyInfo(fid, meshName, i + 1, familyName, &familyNum,
                       &groupNames[0]) < 0){
        Msg::Error("Could not read info for MED3 family %d", i + 1);
        continue;
      }
    }
#else
    if(MEDfamInfo(fid, meshName, i + 1, familyName, &familyNum, &attribId[0],
                  &attribVal[0], &attribDes[0], &numAttrib, &groupNames[0],
                  &numGroups) < 0){
      Msg::Error("Could not read info for MED family %d", i + 1);
      continue;
    }
#endif
    // family tags are unique (for all dimensions)
    GEntity *ge;
    if((ge = getRegionByTag(-familyNum))){}
    else if((ge = getFaceByTag(-familyNum))){}
    else if((ge = getEdgeByTag(-familyNum))){}
    else ge = getVertexByTag(-familyNum);
    if(ge){
      elementaryNames[std::pair<int, int>(ge->dim(), -familyNum)] = familyName;
      if(numGroups > 0){
        for(int j = 0; j < numGroups; j++){
          char tmp[MED_TAILLE_LNOM + 1];
          strncpy(tmp, &groupNames[j * MED_TAILLE_LNOM], MED_TAILLE_LNOM);
          tmp[MED_TAILLE_LNOM] = '\0';
          // don't use same physical number across dimensions, as e.g. getdp
          // does not support this
          int pnum = setPhysicalName(tmp, ge->dim(), getMaxPhysicalNumber(-1) + 1);
          if(std::find(ge->physicals.begin(), ge->physicals.end(), pnum) ==
             ge->physicals.end())
            ge->physicals.push_back(pnum);
        }
      }
    }
  }

  // check if we need to read some post-processing data later
#if (MED_MAJOR_NUM == 3)
  bool postpro = (MEDnField(fid) > 0) ? true : false;
#else
  bool postpro = (MEDnChamp(fid, 0) > 0) ? true : false;
#endif

  if(MEDfermer(fid) < 0){
    Msg::Error("Unable to close file '%s'", (char*)name.c_str());
    return 0;
  }

  return postpro ? 2 : 1;
}

template<class T>
static void fillElementsMED(med_int family, std::vector<T*> &elements,
                            std::vector<med_int> &conn, std::vector<med_int> &fam,
                            med_geometrie_element &type)
{
  if(elements.empty()) return;
  type = msh2medElementType(elements[0]->getTypeForMSH());
  if(type == MED_NONE){
    Msg::Warning("Unsupported element type in MED format");
    return;
  }
  for(unsigned int i = 0; i < elements.size(); i++){
    elements[i]->setVolumePositive();
    for(int j = 0; j < elements[i]->getNumVertices(); j++)
      conn.push_back(elements[i]->getVertex(med2mshNodeIndex(type, j))->getIndex());
    fam.push_back(family);
  }
}

static void writeElementsMED(med_idt &fid, char *meshName, std::vector<med_int> &conn,
                             std::vector<med_int> &fam, med_geometrie_element type)
{
  if(fam.empty()) return;
#if (MED_MAJOR_NUM == 3)
  if(MEDmeshElementWr(fid, meshName, MED_NO_DT, MED_NO_IT, 0., MED_CELL, type,
                      MED_NODAL, MED_FULL_INTERLACE, (med_int)fam.size(),
                      &conn[0], MED_FALSE, 0, MED_FALSE, 0, MED_TRUE, &fam[0]) < 0)
#else
  if(MEDelementsEcr(fid, meshName, (med_int)3, &conn[0], MED_FULL_INTERLACE,
                    0, MED_FAUX, 0, MED_FAUX, &fam[0], (med_int)fam.size(),
                    MED_MAILLE, type, MED_NOD) < 0)
#endif
    Msg::Error("Could not write MED elements");
}

int GModel::writeMED(const std::string &name, bool saveAll, double scalingFactor)
{
  med_idt fid = MEDouvrir((char*)name.c_str(), MED_CREATION);
  if(fid < 0){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  // write header
  if(MEDfichDesEcr(fid, (char*)"MED file generated by Gmsh") < 0){
    Msg::Error("Unable to write MED descriptor");
    return 0;
  }

  char *meshName = (char*)getName().c_str();

  // Gmsh always writes 3D unstructured meshes
#if (MED_MAJOR_NUM == 3)
  char dtUnit[MED_SNAME_SIZE + 1] = "";
  char axisName[3 * MED_SNAME_SIZE + 1] = "";
  char axisUnit[3 * MED_SNAME_SIZE + 1] = "";
  if(MEDmeshCr(fid, meshName, 3, 3, MED_UNSTRUCTURED_MESH, "Mesh created with Gmsh",
               dtUnit, MED_SORT_DTIT, MED_CARTESIAN, axisName, axisUnit) < 0){
#else
  if(MEDmaaCr(fid, meshName, 3, MED_NON_STRUCTURE,
              (char*)"Mesh created with Gmsh") < 0){
#endif
    Msg::Error("Could not create MED mesh");
    return 0;
  }

  // if there are no physicals we save all the elements
  if(noPhysicalGroups()) saveAll = true;

  // index the vertices we save in a continuous sequence (MED
  // connectivity is given in terms of vertex indices)
  indexMeshVertices(saveAll);

  // get a vector containing all the geometrical entities in the
  // model (the ordering of the entities must be the same as the one
  // used during the indexing of the vertices)
  std::vector<GEntity*> entities;
  getEntities(entities);

  std::map<GEntity*, int> families;
  // write the families
  {
    // always create a "0" family, with no groups or attributes
#if (MED_MAJOR_NUM == 3)
    if(MEDfamilyCr(fid, meshName, "F_0", 0, 0, "") < 0)
#else
    if(MEDfamCr(fid, meshName, (char*)"F_0", 0, 0, 0, 0, 0, 0, 0) < 0)
#endif
      Msg::Error("Could not create MED family 0");

    // create one family per elementary entity, with one group per
    // physical entity and no attributes
    for(unsigned int i = 0; i < entities.size(); i++){
      if(saveAll || entities[i]->physicals.size()){
        int num = - ((int)families.size() + 1);
        families[entities[i]] = num;
        std::ostringstream fs;
        fs << entities[i]->dim() << "D_" << entities[i]->tag();
        std::string familyName = "F_" + fs.str();
        std::string groupName;
        for(unsigned j = 0; j < entities[i]->physicals.size(); j++){
          std::string tmp = getPhysicalName
            (entities[i]->dim(), entities[i]->physicals[j]);
          if(tmp.empty()){ // create unique name
            std::ostringstream gs;
            gs << entities[i]->dim() << "D_" << entities[i]->physicals[j];
            groupName += "G_" + gs.str();
          }
          else
            groupName += tmp;
          groupName.resize((j + 1) * MED_TAILLE_LNOM, ' ');
        }
#if (MED_MAJOR_NUM == 3)
        if(MEDfamilyCr(fid, meshName, familyName.c_str(),
                       (med_int)num, (med_int)entities[i]->physicals.size(),
                       groupName.c_str()) < 0)
#else
        if(MEDfamCr(fid, meshName, (char*)familyName.c_str(),
                    (med_int)num, 0, 0, 0, 0, (char*)groupName.c_str(),
                    (med_int)entities[i]->physicals.size()) < 0)
#endif
          Msg::Error("Could not create MED family %d", num);
      }
    }
  }

  // write the nodes
  {
    std::vector<med_float> coord;
    std::vector<med_int> fam;
    for(unsigned int i = 0; i < entities.size(); i++){
      for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++){
        MVertex *v = entities[i]->mesh_vertices[j];
        if(v->getIndex() >= 0){
          coord.push_back(v->x() * scalingFactor);
          coord.push_back(v->y() * scalingFactor);
          coord.push_back(v->z() * scalingFactor);
          fam.push_back(0); // we never create node families
        }
      }
    }
    if(fam.empty()){
      Msg::Error("No nodes to write in MED mesh");
      return 0;
    }
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshNodeWr(fid, meshName, MED_NO_DT, MED_NO_IT, 0., MED_FULL_INTERLACE,
                     (med_int)fam.size(), &coord[0], MED_FALSE, "", MED_FALSE, 0,
                     MED_TRUE, &fam[0]) < 0)
#else
    char coordName[3 * MED_TAILLE_PNOM + 1] =
      "x               y               z               ";
    char coordUnit[3 * MED_TAILLE_PNOM + 1] =
      "unknown         unknown         unknown         ";
    if(MEDnoeudsEcr(fid, meshName, (med_int)3, &coord[0], MED_FULL_INTERLACE,
                    MED_CART, coordName, coordUnit, 0, MED_FAUX, 0, MED_FAUX,
                    &fam[0], (med_int)fam.size()) < 0)
#endif
      Msg::Error("Could not write nodes");
  }

  // write the elements
  {
    { // points
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(viter it = firstVertex(); it != lastVertex(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->points, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // lines
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(eiter it = firstEdge(); it != lastEdge(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->lines, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // triangles
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(fiter it = firstFace(); it != lastFace(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->triangles, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // quads
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(fiter it = firstFace(); it != lastFace(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->quadrangles, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // tets
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->tetrahedra, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // hexas
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->hexahedra, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // prisms
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->prisms, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // pyramids
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->pyramids, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
  }

  if(MEDfermer(fid) < 0){
    Msg::Error("Unable to close file '%s'", (char*)name.c_str());
    return 0;
  }

  return 1;
}

#else

int GModel::readMED(const std::string &name)
{
  Msg::Error("Gmsh must be compiled with MED support to read '%s'",
             name.c_str());
  return 0;
}
Example #5
0
int main (int argc, char **argv)


{
  med_err ret,lret;
  med_idt fid;
  char * fichier = NULL;
  char maa[MED_NAME_SIZE+1]="";
  char desc[MED_COMMENT_SIZE+1]="";
  char pflname[MED_NAME_SIZE+1]="",nomlien[MED_NAME_SIZE+1]="";
  char _meshname [MED_NAME_SIZE+1]="";
  char _dtunit [MED_SNAME_SIZE+1]="";
  char locname[MED_NAME_SIZE+1]="";
  char * lien = NULL;
  char *comp= NULL, *unit= NULL;
  char nomcha  [MED_NAME_SIZE+1]="";
  med_int mdim=0,sdim=0,ncomp,ncha,npro,nln,pflsize,*pflval,nval;
  med_int _ncstp=0,ngauss=0,nloc=0,locsdim=0,lnsize=0;
  int t1,t2,t3;
  med_field_type    typcha;
  med_geometry_type type_geo;
  med_float *refcoo, *gscoo, *wg;
  int i,j;
  med_bool _local;

  char dtunit[MED_SNAME_SIZE+1]="";
  char nomcoo[3*MED_SNAME_SIZE+1]="";
  char unicoo[3*MED_SNAME_SIZE+1]="";
  char geointerpname[MED_SNAME_SIZE+1]="";
  char ipointstructmeshname[MED_SNAME_SIZE+1]="";
  med_mesh_type type;
  med_sorting_type sort;
  med_int nstep=0;
  med_axis_type rep;
  med_int nsectionmeshcell;
  med_geometry_type sectiongeotype;

  if (argc != 2) {
    MESSAGE("Aucun nom de fichier precise, fichier test10.med utilise ");
    fichier = "test10.med";
  } else {
    fichier = argv[1];
  };


  /* Ouverture du fichier med */
  if ((fid = MEDfileOpen(fichier,MED_ACC_RDONLY)) < 0){
    MESSAGE("Erreur a l'ouverture du fichier : ");SSCRUTE(fichier);
    return -1;
  }

  ret = 0;


 /* Lecture des infos concernant le premier maillage */
  if ( MEDmeshInfo( fid, 1,  maa, &sdim, &mdim, &type, desc, dtunit, &sort,
		    &nstep,  &rep, nomcoo,unicoo) < 0 ) {
    MESSAGE("Erreur a la lecture des informations sur le maillage : ");SSCRUTE(maa);
    return -1;
  } else {
    printf("Maillage de nom : |%s| , de dimension : %d , et de type %d\n",maa,mdim,type);
    printf("\t -Dimension de l'espace : %d\n",sdim);
    printf("\t -Description du maillage : %s\n",desc);
    printf("\t -Noms des axes : |%s|\n",nomcoo);
    printf("\t -Unités des axes : |%s|\n",unicoo);
    printf("\t -Type de repère : %d\n",rep);
    printf("\t -Nombre d'étapes de calcul : %d\n",nstep);
    printf("\t -Unité des dates : |%s|\n",dtunit);
  }


  /* combien de champs dans le fichier */
  if ((ncha = MEDnField(fid)) < 0) {
    MESSAGE("Impossible de lire le nombre de champs : ");ISCRUTE(ncha);
    return ncha;
  }

  printf("Nombre de champs : "IFORMAT" \n",ncha);

  /* lecture de tous les champs  */
  for (i =0;i<ncha;i++) {
    lret = 0;
    printf("\nChamp numero : %d \n",i+1);

    /* Lecture du nombre de composantes */
    if ((ncomp = MEDfieldnComponent(fid,i+1)) < 0) {
      MESSAGE("Erreur a la lecture du nombre de composantes : "); ISCRUTE(ncomp);
      ret = -1; continue;
    }

    /* Lecture du type du champ, des noms des composantes et du nom de l'unite*/
    comp = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
    EXIT_IF(comp == NULL,NULL,NULL);
    unit = (char*) malloc(ncomp*MED_SNAME_SIZE+1);
    EXIT_IF(unit == NULL,NULL,NULL);

    if ( MEDfieldInfo(fid,i+1,nomcha,_meshname,&_local,&typcha,comp,unit,_dtunit,&_ncstp) < 0 ) {
      MESSAGE("Erreur a la demande d'information sur les champs : ");
      ISCRUTE_int(i+1);SSCRUTE(nomcha);ISCRUTE_int(typcha);SSCRUTE(comp);SSCRUTE(unit);
      ISCRUTE(ncomp);
      ret = -1; continue;
    }


    printf("Nom du champ : |%s| de type %d\n",nomcha,typcha);
    printf("Nom des composantes : |%s|\n",comp);
    printf("Unites des composantes : |%s| \n",unit);
    printf("Unites des dates  : |%s| \n",_dtunit);
    printf("Le maillage associé est |%s|\n",_meshname);
    printf("Nombre de séquences de calcul |%d|\n",_ncstp);

      /* Le maillage reference est-il porte par un autre fichier */
    if ( !_local ) {

      if ( (lnsize=MEDlinkInfoByName(fid,_meshname) ) < 0 )  {
	MESSAGE("Erreur a la lecture de la taille du lien : ");
	SSCRUTE(_meshname);
	ret = -1;
      } else {

	  lien = malloc(lnsize*sizeof(char));
	  EXIT_IF(lien == NULL,NULL,NULL);

	  if ( MEDlinkRd(fid,_meshname, lien) < 0 )  {
	    MESSAGE("Erreur a la lecture du lien : ");
	    SSCRUTE(_meshname);SSCRUTE(lien);
	    ret = -1;
	  } else {
	    printf("\tLe maillage |%s| est porte par un fichier distant |%s|\n",_meshname,lien);
	  }
	  free(lien);
	}
      }
    
    free(comp);
    free(unit);
    
    /*TODO : Créer les API30 spécifiques pour la lecture de champs multi-maillages*/
    if (strcmp(nomcha,"champ entier")) {
      MESSAGE("There is no API yest for reading field on multiple meshes"); continue;
    }
 
    lret = getFieldsOn(fid, nomcha, typcha, ncomp, MED_NODE, USER_INTERLACE,_ncstp );
    
    if (lret == 0) lret = getFieldsOn(fid, nomcha, typcha, ncomp, MED_CELL, USER_INTERLACE,_ncstp );
    else { MESSAGE("Erreur a la lecture des champs aux noeuds "); ret = -1; continue;}
   
    if (lret == 0) lret = getFieldsOn(fid, nomcha, typcha, ncomp, MED_DESCENDING_FACE,USER_INTERLACE,_ncstp);
    else { MESSAGE("Erreur a la lecture des champs aux mailles "); ret = -1; continue;}
   
    if (lret == 0) lret = getFieldsOn(fid, nomcha, typcha, ncomp, MED_DESCENDING_EDGE,USER_INTERLACE,_ncstp);
    else {MESSAGE("Erreur a la lecture des champs aux faces "); ret = -1; continue;}
    
    if (lret == 0) lret = getFieldsOn(fid, nomcha, typcha, ncomp, MED_NODE_ELEMENT,USER_INTERLACE,_ncstp);
    else {MESSAGE("Erreur a la lecture des champs aux aretes"); ret = -1; continue;}
    
    /*TODO */
/*     if (lret == 0) lret = getFieldsOn(fid, nomcha, typcha, ncomp, MED_STRUCT_ELEMENT,USER_INTERLACE,_ncstp); */
/*     else {MESSAGE("Erreur a la lecture des champs aux éléments de structure"); ret = -1; continue;} */
    
    if  (lret != 0) {MESSAGE("Erreur a la lecture des champs aux noeuds des mailles "); ret = -1;};
  }


  /* Interrogation des profils */
  npro = MEDnProfile(fid);

  printf("\nNombre de profils stockes : "IFORMAT"\n\n",npro);
  for (i=1 ; i <= npro ; i++ ) {
    if ( MEDprofileInfo(fid, i, pflname, &nval) < 0)  {
      MESSAGE("Erreur a la demande d'information sur le profil n° : "); ISCRUTE_int(i);
      ret = -1;continue;
    }
    printf("\t- Profil n°%i de nom |%s| et de taille "IFORMAT"\n",i,pflname,nval);
    pflval = (med_int*) malloc(sizeof(med_int)*nval);
    if ( MEDprofileRd(fid, pflname, pflval) < 0) {
      MESSAGE("Erreur a la lecture des valeurs du profil : ");
      SSCRUTE(pflname);
      ret = -1;
    } else {
      printf("\t");
      for (j=0;j<nval;j++) printf(" "IFORMAT" ",*(pflval+j));
      printf("\n\n");
    }
    free(pflval);
  }

  /* Interrogation des liens */
  nln = MEDnLink(fid);

  printf("\nNombre de liens stockes : "IFORMAT"\n\n",nln);
  for (i=1 ; i <= nln ; i++ ) {
    if ( MEDlinkInfo(fid, i, nomlien, &nval) < 0)  {
      MESSAGE("Erreur a la demande d'information sur le lien n° : "); ISCRUTE_int(i);
      ret = -1;continue;
    }
    printf("\t- Lien n°%i de nom |%s| et de taille "IFORMAT"\n",i,nomlien,nval);

    lien = malloc((nval+1)*sizeof(char));
    EXIT_IF(lien == NULL,NULL,NULL);

    if ( MEDlinkRd(fid, nomlien, lien ) < 0 )  {
      MESSAGE("Erreur a la lecture du lien : ");
      SSCRUTE(nomlien);SSCRUTE(lien);
      ret = -1;
    } else {
      lien[nval] = '\0';
      printf("\t\t|%s|\n\n",lien);
    }
    free(lien);
  }

  /* Interrogation des localisations des points de GAUSS */
  nloc = MEDnLocalization(fid);

  printf("\nNombre de localisations stockees : "IFORMAT"\n\n",nloc);
  for (i=1 ; i <= nloc ; i++ ) {
    if ( MEDlocalizationInfo(fid, i, locname, &type_geo, &locsdim,&ngauss,
			     geointerpname, ipointstructmeshname,
			     &nsectionmeshcell,&sectiongeotype) < 0)  {
      MESSAGE("Erreur a la demande d'information sur la localisation n° : "); ISCRUTE_int(i);
      ret = -1;continue;
    }
    printf("\t- Loc. n°%i de nom |%s| de dimension %i avec "IFORMAT" pts de GAUSS \n",i,locname,locsdim,ngauss);
    t1 = (type_geo%100)*(type_geo/100);
    t2 = ngauss*(type_geo/100);
    t3 = ngauss;
    refcoo = (med_float *) malloc(sizeof(med_float)*t1 );
    gscoo  = (med_float *) malloc(sizeof(med_float)*t2 );
    wg     = (med_float *) malloc(sizeof(med_float)*t3 );

    if ( MEDlocalizationRd(fid, locname, USER_INTERLACE, refcoo, gscoo, wg  ) < 0) {
      MESSAGE("Erreur a la lecture des valeurs de la localisation : ");
      SSCRUTE(locname);
      ret = -1;
    } else {
      printf("\t  Coordonnees de l'element de reference de type %i :\n\t\t",type_geo);
      for (j=0;j<t1;j++) printf(" %f ",*(refcoo+j));
      printf("\n");
      printf("\t  Localisation des points de GAUSS : \n\t\t");
      for (j=0;j<t2;j++) printf(" %f ",*(gscoo+j));
      printf("\n");
      printf("\t  Poids associes aux points de GAUSS :\n\t\t");
      for (j=0;j<t3;j++) printf(" %f ",*(wg+j));
      printf("\n\n");
    }
    free(refcoo);
    free(gscoo);
    free(wg);
  }


  /* fermeture du fichier */
  if ( MEDfileClose(fid) < 0) return -1;

  return ret;
}
Example #6
0
int main (int argc, char **argv)


{
  med_err ret=0;
  med_idt fid;

  /* Maillage support aux champs*/
  /* Ces maillages sont vides*/
  char maa1[MED_NAME_SIZE+1]= "maa1";
  char maa2[MED_NAME_SIZE+1]= "maa2";
  char * lien_maa2 = "./testfoo.med";
  char maa3[MED_NAME_SIZE+1]= "maa3";


  /* Caractéristiques du champ n° 1 sur TRIA6 */
  char nomcha1[MED_NAME_SIZE+1]  = "champ reel";
  char comp1[2*MED_SNAME_SIZE+1] = "comp1           comp2           ";
                                   /*12345678901234561234567890123456*/
  char unit1[2*MED_SNAME_SIZE+1] = "unit1           unit2           ";
  med_int ncomp1  = 2;
  /* Caractéristiques du model n° 1 de localisation des points de gauss pour le champ n° 1*/
  med_int ngauss1_1 = 6;
  char gauss1_1[MED_NAME_SIZE+1]  = "Model n1";
  med_float refcoo1[12] = { -1.0,1.0, -1.0,-1.0, 1.0,-1.0, -1.0,0.0, 0.0,-1.0, 0.0,0.0 };

  /* Constantes */

  med_float gscoo1_1[12] = { 2*_b-1, 1-4*_b, 2*_b-1, 2*_b-1, 1-4*_b,
                             2*_b-1, 1-4*_a, 2*_a-1, 2*_a-1, 1-4*_a, 2*_a-1, 2*_a-1 };
  med_float wg1_1[6] = { 4*_p2, 4*_p2, 4*_p2, 4*_p1, 4*_p1, 4*_p1 };

  med_int   nval1_1= 1*6; /*1 valeurs et 6 points de gauss par valeur */
  med_int   _nent1_1= 1; /*1 valeurs et 6 points de gauss par valeur */
  med_float valr1_1[1*6*2]  = {0.0,1.0, 2.0,3.0, 10.0,11.0, 12.0,13.0, 20.0,21.0, 22.0,23.0};  /* 2 composantes*/
  /* Caractéristiques du model n° 2 de localisation des points de gauss pour le champ n° 1*/
  med_int ngauss1_2 = 3;
  char gauss1_2[MED_NAME_SIZE+1]  = "Model n2";
  med_float gscoo1_2[6] = { -2.0/3,1.0/3, -2.0/3,-2.0/3, 1.0/3,-2.0/3  };
  med_float wg1_2[3] = { 2.0/3, 2.0/3, 2.0/3 };
  med_int   nval1_2= 2*3; /*2 valeurs et 3 points de gauss par valeur */
  med_int   _nent1_2= 2; /*2 valeurs et 3 points de gauss par valeur */
  med_float valr1_2[2*3*2]  = {0.0,1.0, 2.0,3.0, 10.0,11.0,   12.0,13.0, 20.0,21.0, 22.0,23.0};  /* 2 composantes*/
  med_float valr1_2p[2*3*2]  = {                              12.0,13.0, 20.0,21.0, 22.0,23.0};  /* 2 composantes*/
 /* Caractéristiques du model n° 3 sans points de gauss pour le champ n° 1*/
  med_int   nval1_3= 6; /*6 valeurs et pas de points de gauss */
  med_int   _nent1_3= 6; /*6 valeurs et pas de points de gauss */
  med_float valr1_3[2*3*2]  = {0.0,1.0, 2.0,3.0, 10.0,11.0, 12.0,13.0, 20.0,21.0, 22.0,23.0};  /* 2 composantes*/
  med_float valr1_3p[2*2*2] = {         2.0,3.0, 10.0,11.0                                 };  /* 2 composantes profil1 */

  /* Caractéristiques du champ n° 2 */
  char nomcha2[MED_NAME_SIZE+1]  = "champ entier";
  char comp2[3*MED_SNAME_SIZE+1] = "comp1           comp2           comp3           ";
                                   /*123456789012345612345678901234561234567890123456*/
  char unit2[3*MED_SNAME_SIZE+1] = "unit1           unit2           unit3           ";
  med_int ncomp2  = 3; 
  med_int nval2 = 5;   /*5 valeurs */
  med_int   valr2[5*3  ]  = {0,1,2, 10,11,12, 20,21,22, 30,31,32, 40,41,42};              /* 3 composantes*/
  med_int   valr2p[3*3  ] = {0,1,2,           20,21,22,           40,41,42};              /* 3 composantes*/

  /* Profils utilisés */
  char nomprofil1[MED_NAME_SIZE+1]  = "PROFIL(champ(1))";
  char nomprofil1b[MED_NAME_SIZE+1] = "PROFIL(champ(1b))";
  char nomprofil2[MED_NAME_SIZE+1]  = "PROFIL(champ2)";
  med_int profil1[2] = { 2, 3 };
  med_int profil2[3] = { 1, 3, 5 };


  /* Caractéristiques du champ n° 3 */
  char nomcha3[MED_NAME_SIZE+1]  = "champ entier 3";
  char comp3[3*MED_SNAME_SIZE+1] = "comp1           comp2           ";
                                   /*123456789012345612345678901234561234567890123456*/
  char unit3[3*MED_SNAME_SIZE+1] = "unit1           unit2           ";
  char dtunit[MED_SNAME_SIZE+1] = "s";
  med_int ncomp3  = 2;
  med_int nval3 = 5*4;     /*5 valeurs et 4 noeuds par element*/
  med_int _nent3 = 5;     /*5 valeurs et 4 noeuds par element*/
  med_int valr3[5*4*2]   = {0,1, 10,11, 20,21, 30,31,
                            40,41, 50,51, 60,61, 70,71,
                            80,81, 90,91, 100,101, 110,111,
                            120,121, 130,131, 140,141, 150,151,
                            160,161, 170,171, 180,181, 190,191};    /* 2 composantes*/
  med_int valr3p[3*4*2]  = {0,1, 10,11, 20,21, 30,31,
                            80,81, 90,91, 100,101, 110,111,
                            160,161, 170,171, 180,181, 190,191};    /* 2 composantes*/


  char nomcoo[3*MED_SNAME_SIZE+1] = "x               y               z               ";
  char unicoo[3*MED_SNAME_SIZE+1] = "cm              cm              cm              ";

  char _maa[MED_NAME_SIZE+1]="";
  char _desc[MED_COMMENT_SIZE+1]="";
  char _dtunit[MED_SNAME_SIZE+1]="";
  char _nomcoo[3*MED_SNAME_SIZE+1]="";
  char _unicoo[3*MED_SNAME_SIZE+1]="";
  med_int _nstep=0;
  med_axis_type _rep;
  med_mesh_type _type;
  med_sorting_type _sort;
  char __dtunit [MED_SNAME_SIZE+1]="";
  med_int _mdim=0,_sdim=0;

  med_int ncha=0;
  med_access_mode _accessmode;
  
  /* Il n'est pas necessaire de  pré-allouer la mémoire.
   med-fichier s'occupe d'allouer la mémoire au fil de l'utilsation de l'API.*/
  /* Attention la structure doit être initialisée à MED_MEMFILE_INIT avant toute première utilisation.*/
  med_memfile memfile[1]    = MED_MEMFILE_INIT;

  /* On décide de pré-allouer suffisement de mémoire : 10MB */
  /* med-fichier utilisera l'espace réservé sans réallocation.*/
  /* memfile[0].app_image_size = 10*1024*1024; */
  /* memfile[0].app_image_ptr      = calloc(memfile[0].app_image_size,sizeof(char)); */

  /* On décide de pré-allouer insuffisement de mémoire : 1KB */
  /* med-fichier utilisera l'espace réservé puis effectuera une réallocation.*/
  /* memfile[0].app_image_size = 1024; */
  /* memfile[0].app_image_ptr  = calloc(memfile[0].app_image_size,sizeof(char)); */

  AFF_MEMFILE;

  /* Ouverture du fichier */
  /* mode RDWR uniquement si le fichier test10.med a préalablement été généré par test10
     ou par le sync de test10_mem (en CREATE). 
     Si test10.med n'existe pas et demande le mode RDWR 
         -> erreur car nous n'avons pas initialisé une image mémoire valide ! 
  */
  _accessmode = MED_ACC_CREAT;
  if ((fid = MEDmemFileOpen("test10.med",memfile,MED_TRUE,_accessmode) ) < 0){
    MESSAGE("Erreur à l'ouverture du fichier : ");
    return -1;
  }
  /* Ouverture du fichier */
  /* Si l'on ne veut pas créer de fichier sur disque, sync=MED_FALSE */
  /* if ((fid = MEDmemFileOpen("test10.med",memfile,MED_FALSE,MED_ACC_CREAT) ) < 0){ */
  /*   MESSAGE("Erreur à l'ouverture du fichier : "); */
  /*   return -1; */
  /* } */

  AFF_MEMFILE;

  /* combien de champs dans le fichier (pour tester le fichier mémoire)*/
  if ((ncha = MEDnField(fid)) < 0) {
    MESSAGE("Impossible de lire le nombre de champs : ");ISCRUTE(ncha);
  }
  printf("Nombre de champs : "IFORMAT" \n",ncha);
  if (ncha == 3 ) { /*Un quatrième champ est crée seulement si un fichier test10.med existait et mode RDWR + sync */
  /* creation du champ réel n° 1 */
    if ( MEDfieldCr(fid,"Ajout Complémentaire",MED_FLOAT64,ncomp1,comp1,unit1,dtunit,maa1 ) < 0) {
      MESSAGE("Erreur à la création du champ : ");SSCRUTE("Ajout Complémentaire");
      ret = -1;
    };
  }
  /* creation de maa1 de dimension 3*/
  if (MEDmeshCr( fid, maa1, 3, 3, MED_UNSTRUCTURED_MESH,
		 "Maillage vide","s", MED_SORT_DTIT,
		 MED_CARTESIAN, nomcoo, unicoo) < 0) {
    MESSAGE("Erreur a la creation du maillage : "); SSCRUTE(maa1);
    ret = -1;
  }


  /* creation de maa3 de dimension 3*/
  if (MEDmeshCr( fid, maa3, 3, 3, MED_UNSTRUCTURED_MESH,
		 "Maillage vide","s", MED_SORT_DTIT,
		 MED_CARTESIAN, nomcoo, unicoo) < 0) {
    MESSAGE("Erreur a la creation du maillage : "); SSCRUTE(maa3);
    ret = -1;
  }


  /* creation du champ réel n° 1 */
  if ( MEDfieldCr(fid,nomcha1,MED_FLOAT64,ncomp1,comp1,unit1,dtunit,maa1 ) < 0) {
    MESSAGE("Erreur à la création du champ : ");SSCRUTE(nomcha1);
    ret = -1;
  };

  /* creation du champ entier n° 2 */
  if ( MEDfieldCr(fid,nomcha2,MED_INT32,ncomp2,comp2,unit2,dtunit,maa2 ) < 0) {
    MESSAGE("Erreur à la création du champ : ");SSCRUTE(nomcha2);
    ret = -1;
  };

  /* creation du lien au fichier distant contenant maa2 */
  if (MEDlinkWr(fid,maa2,lien_maa2) < 0) {
    MESSAGE("Erreur à la création du lien : ");SSCRUTE(lien_maa2);
    ret = -1;
  };

  /* creation de la localisation des points de Gauss modèle n° 1 */
  if (MEDlocalizationWr(fid, gauss1_1, MED_TRIA6, MED_TRIA6/100, refcoo1, USER_INTERLACE,
			ngauss1_1, gscoo1_1, wg1_1,
			MED_NO_INTERPOLATION, MED_NO_MESH_SUPPORT ) < 0) {
    MESSAGE("Erreur à la création du modèle n° 1 : ");SSCRUTE(gauss1_1);
    ret = -1;
  };

   /* creation de la localisation des points de Gauss modèle n° 2 */
  if (MEDlocalizationWr(fid, gauss1_2, MED_TRIA6, MED_TRIA6/100, refcoo1, USER_INTERLACE,
			ngauss1_2, gscoo1_2, wg1_2,
			MED_NO_INTERPOLATION, MED_NO_MESH_SUPPORT) < 0) {
    MESSAGE("Erreur à la création du modèle n° 1 : ");SSCRUTE(gauss1_2);
    ret = -1;
  };
 
  /* ecriture du champ n° 1*/
  /* enregistre uniquement les composantes n° 2 de valr1_1, et n'utilise ni pas de temps ni n° d'ordre*/

  if ( MEDfieldValueWithProfileWr(fid, nomcha1,MED_NO_DT,MED_NO_IT,0.0,MED_CELL,MED_TRIA6,USER_MODE,MED_ALLENTITIES_PROFILE,
		       gauss1_1,USER_INTERLACE, 2, _nent1_1, (unsigned char*)valr1_1 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  

  /* enregistre uniquement les composantes n° 1 de valr1_1, et n'utilise ni pas de temps ni n° d'ordre */

  if ( MEDfieldValueWithProfileWr(fid, nomcha1,MED_NO_DT,MED_NO_IT,0.0,MED_CELL,MED_TRIA6,USER_MODE,MED_ALLENTITIES_PROFILE,
		       gauss1_1,USER_INTERLACE, 1, _nent1_1, (unsigned char*)valr1_1 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  /* enregistre uniquement les composantes n° 1 de valr1_2, au pas de temps n° 1(5.5), n'utilise pas de n° d'ordre*/
  /* ce champ repose sur le maillage maa2 qui est distant */

  if ( MEDfieldValueWithProfileWr(fid, nomcha1,1,MED_NO_IT,5.5,MED_CELL,MED_TRIA6,USER_MODE,MED_ALLENTITIES_PROFILE,
		       gauss1_2,USER_INTERLACE, 1, _nent1_2, (unsigned char*)valr1_2 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  /* Le test initial utilisait un deuxième maillage epour un même champ et une même séquence de calcul,
     ceci n'existe plus en 3.0*/
  /* enregistre uniquement les composantes n° 2 de valr1_2, au pas de temps n° 1(5.5), n'utilise pas de n° d'ordre*/
  /* ce champ repose sur le maillage maa1 qui est local */

  if ( MEDfieldValueWithProfileWr(fid, nomcha1,1,1,5.5,MED_CELL,MED_TRIA6,USER_MODE,MED_ALLENTITIES_PROFILE,
		       gauss1_1,USER_INTERLACE, 2, _nent1_1, (unsigned char*)valr1_1 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };


    /* enregistre uniquement les composantes n° 1 de valr1_1, au pas de temps n° 1(5.5), et n° d'itération n° 2*/
    /* ce champ repose sur le maillage maa3 qui est local */

  if ( MEDfieldValueWithProfileWr(fid, nomcha1,1,2,5.5,MED_CELL,MED_TRIA6,USER_MODE,MED_ALLENTITIES_PROFILE,
		       gauss1_2,USER_INTERLACE, 1, _nent1_2, (unsigned char*)valr1_2 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  /* Creation d'un profil (selection  du deuxieme élément de valr1_1) */
  /* On n'utilise que la première valeur (2) du profil */
  if ( MEDprofileWr(fid,nomprofil1,1,profil1) < 0) {
    MESSAGE("Erreur à l'écriture du profil : ");
    SSCRUTE(nomprofil1);
    ret = -1;
  };


  if ( MEDprofileWr(fid,nomprofil1b,1,profil1) < 0) {
    MESSAGE("Erreur à l'écriture du profil : ");
    SSCRUTE(nomprofil1b);
    ret = -1;
  };




  /* enregistre toutes les composantes du deuxième élément de valr1_1 (premier élément en stockage compact de valr1p),
     au pas de temps n° 2(5.6), et n° d'itération n° 2*/
  if ( MEDfieldValueWithProfileWr(fid, nomcha1,2,2,5.6,MED_CELL,MED_TRIA6,USER_MODE,nomprofil1,
		       MED_NO_LOCALIZATION,USER_INTERLACE, MED_ALL_CONSTITUENT, nval1_3, (unsigned char*)valr1_3p ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  /* enregistre toutes les composantes du deuxième élément de valr1_1 (premier élément en stockage compact de valr1p),
     au pas de temps n° 2(5.6), et n° d'itération n° 2 */

  if ( MEDfieldValueWithProfileWr(fid, nomcha1,2,2,5.6,MED_CELL,MED_TRIA6,USER_MODE,nomprofil1b,
		       gauss1_2,USER_INTERLACE, MED_ALL_CONSTITUENT, _nent1_2, (unsigned char*)valr1_2p ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };


  if ( MEDfieldValueWithProfileWr(fid, nomcha1,3,2,5.7,MED_CELL,MED_TRIA6,USER_MODE,nomprofil1,
		       MED_NO_LOCALIZATION,USER_INTERLACE, 2, _nent1_3, (unsigned char*)valr1_3p ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };


  /* Ecriture du champ n° 2 */
    

  if ( MEDfieldValueWr(fid, nomcha2,MED_NO_DT,MED_NO_IT,0,
				  MED_DESCENDING_EDGE,MED_SEG2,
				  USER_INTERLACE, 1, nval2, (unsigned char*)valr2 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };


  if ( MEDfieldValueWr(fid, nomcha2,MED_NO_DT,MED_NO_IT,0,MED_NODE,MED_NONE,
				  USER_INTERLACE, 2, nval2, (unsigned char*)valr2 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };


  if ( MEDfieldValueWr(fid, nomcha2,MED_NO_DT,MED_NO_IT,0,MED_DESCENDING_FACE,MED_TRIA6,
				  USER_INTERLACE, 3, nval2, (unsigned char*)valr2 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  /* Creation d'un profil (selection  des éléments 1,3,5 de valr2) */
  /* On utilise les trois valeurs du profil */
  if ( MEDprofileWr(fid,nomprofil2,3,profil2) < 0) {
    MESSAGE("Erreur à l'écriture du profil : ");
    SSCRUTE(nomprofil2);
    ret = -1;
  };


  if ( MEDfieldValueWithProfileWr(fid, nomcha2,MED_NO_DT,MED_NO_IT,0,MED_CELL,MED_TRIA6,USER_MODE,nomprofil2,
		       MED_NO_LOCALIZATION,USER_INTERLACE, 3, nval2, (unsigned char*)valr2p ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  /* creation du champ entier n° 3 */
  if ( MEDfieldCr(fid,nomcha3,MED_INT32,ncomp3,comp3,unit3,dtunit,maa1) < 0) {
    MESSAGE("Erreur à la création du champ : ");SSCRUTE(nomcha3);
    ret = -1;
  };
  
  /* Ecriture du champ n° 3 */

  if ( MEDfieldValueWr(fid, nomcha3,MED_NO_DT,MED_NO_IT,0,MED_CELL,MED_QUAD4,
				  USER_INTERLACE, 1, nval3, (unsigned char*)valr3 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  if ( MEDfieldValueWr(fid, nomcha3,MED_NO_DT,MED_NO_IT,0,MED_NODE_ELEMENT,MED_QUAD4,
				  USER_INTERLACE, MED_ALL_CONSTITUENT, _nent3, (unsigned char*)valr3 ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

  if ( MEDfieldValueWithProfileWr(fid, nomcha3,MED_NO_DT,MED_NO_IT,0,MED_NODE_ELEMENT,MED_QUAD4,USER_MODE,nomprofil2,
		       MED_NO_LOCALIZATION,USER_INTERLACE, MED_ALL_CONSTITUENT, _nent3, (unsigned char*)valr3p ) < 0) {
    MESSAGE("Erreur à l'écriture du champ : ");
    SSCRUTE(nomcha1);ISCRUTE_int(MED_NO_DT);ISCRUTE_int(MED_NO_IT);SSCRUTE(MED_NO_PROFILE);
    SSCRUTE(maa1);
    ret = -1;
  };

AFF_MEMFILE;

  /* fermeture du fichier */
  if ( MEDfileClose(fid) < 0 ) {
    ret=-1;
    MESSAGE("Erreur à la fermeture du fichier ");
  }
AFF_MEMFILE;

  /* H5Fflush(fid, H5F_SCOPE_GLOBAL ); */
  _accessmode = MED_ACC_RDWR;
  /*ATTENTION : Il faut au moins une écriture/création dans le fichier pour que le sync se fasse en mode RW*/
  if ((fid = MEDmemFileOpen("test10_mem.med",memfile,MED_TRUE,_accessmode) ) < 0){
    MESSAGE("Erreur à l'ouverture du fichier : ");
    return -1;
  }

AFF_MEMFILE;

  /* combien de champs dans le fichier (pour tester le fichier mémoire)*/
  if ((ncha = MEDnField(fid)) < 0) {
    MESSAGE("Impossible de lire le nombre de champs : ");ISCRUTE(ncha);
  }
  printf("Nombre de champs : "IFORMAT" \n",ncha);

  /*Il faut une écriture pour que le sync se fasse en mode RW*/
  if ( (ncha == 3) || (_accessmode == MED_ACC_RDWR) )
  /* creation du champ complémentaire  n° 2 */
    if ( MEDfieldCr(fid,"Ajout Complémentaire 2",MED_FLOAT64,ncomp1,comp1,unit1,dtunit,maa1 ) < 0) {
      MESSAGE("Erreur à la création du champ : Complémentaire 2");
      ret = -1;
    };

AFF_MEMFILE;

 /* Lecture des infos concernant le premier maillage */
  if ( MEDmeshInfo( fid, 1,  _maa, &_sdim, &_mdim, &_type, _desc, __dtunit, &_sort,
  		    &_nstep,  &_rep, _nomcoo,_unicoo) < 0 ) {
    MESSAGE("Erreur a la lecture des informations sur le maillage : ");SSCRUTE(_maa);
    return -1;
  } else {
    printf("Maillage de nom : |%s| , de dimension : "IFORMAT" , et de type %d\n",_maa,_mdim,_type);
    printf("\t -Dimension de l'espace : "IFORMAT"\n",_sdim);
    printf("\t -Description du maillage : %s\n",_desc);
    printf("\t -Noms des axes : |%s|\n",_nomcoo);
    printf("\t -Unités des axes : |%s|\n",_unicoo);
    printf("\t -Type de repère : %d\n",_rep);
    printf("\t -Nombre d'étapes de calcul : "IFORMAT"\n",_nstep);
    printf("\t -Unité des dates : |%s|\n",__dtunit);
  }

  /* combien de champs dans le fichier (pour tester le fichier mémoire)*/
  if ((ncha = MEDnField(fid)) < 0) {
    MESSAGE("Impossible de lire le nombre de champs : ");ISCRUTE(ncha);
  }
  printf("Nombre de champs : "IFORMAT" \n",ncha);

  if ( MEDfileClose(fid) < 0 )  {
    ret=-1;
    MESSAGE("Erreur à la fermeture du fichier ");
  }

AFF_MEMFILE;

  free(memfile[0].app_image_ptr);
  memfile->app_image_size =0;
  return ret;
}