예제 #1
2
int main()
{
    float x[21*17*9],y[21*17*9],z[21*17*9];
    cgsize_t isize[3][1],ielem[20*16*8][8];
    int index_file,index_base,index_zone;
    cgsize_t irmin,irmax,istart,iend;
    int nsections,index_sect,nbndry,iparent_flag;
    cgsize_t iparentdata;
    char zonename[33],sectionname[33];
    ElementType_t itype;

/* READ X, Y, Z GRID POINTS FROM CGNS FILE */
/* open CGNS file for read-only */
    if (cg_open("grid_c.cgns",CG_MODE_READ,&index_file)) cg_error_exit();
/* we know there is only one base (real working code would check!) */
    index_base=1;
/* we know there is only one zone (real working code would check!) */
    index_zone=1;
/* get zone size (and name - although not needed here) */
    cg_zone_read(index_file,index_base,index_zone,zonename,isize[0]);
/* lower range index */
    irmin=1;
/* upper range index of vertices */
    irmax=isize[0][0];
/* read grid coordinates */
    cg_coord_read(index_file,index_base,index_zone,"CoordinateX",
                  RealSingle,&irmin,&irmax,x);
    cg_coord_read(index_file,index_base,index_zone,"CoordinateY",
                  RealSingle,&irmin,&irmax,y);
    cg_coord_read(index_file,index_base,index_zone,"CoordinateZ",
                  RealSingle,&irmin,&irmax,z);
/* find out how many sections */
    cg_nsections(index_file,index_base,index_zone,&nsections);
    printf("\nnumber of sections=%i\n",nsections);
/* read element connectivity */
    for (index_sect=1; index_sect <= nsections; index_sect++)
    {
      cg_section_read(index_file,index_base,index_zone,index_sect,sectionname,
                      &itype,&istart,&iend,&nbndry,&iparent_flag);
      printf("\nReading section data...\n");
      printf("   section name=%s\n",sectionname);
      printf("   section type=%s\n",ElementTypeName[itype]);
      printf("   istart,iend=%i, %i\n",(int)istart,(int)iend);
      if (itype == HEXA_8)
      {
        printf("   reading element data for this element\n");
        cg_elements_read(index_file,index_base,index_zone,index_sect,ielem[0], \
                         &iparentdata);
      }
      else
      {
        printf("   not reading element data for this element\n");
      }
    }
/* close CGNS file */
    cg_close(index_file);
    printf("\nSuccessfully read unstructured grid from file grid_c.cgns\n");
    printf("   for example, element 1 is made up of nodes: %i, %i, %i, %i, %i, %i, %i, %i\n",
            (int)ielem[0][0],(int)ielem[0][1],(int)ielem[0][2],(int)ielem[0][3],
            (int)ielem[0][4],(int)ielem[0][5],(int)ielem[0][6],(int)ielem[0][7]);
    printf("   x,y,z of node 357 are: %f, %f, %f\n",x[357],y[357],z[357]);
    printf("   x,y,z of node 1357 are: %f, %f, %f\n",x[1357],y[1357],z[1357]);
    return 0;
}
예제 #2
0
// read number of particles from cgns file
int cgns_read_nparts(void)
{
  // Open cgns file and get cgns file index number fn
  char buf[FILE_NAME_SIZE];
  sprintf(buf, "%s/%s/%s", SIM_ROOT_DIR, OUTPUT_DIR, partFiles[partFileMap[0]]);
  int fn;
  int ier = cg_open(buf, CG_MODE_READ, &fn);
  if (ier != 0 ) {
    printf("\nCGNS Error on file %s\n", buf);
    cg_error_exit();
  }
  fflush(stdout);

  // Set base index nuber and zone index number (only one, so is 1)
  int bn = 1;
  int zn = 1;

  // Read zone to find cgsize_t *size, or nparts
  char zonename[FILE_NAME_SIZE] = "";
  cgsize_t nparts = 0;
  ier = cg_zone_read(fn, bn, zn, zonename, &nparts);
  if (ier != 0 ) {
    printf("\nCGNS Error on file %s\n", buf);
    cg_error_exit();
  }
  fflush(stdout);

  cg_close(fn);

  return nparts;
}
// ------------------ deprecated ------------------------
Zone_t Base_t::readZone( int index, string& zonename, vector<int>& zsize, ZoneType_t& type ) const
{
	cgnsstring zname;
	Array<int> size(9); // What is the max number of dimensions???
	int ier;
	ier = cg_zone_read( getFileID(), getID(), ++index, zname, size );
	check_error( "Base_t::getZone", "cg_zone_read", ier );
	ier = cg_zone_type( getFileID(), getID(), index, &type );
	check_error( "Base_t::getZone", "cg_zone_type", ier );

	// copy to user parameters
	zonename = zname;
	int n = (type==Unstructured) ? 1 : getCellDimension();   // don't call get_index_dimension - 'this' is not a Zone_t!
	zsize.resize(3*n);
	for ( int i=0 ; i<2*n ; i++ )
		zsize[i] = size[i];
	if ( type==Structured )
	{
		// in a structured Zone_t, the number of boundary vertices is always zero and is not transmitted by the MLL
		for ( int i=0 ; i<n ; i++ )
			zsize[2*n+i] = 0;
	}
	else
	{
		zsize[2] = size[2];
	}

	return Zone_t(push("Zone_t",index));
}
예제 #4
0
파일: reader.c 프로젝트: dwille/bbtools
void read_cgnsFlow(double *flowFileTime, int flowCount)
{
  char fname[FILE_NAME_SIZE] = "";
  int fn;
  int nbases;
  int B = 1;
  char Bn[FILE_NAME_SIZE] = "Base";
  int cell_dim = 3;
  int phys_dim = 3;
  int Z = 1;
  char Zn[FILE_NAME_SIZE] = "Zone0";
  int size;
  int S = 1;
  char Sn[FILE_NAME_SIZE] = "Solution";

  // Loop over each file
  for (int ff = 0; ff < flowCount; ff++) {
    printf(fname, "%s/output/flow-%d.cgns", flowFileTime[ff]);
    
    cg_open(fname, CG_MODE_READ, &fn);      // open file for reading
    //cg_nbases(fn, &nbases);               // get number of bases (should be 1)
    //cg_base_read(fn, B, basename, cell_dim, phys_dim);  // rea
    cg_zone_read(fn, B, Z, &Zn, &size);
    // size[0] = NVertexI; size[1] = NVertexJ; size[2] = NVertexK
    // size[3] = NCellI; size[4] = NCellJ; size[5] = NCellK
    // size[6]=NBoundVertexI; size[7]=NBoundVertexJ; size[8]=NBoundVertexK = 0
    cg_field_read(fn, B, Z, S, "VelocityX", RealDouble, 0, NCellI?, solnarray);
  }
}
int main()
{
/*
  dimension statements (note that tri-dimensional arrays
  r and p must be dimensioned exactly as [N-1][17-1][21-1] (N>=9) 
  for this particular case or else they will be read from 
  the CGNS file incorrectly!  Other options are to use 1-D 
  arrays, use dynamic memory, or pass index values to a 
  subroutine and dimension exactly there):
*/
    double r[8][16][20],p[8][16][20];
    cgsize_t isize[3][3],irmin[3],irmax[3];
    int index_file,index_base,index_zone,index_flow;
    char zonename[33],solname[33];
    GridLocation_t loc;

/* READ FLOW SOLUTION FROM CGNS FILE */
/* open CGNS file for read-only */
    if (cg_open("grid_c.cgns",CG_MODE_READ,&index_file)) cg_error_exit();
/* we know there is only one base (real working code would check!) */
    index_base=1;
/* we know there is only one zone (real working code would check!) */
    index_zone=1;
/* we know there is only one FlowSolution_t (real working code would check!) */
    index_flow=1;
/* get zone size (and name - although not needed here) */
    cg_zone_read(index_file,index_base,index_zone,zonename,isize[0]);
/* lower range index */
    irmin[0]=1;
    irmin[1]=1;
    irmin[2]=1;
/* upper range index - use cell dimensions */
/* checking GridLocation first (real working code would check */
/* to make sure there are no Rind cells also!): */
    cg_sol_info(index_file,index_base,index_zone,index_flow,solname,&loc);
    if (loc != CellCenter)
    {
      printf("\nError, GridLocation must be CellCenter! Currently: %s\n",
          GridLocationName[loc]);
      return 1;
    }
    irmax[0]=isize[1][0];
    irmax[1]=isize[1][1];
    irmax[2]=isize[1][2];
/* read flow solution */
    cg_field_read(index_file,index_base,index_zone,index_flow,"Density", \
                  RealDouble,irmin,irmax,r[0][0]);
    cg_field_read(index_file,index_base,index_zone,index_flow,"Pressure", \
                  RealDouble,irmin,irmax,p[0][0]);
/* close CGNS file */
    cg_close(index_file);
    printf("\nSuccessfully read flow solution from file grid_c.cgns\n");
    printf("  For example, r,p[7][15][19]= %f, %f\n",r[7][15][19],p[7][15][19]);
    printf("\nProgram successful... ending now\n");
    return 0;
}
int main()
{
    float r[9*17*21],p[9*17*21];
    cgsize_t isize[3][1],irmin,irmax;
    int index_file,index_base,index_zone,index_flow;
    char zonename[33],solname[33];
    GridLocation_t loc;

/* READ FLOW SOLUTION FROM CGNS FILE */
/* open CGNS file for read-only */
    if (cg_open("grid_c.cgns",CG_MODE_READ,&index_file)) cg_error_exit();
/* we know there is only one base (real working code would check!) */
    index_base=1;
/* we know there is only one zone (real working code would check!) */
    index_zone=1;
/* we know there is only one FlowSolution_t (real working code would check!) */
    index_flow=1;
/* get zone size (and name - although not needed here) */
    cg_zone_read(index_file,index_base,index_zone,zonename,isize[0]);
/* lower range index */
    irmin=1;
/* upper range index - use vertex dimensions */
/* checking GridLocation first (real working code would check */
/* to make sure there are no Rind cells also!): */
    cg_sol_info(index_file,index_base,index_zone,index_flow,solname,&loc);
    if (loc != Vertex)
    {
      printf("\nError, GridLocation must be Vertex! Currently: %s\n",
          GridLocationName[loc]);
      return 1;
    }
    irmax=isize[0][0];
/* read flow solution */
    cg_field_read(index_file,index_base,index_zone,index_flow,"Density", \
                  RealSingle,&irmin,&irmax,r);
    cg_field_read(index_file,index_base,index_zone,index_flow,"Pressure", \
                  RealSingle,&irmin,&irmax,p);
/* close CGNS file */
    cg_close(index_file);
    printf("\nSuccessfully read flow solution from file grid_c.cgns\n");
    printf("  For example, r,p[379] = %f, %f\n",r[379],p[379]);
    printf("               r,p[3212]= %f, %f\n",r[3212],p[3212]);
    printf("\nProgram successful... ending now\n");
    return 0;
}
예제 #7
0
파일: reader.c 프로젝트: dwille/bbtools
// read number of particles from cgns file
int cgns_read_nparts(void)
{
  // Open cgns file and get cgns file index number fn
  char buf[FILE_NAME_SIZE];
  sprintf(buf, "%s/%s/%s", ROOT_DIR, OUTPUT_DIR, partFiles[fileMap[0]]);
  int fn;
  cg_open(buf, CG_MODE_READ, &fn);

  // Set base index nuber and zone index number (only one, so is 1)
  int bn = 1;
  int zn = 1;

  // Read zone to find cgsize_t *size, or nparts
  char zonename[FILE_NAME_SIZE] = "";
  cgsize_t nparts = 0;
  cg_zone_read(fn, bn, zn, zonename, &nparts);

  cg_close(fn);

  return nparts;
}
/*! Reads information about a specified Zone_t
 * \param index     Index of zone to read
 * \param zonename  Name of that zone
 * \param nodesize  Number of nodes in each direction in structured zones, total nb. of nodes for unstructured
 * \param cellsize  Number of cells in each direction in structured zones, total nb. of cells for unstructured
 * \param bndrysize Number of boundary vertices in each direction in structured zone, total nb of boundary vertices for unstructured
 * \param type      Type of zone (Structured or Unstructured)
 * \throw cgns_notfound When the requested zone index was not found under the current base
 */
Zone_t Base_t::readZone( int index, string& zonename, vector<int>& nodesize, vector<int>& cellsize, vector<int>& bndrysize, ZoneType_t& type ) const
{
	cgnsstring zname;
	int sizedata[9]; // What is the max number of dimensions???
	int ier;
	ier = cg_zone_read( getFileID(), getID(), ++index, zname, sizedata );
	check_error( "Base_t::getZone", "cg_zone_read", ier );
	ier = cg_zone_type( getFileID(), getID(), index, &type );
	check_error( "Base_t::getZone", "cg_zone_type", ier );

	// copy to user parameters
	switch( type )
	{
	case Unstructured:
		nodesize.resize(1,sizedata[0]);
		cellsize.resize(1,sizedata[1]);
		bndrysize.resize(1,sizedata[2]);
		break;
	case Structured:
		{
		int nindexdim = getCellDimension();   // don't call get_index_dimension - 'this' is not a Zone_t!
		nodesize.resize(nindexdim);
		cellsize.resize(nindexdim);
		bndrysize.resize(0);
		for ( int i=0 ; i<nindexdim ; i++ )
			{
			nodesize[i] = sizedata[i];
			cellsize[i] = sizedata[nindexdim+i];
			}
		}
		break;
	}
	zonename = zname;
	
	structure_t s = push( "Zone_t", index );
	s.set_attribute( "ZoneType", type );
	return Zone_t(s);
	
	//return Zone_t(push("Zone_t",index));
}
int main()
{
    int ilo[2],ihi[2],jlo[2],jhi[2],klo[2],khi[2];
    int icount,j,k;
    int index_file,index_base,nzone,index_zone,nconns,n1to1,index_conn,iz;
    char donorname[33],zonename0[33],zonename1[33],zn[33];
    cgsize_t isize[3][3],ipnts[maxcount][3],ipntsdonor[maxcount][3];

/* WRITE GENERAL CONNECTIVITY INFORMATION TO EXISTING CGNS FILE */
/* open CGNS file for modify */
    if (cg_open("grid_c.cgns",CG_MODE_MODIFY,&index_file)) cg_error_exit();
/* we know there is only one base (real working code would check!) */
    index_base=1;
/* get number of zones (should be 2 for our case) */
    cg_nzones(index_file,index_base,&nzone);
    if (nzone != 2)
    {
      printf("\nError. This program expects 2 zones. %d read.\n",nzone);
      return 1;
    }

/* loop over zones to get zone sizes and names */
    for (index_zone=0; index_zone < nzone; ++index_zone)
    {
      iz=index_zone+1;
      cg_zone_read(index_file,index_base,iz,zn,isize[0]);
      if (index_zone == 0)
      {
        strcpy(zonename0,zn);
      }
      else
      {
        strcpy(zonename1,zn);
      }
      ilo[index_zone]=1;
      ihi[index_zone]=isize[0][0];
      jlo[index_zone]=1;
      jhi[index_zone]=isize[0][1];
      klo[index_zone]=1;
      khi[index_zone]=isize[0][2];
    }
/* loop over zones again */
    for (index_zone=0; index_zone < nzone; ++index_zone)
    {
      iz=index_zone+1;
/* for this program, there should be no existing connectivity info: */
      cg_nconns(index_file,index_base,iz,&nconns);
      if (nconns != 0)
      {
        printf("\nError. This program expects no interfaces yet. %d read.\n",nconns);
        return 1;
      }
      cg_n1to1(index_file,index_base,iz,&n1to1);
      if (n1to1 != 0)
      {
        printf("\nError. This program expects no interfaces yet. %d read.\n",n1to1);
        return 1;
      }
/* set up point lists */
      if (index_zone == 0)
      {
        strcpy(donorname,zonename1);
        icount=0;
        for (j=jlo[index_zone]; j <= jhi[index_zone]; j++)
        {
          for (k=klo[index_zone]; k <= khi[index_zone]; k++)
          {
            ipnts[icount][0]=ihi[0];
            ipnts[icount][1]=j;
            ipnts[icount][2]=k;
            ipntsdonor[icount][0]=ilo[1];
            ipntsdonor[icount][1]=j;
            ipntsdonor[icount][2]=k;
            icount=icount+1;
          }
        }
        if (icount > maxcount)
        {
          printf("\nError. Need to increase maxcount to at least %i\n",icount);
          return 1;
        }
      }
      else
      {
        strcpy(donorname,zonename0);
        icount=0;
        for (j=jlo[index_zone]; j <= jhi[index_zone]; j++)
        {
          for (k=klo[index_zone]; k <= khi[index_zone]; k++)
          {
            ipnts[icount][0]=ilo[1];
            ipnts[icount][1]=j;
            ipnts[icount][2]=k;
            ipntsdonor[icount][0]=ihi[0];
            ipntsdonor[icount][1]=j;
            ipntsdonor[icount][2]=k;
            icount=icount+1;
          }
        }
        if (icount > maxcount)
        {
          printf("\nError. Need to increase maxcount to at least %i\n",icount);
          return 1;
        }
      }
/* write integer connectivity info (user can give any name) */
      cg_conn_write(index_file,index_base,iz,"GenInterface",Vertex,Abutting1to1,
          PointList,icount,ipnts[0],donorname,Structured,
          PointListDonor,Integer,icount,ipntsdonor[0],&index_conn);
    }
/* close CGNS file */
    cg_close(index_file);
    printf("\nSuccessfully added 1-to-1 connectivity info to file grid_c.cgns (using GENERAL method)\n"); 
    return 0;
}
예제 #10
0
/*@
  DMPlexCreateCGNS - Create a DMPlex mesh from a CGNS file ID.

  Collective on comm

  Input Parameters:
+ comm  - The MPI communicator
. cgid - The CG id associated with a file and obtained using cg_open
- interpolate - Create faces and edges in the mesh

  Output Parameter:
. dm  - The DM object representing the mesh

  Note: http://www.grc.nasa.gov/WWW/cgns/CGNS_docs_current/index.html

  Level: beginner

.keywords: mesh,CGNS
.seealso: DMPlexCreate(), DMPlexCreateExodus()
@*/
PetscErrorCode DMPlexCreateCGNS(MPI_Comm comm, PetscInt cgid, PetscBool interpolate, DM *dm)
{
#if defined(PETSC_HAVE_CGNS)
  PetscMPIInt    num_proc, rank;
  PetscSection   coordSection;
  Vec            coordinates;
  PetscScalar   *coords;
  PetscInt      *cellStart, *vertStart;
  PetscInt       coordSize, v;
  PetscErrorCode ierr;
  /* Read from file */
  char basename[CGIO_MAX_NAME_LENGTH+1];
  char buffer[CGIO_MAX_NAME_LENGTH+1];
  int  dim    = 0, physDim = 0, numVertices = 0, numCells = 0;
  int  nzones = 0;
#endif

  PetscFunctionBegin;
#if defined(PETSC_HAVE_CGNS)
  ierr = MPI_Comm_rank(comm, &rank);CHKERRQ(ierr);
  ierr = MPI_Comm_size(comm, &num_proc);CHKERRQ(ierr);
  ierr = DMCreate(comm, dm);CHKERRQ(ierr);
  ierr = DMSetType(*dm, DMPLEX);CHKERRQ(ierr);
  /* Open CGNS II file and read basic informations on rank 0, then broadcast to all processors */
  if (!rank) {
    int nbases, z;

    ierr = cg_nbases(cgid, &nbases);CHKERRQ(ierr);
    if (nbases > 1) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CGNS file must have a single base, not %d\n",nbases);
    ierr = cg_base_read(cgid, 1, basename, &dim, &physDim);CHKERRQ(ierr);
    ierr = cg_nzones(cgid, 1, &nzones);CHKERRQ(ierr);
    ierr = PetscCalloc2(nzones+1, &cellStart, nzones+1, &vertStart);CHKERRQ(ierr);
    for (z = 1; z <= nzones; ++z) {
      cgsize_t sizes[3]; /* Number of vertices, number of cells, number of boundary vertices */

      ierr = cg_zone_read(cgid, 1, z, buffer, sizes);CHKERRQ(ierr);
      numVertices += sizes[0];
      numCells    += sizes[1];
      cellStart[z] += sizes[1] + cellStart[z-1];
      vertStart[z] += sizes[0] + vertStart[z-1];
    }
    for (z = 1; z <= nzones; ++z) {
      vertStart[z] += numCells;
    }
  }
  ierr = MPI_Bcast(basename, CGIO_MAX_NAME_LENGTH+1, MPI_CHAR, 0, comm);CHKERRQ(ierr);
  ierr = MPI_Bcast(&dim, 1, MPI_INT, 0, comm);CHKERRQ(ierr);
  ierr = MPI_Bcast(&nzones, 1, MPI_INT, 0, comm);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) *dm, basename);CHKERRQ(ierr);
  ierr = DMSetDimension(*dm, dim);CHKERRQ(ierr);
  ierr = DMPlexSetChart(*dm, 0, numCells+numVertices);CHKERRQ(ierr);

  /* Read zone information */
  if (!rank) {
    int z, c, c_loc, v, v_loc;

    /* Read the cell set connectivity table and build mesh topology
       CGNS standard requires that cells in a zone be numbered sequentially and be pairwise disjoint. */
    /* First set sizes */
    for (z = 1, c = 0; z <= nzones; ++z) {
      ZoneType_t    zonetype;
      int           nsections;
      ElementType_t cellType;
      cgsize_t      start, end;
      int           nbndry, parentFlag;
      PetscInt      numCorners;

      ierr = cg_zone_type(cgid, 1, z, &zonetype);CHKERRQ(ierr);
      if (zonetype == Structured) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Can only handle Unstructured zones for CGNS");
      ierr = cg_nsections(cgid, 1, z, &nsections);CHKERRQ(ierr);
      if (nsections > 1) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CGNS file must have a single section, not %d\n",nsections);
      ierr = cg_section_read(cgid, 1, z, 1, buffer, &cellType, &start, &end, &nbndry, &parentFlag);CHKERRQ(ierr);
      /* This alone is reason enough to bludgeon every single CGNDS developer, this must be what they describe as the "idiocy of crowds" */
      if (cellType == MIXED) {
        cgsize_t elementDataSize, *elements;
        PetscInt off;

        ierr = cg_ElementDataSize(cgid, 1, z, 1, &elementDataSize);CHKERRQ(ierr);
        ierr = PetscMalloc1(elementDataSize, &elements);CHKERRQ(ierr);
        ierr = cg_elements_read(cgid, 1, z, 1, elements, NULL);CHKERRQ(ierr);
        for (c_loc = start, off = 0; c_loc <= end; ++c_loc, ++c) {
          switch (elements[off]) {
          case TRI_3:   numCorners = 3;break;
          case QUAD_4:  numCorners = 4;break;
          case TETRA_4: numCorners = 4;break;
          case HEXA_8:  numCorners = 8;break;
          default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid cell type %d", (int) elements[off]);
          }
          ierr = DMPlexSetConeSize(*dm, c, numCorners);CHKERRQ(ierr);
          off += numCorners+1;
        }
        ierr = PetscFree(elements);CHKERRQ(ierr);
      } else {
        switch (cellType) {
        case TRI_3:   numCorners = 3;break;
        case QUAD_4:  numCorners = 4;break;
        case TETRA_4: numCorners = 4;break;
        case HEXA_8:  numCorners = 8;break;
        default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid cell type %d", (int) cellType);
        }
        for (c_loc = start; c_loc <= end; ++c_loc, ++c) {
          ierr = DMPlexSetConeSize(*dm, c, numCorners);CHKERRQ(ierr);
        }
      }
    }
    ierr = DMSetUp(*dm);CHKERRQ(ierr);
    for (z = 1, c = 0; z <= nzones; ++z) {
      ElementType_t cellType;
      cgsize_t     *elements, elementDataSize, start, end;
      int           nbndry, parentFlag;
      PetscInt     *cone, numc, numCorners, maxCorners = 27;

      ierr = cg_section_read(cgid, 1, z, 1, buffer, &cellType, &start, &end, &nbndry, &parentFlag);CHKERRQ(ierr);
      numc = end - start;
      /* This alone is reason enough to bludgeon every single CGNDS developer, this must be what they describe as the "idiocy of crowds" */
      ierr = cg_ElementDataSize(cgid, 1, z, 1, &elementDataSize);CHKERRQ(ierr);
      ierr = PetscMalloc2(elementDataSize,&elements,maxCorners,&cone);CHKERRQ(ierr);
      ierr = cg_elements_read(cgid, 1, z, 1, elements, NULL);CHKERRQ(ierr);
      if (cellType == MIXED) {
        /* CGNS uses Fortran-based indexing, sieve uses C-style and numbers cell first then vertices. */
        for (c_loc = 0, v = 0; c_loc <= numc; ++c_loc, ++c) {
          switch (elements[v]) {
          case TRI_3:   numCorners = 3;break;
          case QUAD_4:  numCorners = 4;break;
          case TETRA_4: numCorners = 4;break;
          case HEXA_8:  numCorners = 8;break;
          default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid cell type %d", (int) elements[v]);
          }
          ++v;
          for (v_loc = 0; v_loc < numCorners; ++v_loc, ++v) {
            cone[v_loc] = elements[v]+numCells-1;
          }
          /* Tetrahedra are inverted */
          if (elements[v] == TETRA_4) {
            PetscInt tmp = cone[0];
            cone[0] = cone[1];
            cone[1] = tmp;
          }
          /* Hexahedra are inverted */
          if (elements[v] == HEXA_8) {
            PetscInt tmp = cone[5];
            cone[5] = cone[7];
            cone[7] = tmp;
          }
          ierr = DMPlexSetCone(*dm, c, cone);CHKERRQ(ierr);
          ierr = DMPlexSetLabelValue(*dm, "zone", c, z);CHKERRQ(ierr);
        }
      } else {
        switch (cellType) {
        case TRI_3:   numCorners = 3;break;
        case QUAD_4:  numCorners = 4;break;
        case TETRA_4: numCorners = 4;break;
        case HEXA_8:  numCorners = 8;break;
        default: SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid cell type %d", (int) cellType);
        }

        /* CGNS uses Fortran-based indexing, sieve uses C-style and numbers cell first then vertices. */
        for (c_loc = 0, v = 0; c_loc <= numc; ++c_loc, ++c) {
          for (v_loc = 0; v_loc < numCorners; ++v_loc, ++v) {
            cone[v_loc] = elements[v]+numCells-1;
          }
          /* Tetrahedra are inverted */
          if (cellType == TETRA_4) {
            PetscInt tmp = cone[0];
            cone[0] = cone[1];
            cone[1] = tmp;
          }
          /* Hexahedra are inverted, and they give the top first */
          if (cellType == HEXA_8) {
            PetscInt tmp = cone[5];
            cone[5] = cone[7];
            cone[7] = tmp;
          }
          ierr = DMPlexSetCone(*dm, c, cone);CHKERRQ(ierr);
          ierr = DMPlexSetLabelValue(*dm, "zone", c, z);CHKERRQ(ierr);
        }
      }
      ierr = PetscFree2(elements,cone);CHKERRQ(ierr);
    }
  }
  ierr = DMPlexSymmetrize(*dm);CHKERRQ(ierr);
  ierr = DMPlexStratify(*dm);CHKERRQ(ierr);
  if (interpolate) {
    DM idm = NULL;

    ierr = DMPlexInterpolate(*dm, &idm);CHKERRQ(ierr);
    /* Maintain zone label */
    {
      DMLabel label;

      ierr = DMPlexRemoveLabel(*dm, "zone", &label);CHKERRQ(ierr);
      if (label) {ierr = DMPlexAddLabel(idm, label);CHKERRQ(ierr);}
    }
    ierr = DMDestroy(dm);CHKERRQ(ierr);
    *dm  = idm;
  }

  /* Read coordinates */
  ierr = DMGetCoordinateSection(*dm, &coordSection);CHKERRQ(ierr);
  ierr = PetscSectionSetNumFields(coordSection, 1);CHKERRQ(ierr);
  ierr = PetscSectionSetFieldComponents(coordSection, 0, dim);CHKERRQ(ierr);
  ierr = PetscSectionSetChart(coordSection, numCells, numCells + numVertices);CHKERRQ(ierr);
  for (v = numCells; v < numCells+numVertices; ++v) {
    ierr = PetscSectionSetDof(coordSection, v, dim);CHKERRQ(ierr);
    ierr = PetscSectionSetFieldDof(coordSection, v, 0, dim);CHKERRQ(ierr);
  }
  ierr = PetscSectionSetUp(coordSection);CHKERRQ(ierr);
  ierr = PetscSectionGetStorageSize(coordSection, &coordSize);CHKERRQ(ierr);
  ierr = VecCreate(comm, &coordinates);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) coordinates, "coordinates");CHKERRQ(ierr);
  ierr = VecSetSizes(coordinates, coordSize, PETSC_DETERMINE);CHKERRQ(ierr);
  ierr = VecSetType(coordinates,VECSTANDARD);CHKERRQ(ierr);
  ierr = VecGetArray(coordinates, &coords);CHKERRQ(ierr);
  if (!rank) {
    PetscInt off = 0;
    float   *x[3];
    int      z, d;

    ierr = PetscMalloc3(numVertices,&x[0],numVertices,&x[1],numVertices,&x[2]);CHKERRQ(ierr);
    for (z = 1; z <= nzones; ++z) {
      DataType_t datatype;
      cgsize_t   sizes[3]; /* Number of vertices, number of cells, number of boundary vertices */
      cgsize_t   range_min[3] = {1, 1, 1};
      cgsize_t   range_max[3] = {1, 1, 1};
      int        ngrids, ncoords;


      ierr = cg_zone_read(cgid, 1, z, buffer, sizes);CHKERRQ(ierr);
      range_max[0] = sizes[0];
      ierr = cg_ngrids(cgid, 1, z, &ngrids);CHKERRQ(ierr);
      if (ngrids > 1) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CGNS file must have a single grid, not %d\n",ngrids);
      ierr = cg_ncoords(cgid, 1, z, &ncoords);CHKERRQ(ierr);
      if (ncoords != dim) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"CGNS file must have a coordinate array for each dimension, not %d\n",ncoords);
      for (d = 0; d < dim; ++d) {
        ierr = cg_coord_info(cgid, 1, z, 1+d, &datatype, buffer);CHKERRQ(ierr);
        ierr = cg_coord_read(cgid, 1, z, buffer, RealSingle, range_min, range_max, x[d]);CHKERRQ(ierr);
      }
      if (dim > 0) {
        for (v = 0; v < sizes[0]; ++v) coords[(v+off)*dim+0] = x[0][v];
      }
      if (dim > 1) {
        for (v = 0; v < sizes[0]; ++v) coords[(v+off)*dim+1] = x[1][v];
      }
      if (dim > 2) {
        for (v = 0; v < sizes[0]; ++v) coords[(v+off)*dim+2] = x[2][v];
      }
      off += sizes[0];
    }
    ierr = PetscFree3(x[0],x[1],x[2]);CHKERRQ(ierr);
  }
  ierr = VecRestoreArray(coordinates, &coords);CHKERRQ(ierr);
  ierr = DMSetCoordinatesLocal(*dm, coordinates);CHKERRQ(ierr);
  ierr = VecDestroy(&coordinates);CHKERRQ(ierr);
  /* Read boundary conditions */
  if (!rank) {
    DMLabel        label;
    BCType_t       bctype;
    DataType_t     datatype;
    PointSetType_t pointtype;
    cgsize_t      *points;
    PetscReal     *normals;
    int            normal[3];
    char          *bcname = buffer;
    cgsize_t       npoints, nnormals;
    int            z, nbc, bc, c, ndatasets;

    for (z = 1; z <= nzones; ++z) {
      ierr = cg_nbocos(cgid, 1, z, &nbc);CHKERRQ(ierr);
      for (bc = 1; bc <= nbc; ++bc) {
        ierr = cg_boco_info(cgid, 1, z, bc, bcname, &bctype, &pointtype, &npoints, normal, &nnormals, &datatype, &ndatasets);CHKERRQ(ierr);
        ierr = DMPlexCreateLabel(*dm, bcname);CHKERRQ(ierr);
        ierr = DMPlexGetLabel(*dm, bcname, &label);CHKERRQ(ierr);
        ierr = PetscMalloc2(npoints, &points, nnormals, &normals);CHKERRQ(ierr);
        ierr = cg_boco_read(cgid, 1, z, bc, points, (void *) normals);CHKERRQ(ierr);
        if (pointtype == ElementRange) {
          /* Range of cells: assuming half-open interval since the documentation sucks */
          for (c = points[0]; c < points[1]; ++c) {
            ierr = DMLabelSetValue(label, c - cellStart[z-1], 1);CHKERRQ(ierr);
          }
        } else if (pointtype == ElementList) {
          /* List of cells */
          for (c = 0; c < npoints; ++c) {
            ierr = DMLabelSetValue(label, points[c] - cellStart[z-1], 1);CHKERRQ(ierr);
          }
        } else if (pointtype == PointRange) {
          GridLocation_t gridloc;

          /* List of points: Oh please, someone get the CGNS developers away from a computer. This is unconscionable. */
          ierr = cg_goto(cgid, 1, "Zone_t", z, "BC_t", bc, "end");CHKERRQ(ierr);
          ierr = cg_gridlocation_read(&gridloc);CHKERRQ(ierr);
          /* Range of points: assuming half-open interval since the documentation sucks */
          for (c = points[0]; c < points[1]; ++c) {
            if (gridloc == Vertex) {ierr = DMLabelSetValue(label, c - vertStart[z-1], 1);CHKERRQ(ierr);}
            else                   {ierr = DMLabelSetValue(label, c - cellStart[z-1], 1);CHKERRQ(ierr);}
          }
        } else if (pointtype == PointList) {
          GridLocation_t gridloc;

          /* List of points: Oh please, someone get the CGNS developers away from a computer. This is unconscionable. */
          ierr = cg_goto(cgid, 1, "Zone_t", z, "BC_t", bc, "end");
          ierr = cg_gridlocation_read(&gridloc);
          for (c = 0; c < npoints; ++c) {
            if (gridloc == Vertex) {ierr = DMLabelSetValue(label, points[c] - vertStart[z-1], 1);CHKERRQ(ierr);}
            else                   {ierr = DMLabelSetValue(label, points[c] - cellStart[z-1], 1);CHKERRQ(ierr);}
          }
        } else SETERRQ1(comm, PETSC_ERR_SUP, "Unsupported point set type %d", (int) pointtype);
        ierr = PetscFree2(points, normals);CHKERRQ(ierr);
      }
    }
    ierr = PetscFree2(cellStart, vertStart);CHKERRQ(ierr);
  }
#else
  SETERRQ(comm, PETSC_ERR_SUP, "This method requires CGNS support. Reconfigure using --with-cgns-dir");
#endif
  PetscFunctionReturn(0);
}
예제 #11
0
int main()
{
    cgsize_t isize[3][3],ipnts[maxcount][3],icounts;
    int index_file,index_base,index_zone,index_bc;
    int ilo,ihi,jlo,jhi,klo,khi;
    int icount,i,j,k;
    char zonename[33];

    printf("\nProgram write_bcpnts_str\n");

/* WRITE BOUNDARY CONDITIONS TO EXISTING CGNS FILE */
/* open CGNS file for modify */
    if (cg_open("grid_c.cgns",CG_MODE_MODIFY,&index_file)) cg_error_exit();
/* we know there is only one base (real working code would check!) */
    index_base=1;
/* we know there is only one zone (real working code would check!) */
    index_zone=1;
/* get zone size (and name - although not needed here) */
    cg_zone_read(index_file,index_base,index_zone,zonename,isize[0]);
    printf("zonename=%s\n",zonename);
    ilo=1;
    ihi=isize[0][0];
    jlo=1;
    jhi=isize[0][1];
    klo=1;
    khi=isize[0][2];
/* write boundary conditions for ilo face, defining pointlist first */
/* (user can give any name) */
    icount=0;
    for (j=jlo; j <= jhi; j++)
    {
      for (k=klo; k <= khi; k++)
      {
        ipnts[icount][0]=ilo;
        ipnts[icount][1]=j;
        ipnts[icount][2]=k;
        icount=icount+1;
      }
    }
    if (icount > maxcount)
    {
      printf("\nError. Need to increase maxcount to at least %i\n",icount);
      return 1;
    }
    icounts=icount;
    cg_boco_write(index_file,index_base,index_zone,"Ilo",BCTunnelInflow,
        PointList,icounts,ipnts[0],&index_bc);
/* write boundary conditions for ihi face, defining pointlist first */
/* (user can give any name) */
    icount=0;
    for (j=jlo; j <= jhi; j++)
    {
      for (k=klo; k <= khi; k++)
      {
        ipnts[icount][0]=ihi;
        ipnts[icount][1]=j;
        ipnts[icount][2]=k;
        icount=icount+1;
      }
    }
    if (icount > maxcount)
    {
      printf("\nError. Need to increase maxcount to at least %i\n",icount);
      return 1;
    }
    icounts=icount;
    cg_boco_write(index_file,index_base,index_zone,"Ihi",BCExtrapolate,
        PointList,icounts,ipnts[0],&index_bc);
/* write boundary conditions for jlo face, defining pointlist first */
/* (user can give any name) */
    icount=0;
    for (i=ilo; i <= ihi; i++)
    {
      for (k=klo; k <= khi; k++)
      {
        ipnts[icount][0]=i;
        ipnts[icount][1]=jlo;
        ipnts[icount][2]=k;
        icount=icount+1;
      }
    }
    if (icount > maxcount)
    {
      printf("\nError. Need to increase maxcount to at least %i\n",icount);
      return 1;
    }
    icounts=icount;
    cg_boco_write(index_file,index_base,index_zone,"Jlo",BCWallInviscid,
        PointList,icounts,ipnts[0],&index_bc);
/* write boundary conditions for jhi face, defining pointlist first */
/* (user can give any name) */
    icount=0;
    for (i=ilo; i <= ihi; i++)
    {
      for (k=klo; k <= khi; k++)
      {
        ipnts[icount][0]=i;
        ipnts[icount][1]=jhi;
        ipnts[icount][2]=k;
        icount=icount+1;
      }
    }
    if (icount > maxcount)
    {
      printf("\nError. Need to increase maxcount to at least %i\n",icount);
      return 1;
    }
    icounts=icount;
    cg_boco_write(index_file,index_base,index_zone,"Jhi",BCWallInviscid,
        PointList,icounts,ipnts[0],&index_bc);
/* write boundary conditions for klo face, defining pointlist first */
/* (user can give any name) */
    icount=0;
    for (i=ilo; i <= ihi; i++)
    {
      for (j=jlo; j <= jhi; j++)
      {
        ipnts[icount][0]=i;
        ipnts[icount][1]=j;
        ipnts[icount][2]=klo;
        icount=icount+1;
      }
    }
    if (icount > maxcount)
    {
      printf("\nError. Need to increase maxcount to at least %i\n",icount);
      return 1;
    }
    icounts=icount;
    cg_boco_write(index_file,index_base,index_zone,"Klo",BCWallInviscid,
        PointList,icounts,ipnts[0],&index_bc);
/* write boundary conditions for khi face, defining pointlist first */
/* (user can give any name) */
    icount=0;
    for (i=ilo; i <= ihi; i++)
    {
      for (j=jlo; j <= jhi; j++)
      {
        ipnts[icount][0]=i;
        ipnts[icount][1]=j;
        ipnts[icount][2]=khi;
        icount=icount+1;
      }
    }
    if (icount > maxcount)
    {
      printf("\nError. Need to increase maxcount to at least %i\n",icount);
      return 1;
    }
    icounts=icount;
    cg_boco_write(index_file,index_base,index_zone,"Khi",BCWallInviscid,
        PointList,icounts,ipnts[0],&index_bc);
/* close CGNS file */
    cg_close(index_file);
    printf("\nSuccessfully added BCs (PointList) to file grid_c.cgns\n");
    return 0;
}
예제 #12
0
int main()
{
    int ilo[2],ihi[2],jlo[2],jhi[2],klo[2],khi[2];
    int itranfrm[3];
    int index_file,index_base,nzone,index_zone,nconns,n1to1,index_conn,iz;
    char donorname[33],zonename0[33],zonename1[33],zn[33];
    cgsize_t isize[3][3],ipnts[2][3],ipntsdonor[2][3];

    printf("\nProgram write_con2zn_str\n");

/* WRITE 1-TO-1 CONNECTIVITY INFORMATION TO EXISTING CGNS FILE */
/* open CGNS file for modify */
    if (cg_open("grid_c.cgns",CG_MODE_MODIFY,&index_file)) cg_error_exit();
/* we know there is only one base (real working code would check!) */
    index_base=1;
/* get number of zones (should be 2 for our case) */
    cg_nzones(index_file,index_base,&nzone);
    if (nzone != 2)
    {
      printf("\nError. This program expects 2 zones. %d read.\n",nzone);
      return 1;
    }

/* loop over zones to get zone sizes and names */
    for (index_zone=0; index_zone < nzone; ++index_zone)
    {
      iz=index_zone+1;
      cg_zone_read(index_file,index_base,iz,zn,isize[0]);
      if (index_zone == 0)
      {
        strcpy(zonename0,zn);
      }
      else
      {
        strcpy(zonename1,zn);
      }
      ilo[index_zone]=1;
      ihi[index_zone]=isize[0][0];
      jlo[index_zone]=1;
      jhi[index_zone]=isize[0][1];
      klo[index_zone]=1;
      khi[index_zone]=isize[0][2];
    }
/* loop over zones again */
    for (index_zone=0; index_zone < nzone; ++index_zone)
    {
      iz=index_zone+1;
/* for this program, there should be no existing connectivity info: */
      cg_nconns(index_file,index_base,iz,&nconns);
      if (nconns != 0)
      {
        printf("\nError. This program expects no interfaces yet. %d read.\n",nconns);
        return 1;
      }
      cg_n1to1(index_file,index_base,iz,&n1to1);
      if (n1to1 != 0)
      {
        printf("\nError. This program expects no interfaces yet. %d read.\n",n1to1);
        return 1;
      }
/* set up index ranges */
      if (index_zone == 0)
      {
        strcpy(donorname,zonename1);
/* lower point of receiver range */
        ipnts[0][0]=ihi[0];
        ipnts[0][1]=jlo[0];
        ipnts[0][2]=klo[0];
/* upper point of receiver range */
        ipnts[1][0]=ihi[0];
        ipnts[1][1]=jhi[0];
        ipnts[1][2]=khi[0];
/* lower point of donor range */
        ipntsdonor[0][0]=ilo[1];
        ipntsdonor[0][1]=jlo[1];
        ipntsdonor[0][2]=klo[1];
/* upper point of donor range */
        ipntsdonor[1][0]=ilo[1];
        ipntsdonor[1][1]=jhi[1];
        ipntsdonor[1][2]=khi[1];
      }
      else
      {
        strcpy(donorname,zonename0);
/* lower point of receiver range */
        ipnts[0][0]=ilo[1];
        ipnts[0][1]=jlo[1];
        ipnts[0][2]=klo[1];
/* upper point of receiver range */
        ipnts[1][0]=ilo[1];
        ipnts[1][1]=jhi[1];
        ipnts[1][2]=khi[1];
/* lower point of donor range */
        ipntsdonor[0][0]=ihi[0];
        ipntsdonor[0][1]=jlo[0];
        ipntsdonor[0][2]=klo[0];
/* upper point of donor range */
        ipntsdonor[1][0]=ihi[0];
        ipntsdonor[1][1]=jhi[0];
        ipntsdonor[1][2]=khi[0];
      }

/* set up Transform */
      itranfrm[0]=1;
      itranfrm[1]=2;
      itranfrm[2]=3;
/* write 1-to-1 info (user can give any name) */
      cg_1to1_write(index_file,index_base,iz,"Interface",donorname,
          ipnts[0],ipntsdonor[0],itranfrm,&index_conn);
    }

/* close CGNS file */
    cg_close(index_file);
    printf("\nSuccessfully added 1-to-1 connectivity info to file grid_c.cgns\n");
    return 0;
}
예제 #13
0
ErrorCode ReadCGNS::load_file(const char* filename,
                              const EntityHandle * /*file_set*/,
                              const FileOptions& opts,
                              const ReaderIface::SubsetList* subset_list,
                              const Tag* file_id_tag)
{
  int num_material_sets = 0;
  const int* material_set_list = 0;

  if (subset_list) {
    if (subset_list->tag_list_length > 1 &&
        !strcmp(subset_list->tag_list[0].tag_name, MATERIAL_SET_TAG_NAME)) {
      MB_SET_ERR(MB_UNSUPPORTED_OPERATION, "CGNS supports subset read only by material ID");
    }
    material_set_list = subset_list->tag_list[0].tag_values;
    num_material_sets = subset_list->tag_list[0].num_tag_values;
  }

  ErrorCode result;

  geomSets.clear();
  result = mbImpl->tag_get_handle(GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER,
                                  globalId, MB_TAG_DENSE | MB_TAG_CREAT, 0);
  if (MB_SUCCESS != result)
    return result;

  // Create set for more convienient check for material set ids
  std::set<int> blocks;
  for (const int* mat_set_end = material_set_list + num_material_sets;
       material_set_list != mat_set_end; ++material_set_list)
    blocks.insert(*material_set_list);

  // Map of ID->handle for nodes
  std::map<long, EntityHandle> node_id_map;

  // Save filename to member variable so we don't need to pass as an argument
  // to called functions
  fileName = filename;

  // Process options; see src/FileOptions.hpp for API for FileOptions class, and doc/metadata_info.doc for
  // a description of various options used by some of the readers in MOAB
  result = process_options(opts);MB_CHK_SET_ERR(result, fileName << ": problem reading options");

  // Open file
  int filePtr = 0;

  cg_open(filename, CG_MODE_READ, &filePtr);

  if (filePtr <= 0) {
    MB_SET_ERR(MB_FILE_DOES_NOT_EXIST, fileName << ": fopen returned error");
  }

  // Read number of verts, elements, sets
  long num_verts = 0, num_elems = 0, num_sets = 0;
  int num_bases = 0, num_zones = 0, num_sections = 0;

  char zoneName[128];
  cgsize_t size[3];

  mesh_dim = 3; // Default to 3D

  // Read number of bases;
  cg_nbases(filePtr, &num_bases);

  if (num_bases > 1) {
    MB_SET_ERR(MB_NOT_IMPLEMENTED, fileName << ": support for number of bases > 1 not implemented");
  }

  for (int indexBase = 1; indexBase <= num_bases; ++indexBase) {
    // Get the number of zones/blocks in current base.
    cg_nzones(filePtr, indexBase, &num_zones);

    if (num_zones > 1) {
      MB_SET_ERR(MB_NOT_IMPLEMENTED, fileName << ": support for number of zones > 1 not implemented");
    }

    for (int indexZone = 1; indexZone <= num_zones; ++indexZone) {
      // Get zone name and size.
      cg_zone_read(filePtr, indexBase, indexZone, zoneName, size);

      // Read number of sections/Parts in current zone.
      cg_nsections(filePtr, indexBase, indexZone, &num_sections);

      num_verts = size[0];
      num_elems = size[1];
      num_sets = num_sections;

      std::cout << "\nnumber of nodes = " << num_verts;
      std::cout << "\nnumber of elems = " << num_elems;
      std::cout << "\nnumber of parts = " << num_sets << std::endl;

      // //////////////////////////////////
      // Read Nodes

      // Allocate nodes; these are allocated in one shot, get contiguous handles starting with start_handle,
      // and the reader is passed back double*'s pointing to MOAB's native storage for vertex coordinates
      // for those verts
      std::vector<double*> coord_arrays;
      EntityHandle handle = 0;
      result = readMeshIface->get_node_coords(3, num_verts, MB_START_ID, handle,
                                              coord_arrays);MB_CHK_SET_ERR(result, fileName << ": Trouble reading vertices");

      // Fill in vertex coordinate arrays
      cgsize_t beginPos = 1, endPos = num_verts;

      // Read nodes coordinates.
      cg_coord_read(filePtr, indexBase, indexZone, "CoordinateX",
                    RealDouble, &beginPos, &endPos, coord_arrays[0]);
      cg_coord_read(filePtr, indexBase, indexZone, "CoordinateY",
                    RealDouble, &beginPos, &endPos, coord_arrays[1]);
      cg_coord_read(filePtr, indexBase, indexZone, "CoordinateZ",
                    RealDouble, &beginPos, &endPos, coord_arrays[2]);

      // CGNS seems to always include the Z component, even if the mesh is 2D.
      // Check if Z is zero and determine mesh dimension.
      // Also create the node_id_map data.
      double sumZcoord = 0.0;
      double eps = 1.0e-12;
      for (long i = 0; i < num_verts; ++i, ++handle) {
        int index = i + 1;

        node_id_map.insert(std::pair<long, EntityHandle>(index, handle)).second;

        sumZcoord += *(coord_arrays[2] + i);
      }
      if (std::abs(sumZcoord) <= eps) mesh_dim = 2;

      // Create reverse map from handle to id
      std::vector<int> ids(num_verts);
      std::vector<int>::iterator id_iter = ids.begin();
      std::vector<EntityHandle> handles(num_verts);
      std::vector<EntityHandle>::iterator h_iter = handles.begin();
      for (std::map<long, EntityHandle>::iterator i = node_id_map.begin();
          i != node_id_map.end(); ++i, ++id_iter, ++h_iter) {
        *id_iter = i->first;
        * h_iter = i->second;
      }
      // Store IDs in tags
      result = mbImpl->tag_set_data(globalId, &handles[0], num_verts, &ids[0]);
      if (MB_SUCCESS != result)
        return result;
      if (file_id_tag) {
        result = mbImpl->tag_set_data(*file_id_tag, &handles[0], num_verts, &ids[0]);
        if (MB_SUCCESS != result)
          return result;
      }
      ids.clear();
      handles.clear();

      // //////////////////////////////////
      // Read elements data

      EntityType ent_type;

      long section_offset = 0;

      // Define which mesh parts are volume families.
      // Mesh parts with volumeID[X] = 0 are boundary parts.
      std::vector<int> volumeID(num_sections, 0);

      for (int section = 0; section < num_sections; ++section) {
        ElementType_t elemsType;
        int iparent_flag, nbndry;
        char sectionName[128];
        int verts_per_elem;

        int cgSection = section + 1;

        cg_section_read(filePtr, indexBase, indexZone, cgSection, sectionName,
                        &elemsType, &beginPos, &endPos, &nbndry, &iparent_flag);

        size_t section_size = endPos - beginPos + 1;

        // Read element description in current section

        switch (elemsType) {
          case BAR_2:
            ent_type = MBEDGE;
            verts_per_elem = 2;
            break;
          case TRI_3:
            ent_type = MBTRI;
            verts_per_elem = 3;
            if (mesh_dim == 2)
              volumeID[section] = 1;
            break;
          case QUAD_4:
            ent_type = MBQUAD;
            verts_per_elem = 4;
            if (mesh_dim == 2)
              volumeID[section] = 1;
            break;
          case TETRA_4:
            ent_type = MBTET;
            verts_per_elem = 4;
            if (mesh_dim == 3)
              volumeID[section] = 1;
              break;
          case PYRA_5:
            ent_type = MBPYRAMID;
            verts_per_elem = 5;
            if (mesh_dim == 3) volumeID[section] = 1;
              break;
          case PENTA_6:
            ent_type = MBPRISM;
            verts_per_elem = 6;
            if (mesh_dim == 3) volumeID[section] = 1;
              break;
          case HEXA_8:
            ent_type = MBHEX;
            verts_per_elem = 8;
            if (mesh_dim == 3) volumeID[section] = 1;
            break;
          case MIXED:
            ent_type = MBMAXTYPE;
            verts_per_elem = 0;
            break;
          default:
            MB_SET_ERR(MB_INDEX_OUT_OF_RANGE, fileName << ": Trouble determining element type");
        }

        if (elemsType == TETRA_4 || elemsType == PYRA_5 || elemsType == PENTA_6 || elemsType == HEXA_8 ||
            elemsType == TRI_3   || elemsType == QUAD_4 || ((elemsType == BAR_2) && mesh_dim == 2)) {
          // Read connectivity into conn_array directly

          cgsize_t iparentdata;
          cgsize_t connDataSize;

          // Get number of entries on the connectivity list for this section
          cg_ElementDataSize(filePtr, indexBase, indexZone, cgSection, &connDataSize);

          // Need a temporary vector to later cast to conn_array.
          std::vector<cgsize_t> elemNodes(connDataSize);

          cg_elements_read(filePtr, indexBase, indexZone, cgSection, &elemNodes[0], &iparentdata);

          // //////////////////////////////////
          // Create elements, sets and tags

          create_elements(sectionName, file_id_tag,
                          ent_type, verts_per_elem, section_offset, section_size , elemNodes);
        } // Homogeneous mesh type
        else if (elemsType == MIXED) {
          // We must first sort all elements connectivities into continuous vectors

          cgsize_t connDataSize;
          cgsize_t iparentdata;

          cg_ElementDataSize(filePtr, indexBase, indexZone, cgSection, &connDataSize);

          std::vector< cgsize_t > elemNodes(connDataSize);

          cg_elements_read(filePtr, indexBase, indexZone, cgSection, &elemNodes[0], &iparentdata);

          std::vector<cgsize_t> elemsConn_EDGE;
          std::vector<cgsize_t> elemsConn_TRI, elemsConn_QUAD;
          std::vector<cgsize_t> elemsConn_TET, elemsConn_PYRA, elemsConn_PRISM, elemsConn_HEX;
          cgsize_t count_EDGE, count_TRI, count_QUAD;
          cgsize_t count_TET, count_PYRA, count_PRISM, count_HEX;

          // First, get elements count for current section

          count_EDGE = count_TRI = count_QUAD = 0;
          count_TET = count_PYRA = count_PRISM = count_HEX = 0;

          int connIndex = 0;
          for (int i = beginPos; i <= endPos; i++) {
            elemsType = ElementType_t(elemNodes[connIndex]);

            // Get current cell node count.
            cg_npe(elemsType, &verts_per_elem);

            switch (elemsType) {
              case BAR_2:
                count_EDGE += 1;
                break;
              case TRI_3:
                count_TRI += 1;
                break;
              case QUAD_4:
                count_QUAD += 1;
                break;
              case TETRA_4:
                count_TET += 1;
                break;
              case PYRA_5:
                count_PYRA += 1;
                break;
              case PENTA_6:
                count_PRISM += 1;
                break;
              case HEXA_8:
                count_HEX += 1;
                break;
              default:
                MB_SET_ERR(MB_INDEX_OUT_OF_RANGE, fileName << ": Trouble determining element type");
            }

            connIndex += (verts_per_elem + 1); // Add one to skip next element descriptor
          }

          if (count_EDGE  > 0) elemsConn_EDGE.resize(count_EDGE * 2);
          if (count_TRI   > 0) elemsConn_TRI.resize(count_TRI * 3);
          if (count_QUAD  > 0) elemsConn_QUAD.resize(count_QUAD * 4);
          if (count_TET   > 0) elemsConn_TET.resize(count_TET * 4);
          if (count_PYRA  > 0) elemsConn_PYRA.resize(count_PYRA * 5);
          if (count_PRISM > 0) elemsConn_PRISM.resize(count_PRISM * 6);
          if (count_HEX   > 0) elemsConn_HEX.resize(count_HEX * 8);

          // Grab mixed section elements connectivity

          int idx_edge, idx_tri, idx_quad;
          int idx_tet, idx_pyra, idx_prism, idx_hex;
          idx_edge = idx_tri = idx_quad = 0;
          idx_tet = idx_pyra = idx_prism = idx_hex = 0;

          connIndex = 0;
          for (int i = beginPos; i <= endPos; i++) {
            elemsType = ElementType_t(elemNodes[connIndex]);

            // Get current cell node count.
            cg_npe(elemsType, &verts_per_elem);

            switch (elemsType) {
              case BAR_2:
                for (int j = 0; j < 2; ++j)
                  elemsConn_EDGE[idx_edge + j] = elemNodes[connIndex + j + 1];
                idx_edge += 2;
                break;
              case TRI_3:
                for (int j = 0; j < 3; ++j)
                  elemsConn_TRI[idx_tri + j] = elemNodes[connIndex + j + 1];
                idx_tri += 3;
                break;
              case QUAD_4:
                for (int j = 0; j < 4; ++j)
                  elemsConn_QUAD[idx_quad + j] = elemNodes[connIndex + j + 1];
                idx_quad += 4;
                break;
              case TETRA_4:
                for (int j = 0; j < 4; ++j)
                  elemsConn_TET[idx_tet + j] = elemNodes[connIndex + j + 1];
                idx_tet += 4;
                break;
              case PYRA_5:
                for (int j = 0; j < 5; ++j)
                  elemsConn_PYRA[idx_pyra + j] = elemNodes[connIndex + j + 1];
                idx_pyra += 5;
                break;
              case PENTA_6:
                for (int j = 0; j < 6; ++j)
                  elemsConn_PRISM[idx_prism + j] = elemNodes[connIndex + j + 1];
                idx_prism += 6;
                break;
              case HEXA_8:
                for (int j = 0; j < 8; ++j)
                  elemsConn_HEX[idx_hex + j] = elemNodes[connIndex + j + 1];
                idx_hex += 8;
                break;
              default:
                MB_SET_ERR(MB_INDEX_OUT_OF_RANGE, fileName << ": Trouble determining element type");
            }

            connIndex += (verts_per_elem + 1); // Add one to skip next element descriptor
          }

          // //////////////////////////////////
          // Create elements, sets and tags

          if (count_EDGE > 0)
            create_elements(sectionName, file_id_tag, MBEDGE, 2, section_offset, count_EDGE, elemsConn_EDGE);

          if (count_TRI > 0)
            create_elements(sectionName, file_id_tag, MBTRI, 3, section_offset, count_TRI, elemsConn_TRI);

          if (count_QUAD > 0)
            create_elements(sectionName, file_id_tag, MBQUAD, 4, section_offset, count_QUAD, elemsConn_QUAD);

          if (count_TET > 0)
            create_elements(sectionName, file_id_tag, MBTET, 4, section_offset, count_TET, elemsConn_TET);

          if (count_PYRA > 0)
            create_elements(sectionName, file_id_tag, MBPYRAMID, 5, section_offset, count_PYRA, elemsConn_PYRA);

          if (count_PRISM > 0)
            create_elements(sectionName, file_id_tag, MBPRISM, 6, section_offset, count_PRISM, elemsConn_PRISM);

          if (count_HEX > 0)
            create_elements(sectionName, file_id_tag, MBHEX, 8, section_offset, count_HEX, elemsConn_HEX);
        } // Mixed mesh type
      } // num_sections

      cg_close(filePtr);

      return result;
    } // indexZone for
  } // indexBase for

  return MB_SUCCESS;
}