Ejemplo n.º 1
0
int ex_inquire (int   exoid,
                int   req_info,
                int  *ret_int,
                void *ret_float,
                char *ret_char)
{
   int dimid, varid, i, tmp_num, *ids;
   long ldum, num_sets, start[2], count[2];
   nclong *stat_vals;
   char  errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

   switch (req_info)
   {
     case EX_INQ_FILE_TYPE:

       /* obsolete call */
       /*returns "r" for regular EXODUS II file or "h" for history EXODUS file*/

       *ret_char = '\0';
       exerrval = EX_BADPARAM;
       sprintf(errmsg,
              "Warning: file type inquire is obsolete");
       ex_err("ex_inquire",errmsg,exerrval);
       return (EX_WARN);

     case EX_INQ_API_VERS:

/*     returns the EXODUS II API version number */

       if (ncattget (exoid, NC_GLOBAL, ATT_API_VERSION, ret_float) == -1)
       {  /* try old (prior to db version 2.02) attribute name */
         if (ncattget (exoid, NC_GLOBAL, ATT_API_VERSION_BLANK,ret_float) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
             "Error: failed to get EXODUS API version for file id %d", exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }
       }

       break;

     case EX_INQ_DB_VERS:

/*     returns the EXODUS II database version number */

       if (ncattget (exoid, NC_GLOBAL, ATT_VERSION, ret_float) == -1)
       {
         exerrval = ncerr;
         sprintf(errmsg,
          "Error: failed to get EXODUS database version for file id %d", exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }

       break;

     case EX_INQ_LIB_VERS:

/*     returns the EXODUS II Library version number */

       flt_cvt((float *)ret_float, EX_API_VERS);

       break;

     case EX_INQ_TITLE:

/*     returns the title of the database */

       if (ncattget (exoid, NC_GLOBAL, ATT_TITLE, ret_char) == -1)
       {
         *ret_char = '\0';
         exerrval = ncerr;
         sprintf(errmsg,
             "Error: failed to get database title for file id %d", exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }

       break;

     case EX_INQ_DIM:

/*     returns the dimensionality (2 or 3, for 2-d or 3-d) of the database */

       if ((dimid = ncdimid (exoid, DIM_NUM_DIM)) == -1)
       {
         *ret_int = 0;
         exerrval = ncerr;
         sprintf(errmsg,
                "Error: failed to locate database dimensionality in file id %d",
                exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }

       if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
       {
         *ret_int = 0;
         exerrval = ncerr;
         sprintf(errmsg,
            "Error: failed to get database dimensionality for file id %d",
            exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }
       *ret_int = ldum;

       break;

     case EX_INQ_NODES:

/*     returns the number of nodes */

       if ((dimid = ncdimid (exoid, DIM_NUM_NODES)) == -1)
       {
         *ret_int = 0;
       } else {

         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
                     "Error: failed to get number of nodes for file id %d",
                     exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             return (EX_FATAL);
           }
         *ret_int = ldum;
       }
       break;

     case EX_INQ_ELEM:

/*     returns the number of elements */

       if ((dimid = ncdimid (exoid, DIM_NUM_ELEM)) == -1)
       {
         *ret_int = 0;
       } else {

         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
                     "Error: failed to get number of elements for file id %d",
                     exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             return (EX_FATAL);
           }
         *ret_int = ldum;
       }
       break;

     case EX_INQ_ELEM_BLK:

/*     returns the number of element blocks */

       if ((dimid = ncdimid (exoid, DIM_NUM_EL_BLK)) == -1)
       {
         *ret_int = 0;
       } else {

         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
                     "Error: failed to get number of element blocks for file id %d",
                     exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             return (EX_FATAL);
           }
         *ret_int = ldum;
       }

       break;

     case EX_INQ_NODE_SETS:

/*     returns the number of node sets */

       if ((dimid = ncdimid (exoid, DIM_NUM_NS)) < 0)
         *ret_int = 0;      /* no node sets defined */
       else
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
         {
           *ret_int = 0;
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of node sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }
         *ret_int = ldum;
       }

       break;

     case EX_INQ_NS_NODE_LEN:

/*     returns the length of the concatenated node sets node list */

       *ret_int = 0;       /* default value if no node sets are defined */
       if ((dimid = ncdimid (exoid, DIM_NUM_NS)) != -1 )
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &num_sets) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of node sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }


         if (!(ids =  malloc(num_sets*sizeof(int))))
         {
           exerrval = EX_MEMFAIL;
           sprintf(errmsg,
             "Error: failed to allocate memory for node set ids for file id %d",
              exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         if (ex_get_node_set_ids (exoid, ids) == EX_FATAL)
         {
           sprintf(errmsg,
                   "Error: failed to get node sets in file id %d",
                    exoid);
           /* pass back error code from ex_get_node_set_ids (in exerrval) */
           ex_err("ex_inquire",errmsg,exerrval);
           free (ids);
           return (EX_FATAL);
         }
         /* allocate space for stat array */
         if (!(stat_vals = malloc((int)num_sets*sizeof(nclong))))
         {
           exerrval = EX_MEMFAIL;
           free (ids);
           sprintf(errmsg,
    "Error: failed to allocate memory for node set status array for file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         /* get variable id of status array */
         if ((varid = ncvarid (exoid, VAR_NS_STAT)) != -1)
         {
         /* if status array exists, use it, otherwise assume, object exists
            to be backward compatible */

           start[0] = 0;
           start[1] = 0;
           count[0] = num_sets;
           count[1] = 0;

           if (ncvarget (exoid, varid, start, count, (void *)stat_vals) == -1)
           {
             exerrval = ncerr;
             free (ids);
             free(stat_vals);
             sprintf(errmsg,
                   "Error: failed to get node set status array from file id %d",
                     exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             return (EX_FATAL);
           }
         }
         else /* default: status is true */
           for(i=0;i<num_sets;i++)
             stat_vals[i]=1;

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

           if (stat_vals[i] == 0) /* is this object null? */
              continue;

           if ((dimid = ncdimid (exoid, DIM_NUM_NOD_NS(i+1))) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
         "Error: failed to locate number of nodes in node set %d in file id %d",
                  ids[i],exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             free (ids);
             free (stat_vals);
             return (EX_FATAL);
           }

           if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
            "Error: failed to get number of nodes in node set %d in file id %d",
                  ids[i],exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             free (stat_vals);
             free (ids);
             return (EX_FATAL);
           }

           *ret_int += ldum;
         }

         free (stat_vals);
         free (ids);
       }

       break;

     case EX_INQ_NS_DF_LEN:

/*     returns the length of the concatenated node sets dist factor list */

/*
     Determine the concatenated node sets distribution factor length:

        1. Get the node set ids list.
        2. Check see if the dist factor variable for a node set id exists.
        3. If it exists, goto step 4, else the length is zero.
        4. Get the dimension of the number of nodes in the node set -0
             use this value as the length as by definition they are the same.
        5. Sum the individual lengths for the total list length.
*/

       *ret_int = 0;    /* default value if no node sets defined */

       if ((dimid = ncdimid (exoid, DIM_NUM_NS))  != -1)
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &num_sets) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of node sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }


         if (!(ids = malloc(num_sets*sizeof(int))))
         {
           exerrval = EX_MEMFAIL;
           sprintf(errmsg,
             "Error: failed to allocate memory for node set ids for file id %d",
              exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         if (ex_get_node_set_ids (exoid, ids) == EX_FATAL)
         {
           sprintf(errmsg,
                   "Error: failed to get node sets in file id %d",
                    exoid);
           /* pass back error code from ex_get_node_set_ids (in exerrval) */
           ex_err("ex_inquire",errmsg,exerrval);
           free (ids);
           return (EX_FATAL);
         }

         for (i=0; i<num_sets; i++)
         {
           if (ncvarid (exoid, VAR_FACT_NS(i+1)) == -1)
           {
             if (ncerr == NC_ENOTVAR)
             {
               ldum = 0;        /* this dist factor doesn't exist */
             }
             else
             {
               *ret_int = 0;
               exerrval = ncerr;
               sprintf(errmsg,
    "Error: failed to locate number of dist fact for node set %d in file id %d",
                        ids[i], exoid);
               ex_err("ex_inquire",errmsg,exerrval);
               free (ids);
               return (EX_FATAL);
             }
           }
           else
           {
             if ((dimid = ncdimid (exoid, DIM_NUM_NOD_NS(i+1))) == -1)
             {
               *ret_int = 0;
               exerrval = ncerr;
               sprintf(errmsg,
         "Error: failed to locate number of nodes in node set %d in file id %d",
                       ids[i], exoid);
               ex_err("ex_inquire",errmsg,exerrval);
               free (ids);
               return (EX_FATAL);
             }
             if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
             {
               *ret_int = 0;
               exerrval = ncerr;
               sprintf(errmsg,
            "Error: failed to get number of nodes in node set %d in file id %d",
                       ids[i],exoid);
               ex_err("ex_inquire",errmsg,exerrval);
               free(ids);
               return (EX_FATAL);
             }
           }
           *ret_int += ldum;
         }
         free(ids);
       }

       break;

     case EX_INQ_SIDE_SETS:

/*     returns the number of side sets */

       *ret_int = 0;     /* default return value */

       if ((dimid = ncdimid (exoid, DIM_NUM_SS)) != -1)
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of side sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }
         *ret_int = ldum;
       }

       break;

     case EX_INQ_SS_NODE_LEN:

/*     returns the length of the concatenated side sets node list */

       *ret_int = 0;     /* default return value */

       if ((dimid = ncdimid (exoid, DIM_NUM_SS)) != -1)
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &num_sets) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of side sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }


         if (!(ids = malloc(num_sets*sizeof(int))))
         {
           exerrval = EX_MEMFAIL;
           sprintf(errmsg,
             "Error: failed to allocate memory for side set ids for file id %d",
              exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         if (ex_get_side_set_ids (exoid, ids) == EX_FATAL)
         {
           sprintf(errmsg,
                  "Error: failed to get side set ids in file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           free(ids);
           return (EX_FATAL);
         }

         /* allocate space for stat array */
         if (!(stat_vals = malloc((int)num_sets*sizeof(nclong))))
         {
           exerrval = EX_MEMFAIL;
           free (ids);
           sprintf(errmsg,
    "Error: failed to allocate memory for side set status array for file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }
         /* get variable id of status array */
         if ((varid = ncvarid (exoid, VAR_SS_STAT)) != -1)
         {
         /* if status array exists, use it, otherwise assume, object exists
            to be backward compatible */

           start[0] = 0;
           start[1] = 0;
           count[0] = num_sets;
           count[1] = 0;

           if (ncvarget (exoid, varid, start, count, (void *)stat_vals) == -1)
           {
             exerrval = ncerr;
             free (ids);
             free(stat_vals);
             sprintf(errmsg,
             "Error: failed to get element block status array from file id %d",
                     exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             return (EX_FATAL);
           }
         }
         else /* default: status is true */
           for(i=0;i<num_sets;i++)
             stat_vals[i]=1;

         /* walk id list, get each side set node length and sum for total */

         for (i=0; i<num_sets; i++)
         {
           if (stat_vals[i] == 0) /* is this object null? */
             continue;

           if (ex_get_side_set_node_list_len(exoid, ids[i], &tmp_num) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
                 "Error: failed to side set %d node length in file id %d",
                  ids[i],exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             free(stat_vals);
             free(ids);
             return (EX_FATAL);
           }
           *ret_int += tmp_num;
         }

         free(stat_vals);
         free (ids);
       }

       break;

     case EX_INQ_SS_ELEM_LEN:

/*     returns the length of the concatenated side sets element list */

       *ret_int = 0;     /* default return value */

       if ((dimid = ncdimid (exoid, DIM_NUM_SS)) != -1)
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &num_sets) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of side sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }


         if (!(ids = malloc(num_sets*sizeof(int))))
         {
           exerrval = EX_MEMFAIL;
           sprintf(errmsg,
             "Error: failed to allocate memory for side set ids for file id %d",
              exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         if (ex_get_side_set_ids (exoid, ids) == EX_FATAL)
         {
           sprintf(errmsg,
                  "Error: failed to get side set ids in file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           free(ids);
           return (EX_FATAL);
         }

         /* allocate space for stat array */
         if (!(stat_vals = malloc((int)num_sets*sizeof(nclong))))
         {
           exerrval = EX_MEMFAIL;
           free (ids);
           sprintf(errmsg,
    "Error: failed to allocate memory for side set status array for file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         /* get variable id of status array */
         if ((varid = ncvarid (exoid, VAR_SS_STAT)) != -1)
         {
         /* if status array exists, use it, otherwise assume, object exists
            to be backward compatible */

           start[0] = 0;
           start[1] = 0;
           count[0] = num_sets;
           count[1] = 0;

           if (ncvarget (exoid, varid, start, count, (void *)stat_vals) == -1)
           {
             exerrval = ncerr;
             free (ids);
             free(stat_vals);
             sprintf(errmsg,
             "Error: failed to get element block status array from file id %d",
                     exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             return (EX_FATAL);
           }
         }
         else /* default: status is true */
           for(i=0;i<num_sets;i++)
             stat_vals[i]=1;

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

           if (stat_vals[i] == 0) /* is this object null? */
              continue;

           if ((dimid = ncdimid (exoid, DIM_NUM_SIDE_SS(i+1))) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
                 "Error: failed to locate side set %d in file id %d",
                  ids[i],exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             free(stat_vals);
             free(ids);
             return (EX_FATAL);
           }

           if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
           {
             *ret_int = 0;
             exerrval = ncerr;
             sprintf(errmsg,
                 "Error: failed to get size of side set %d in file id %d",
                  ids[i], exoid);
             ex_err("ex_inquire",errmsg,exerrval);
             free(stat_vals);
             free(ids);
             return (EX_FATAL);
           }

           *ret_int += ldum;
         }

         free(stat_vals);
         free (ids);
       }

       break;

     case EX_INQ_SS_DF_LEN:

/*     returns the length of the concatenated side sets dist factor list */

/*
     Determine the concatenated side sets distribution factor length:

        1. Get the side set ids list.
        2. Check see if the dist factor dimension for a side set id exists.
        3. If it exists, goto step 4, else set the individual length to zero.
        4. Sum the dimension value into the running total length.
*/

       *ret_int = 0;

       /* first check see if any side sets exist */

       if ((dimid = ncdimid (exoid, DIM_NUM_SS))  != -1)
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &num_sets) == -1)
         {
           exerrval = ncerr;
           sprintf(errmsg,
                 "Error: failed to get number of side sets in file id %d",
                  exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }


         if (!(ids = malloc(num_sets*sizeof(int))))
         {
           exerrval = EX_MEMFAIL;
           sprintf(errmsg,
             "Error: failed to allocate memory for side set ids for file id %d",
              exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }

         if (ex_get_side_set_ids (exoid, ids) == EX_FATAL)
         {
           sprintf(errmsg,
                   "Error: failed to get side sets in file id %d",
                    exoid);
           /* pass back error code from ex_get_side_set_ids (in exerrval) */
           ex_err("ex_inquire",errmsg,exerrval);
           free (ids);
           return (EX_FATAL);
         }

         for (i=0; i<num_sets; i++)
         {
           if ((dimid = ncdimid (exoid, DIM_NUM_DF_SS(i+1))) == -1)
           {
             if (ncerr == NC_EBADDIM)
             {
               ldum = 0;        /* this dist factor doesn't exist */
             }
             else
             {
               *ret_int = 0;
               exerrval = ncerr;
               sprintf(errmsg,
    "Error: failed to locate number of dist fact for side set %d in file id %d",
                        ids[i], exoid);
               ex_err("ex_inquire",errmsg,exerrval);
               free (ids);
               return (EX_FATAL);
             }
           }
           else
           {
             if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
             {
               *ret_int = 0;
               exerrval = ncerr;
               sprintf(errmsg,
     "Error: failed to get number of dist factors in side set %d in file id %d",
                       ids[i], exoid);
               ex_err("ex_inquire",errmsg,exerrval);
               free (ids);
               return (EX_FATAL);
             }
           }
           *ret_int += ldum;
         }
         free (ids);
       }

       break;

     case EX_INQ_QA:

/*     returns the number of QA records */

       if ((dimid = ncdimid (exoid, DIM_NUM_QA)) < 0)
         *ret_int = 0;      /* no QA records stored */
       else
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
         {
           *ret_int = 0;
           exerrval = ncerr;
           sprintf(errmsg,
                  "Error: failed to get number of QA records in file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }
         *ret_int = ldum;
       }

       break;

     case EX_INQ_INFO:

/*     returns the number of information records */

       if ((dimid = ncdimid (exoid, DIM_NUM_INFO)) < 0)
         *ret_int = 0;        /* no information records stored */
       else
       {
         if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
         {
           *ret_int = 0;
           exerrval = ncerr;
           sprintf(errmsg,
                  "Error: failed to get number of info records in file id %d",
                   exoid);
           ex_err("ex_inquire",errmsg,exerrval);
           return (EX_FATAL);
         }
         *ret_int = ldum;
       }
       break;

     case EX_INQ_TIME:

/*     returns the number of time steps stored in the database; we find 
 *     this out by inquiring the maximum record number of the "unlimited" 
 *     dimension
 */

       if ((dimid = ncdimid (exoid, DIM_TIME)) == -1)
       {
         *ret_int = 0;
         exerrval = ncerr;
         sprintf(errmsg,
                "Error: failed to locate time dimension in file id %d", exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }

       if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
       {
         *ret_int = 0;
         exerrval = ncerr;
         sprintf(errmsg,
                "Error: failed to get time dimension in file id %d",
                 exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }
       *ret_int = ldum;

       break;
     case EX_INQ_EB_PROP:

/*     returns the number of element block properties */

       *ret_int = ex_get_num_props (exoid, EX_ELEM_BLOCK);
       break;

     case EX_INQ_NS_PROP:

/*     returns the number of node set properties */

       *ret_int = ex_get_num_props (exoid, EX_NODE_SET);
       break;

     case EX_INQ_SS_PROP:

/*     returns the number of side set properties */

       *ret_int = ex_get_num_props (exoid, EX_SIDE_SET);
       break;

     case EX_INQ_ELEM_MAP:

/*     returns the number of element maps */

       if ((dimid = ncdimid (exoid, DIM_NUM_EM)) == -1)
       {
         /* no element maps so return 0 */

         *ret_int = 0;
         return (EX_NOERR);
       }

       if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
       {
         *ret_int = 0;
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to get number of element maps for file id %d",
           exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }
       *ret_int = ldum;

       break;

     case EX_INQ_EM_PROP:

/*     returns the number of element map properties */

       *ret_int = ex_get_num_props (exoid, EX_ELEM_MAP);
       break;

     case EX_INQ_NODE_MAP:

/*     returns the number of node maps */

       if ((dimid = ncdimid (exoid, DIM_NUM_NM)) == -1)
       {
         /* no node maps so return 0 */

         *ret_int = 0;
         return (EX_NOERR);
       }

       if (ncdiminq (exoid, dimid, (char *) 0, &ldum) == -1)
       {
         *ret_int = 0;
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to get number of node maps for file id %d",
           exoid);
         ex_err("ex_inquire",errmsg,exerrval);
         return (EX_FATAL);
       }
       *ret_int = ldum;

       break;

     case EX_INQ_NM_PROP:

/*     returns the number of element map properties */

       *ret_int = ex_get_num_props (exoid, EX_NODE_MAP);
       break;


     default:
       *ret_int = 0;
       exerrval = EX_FATAL;
       sprintf(errmsg, "Error: invalid inquiry %d", req_info);
       ex_err("ex_inquire",errmsg,exerrval);
       return(EX_FATAL);
   }
   return (EX_NOERR);
}
Ejemplo n.º 2
0
void update_netcdfs(void)
{
    int i, j;
    char buf[256], fname[512];
    XmString xms;
    int cdfid; /* netCDF id */
    int ndims, nvars, ngatts, recdim;
    int var_id;
    long start[2];
    long count[2];
    char varname[256];
    nc_type datatype = 0;
    int dim[100], natts;
    long dimlen[100];
    long len;
    extern int ncopts;

    ncopts = 0; /* no crash on error */

    if (netcdf_frame != NULL)
    {
        strcpy(fname, xv_getstr(netcdf_file_item));
        set_wait_cursor();
        XmListDeleteAllItems(netcdf_listx_item);
        XmListDeleteAllItems(netcdf_listy_item);
        xms = XmStringCreateLtoR("INDEX", charset);
        XmListAddItemUnselected(netcdf_listx_item, xms, 0);
        XmStringFree(xms);

        if (strlen(fname) < 2)
        {
            unset_wait_cursor();
            return;
        }
        if ((cdfid = ncopen(fname, NC_NOWRITE)) == -1)
        {
            errwin("Can't open file.");
            unset_wait_cursor();
            return;
        }
        ncinquire(cdfid, &ndims, &nvars, &ngatts, &recdim);
        /*
          printf("%d %d %d %d\n", ndims, nvars, ngatts, recdim);
      */
        for (i = 0; i < ndims; i++)
        {
            ncdiminq(cdfid, i, NULL, &dimlen[i]);
        }
        for (i = 0; i < nvars; i++)
        {
            ncvarinq(cdfid, i, varname, &datatype, &ndims, dim, &natts);
            if ((var_id = ncvarid(cdfid, varname)) == -1)
            {
                char ebuf[256];
                sprintf(ebuf, "update_netcdfs(): No such variable %s", varname);
                errwin(ebuf);
                continue;
            }
            if (ndims != 1)
            {
                continue;
            }
            ncdiminq(cdfid, dim[0], (char *)NULL, &len);
            sprintf(buf, "%s", varname);
            xms = XmStringCreateLtoR(buf, charset);
            XmListAddItemUnselected(netcdf_listx_item, xms, 0);
            XmListAddItemUnselected(netcdf_listy_item, xms, 0);
            XmStringFree(xms);
        }
        ncclose(cdfid);
        unset_wait_cursor();
    }
}
Ejemplo n.º 3
0
int ex_get_side_set_dist_fact (int   exoid,
                               int   side_set_id,
                               void *side_set_dist_fact)
{

    int dimid, dist_id, side_set_id_ndx;
    long num_df_in_set, count[1], start[1];
    char errmsg[MAX_ERR_LENGTH];

    exerrval = 0; /* clear error code */

    /* first check if any side sets are specified */

    if ((dimid = ncdimid (exoid, DIM_NUM_SS)) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Warning: no side sets stored in file id %d",
                exoid);
        ex_err("ex_get_side_set_dist_fact",errmsg,exerrval);
        return (EX_WARN);
    }

    /* Lookup index of side set id in VAR_SS_IDS array */

    side_set_id_ndx = ex_id_lkup(exoid,VAR_SS_IDS,side_set_id);
    if (exerrval != 0)
    {
        if (exerrval == EX_NULLENTITY)
        {
            sprintf(errmsg,
                    "Warning: side set %d is NULL in file id %d",
                    side_set_id,exoid);
            ex_err("ex_get_side_set_dist_fact",errmsg,EX_MSG);
            return (EX_WARN);
        }
        else
        {
            sprintf(errmsg,
                    "Error: failed to locate side set id %d in VAR_SS_IDS array in file id %d",
                    side_set_id,exoid);
            ex_err("ex_get_side_set_dist_fact",errmsg,exerrval);
            return (EX_FATAL);
        }
    }

    /* inquire id's of previously defined dimensions and variables */

    if ((dimid = ncdimid (exoid, DIM_NUM_DF_SS(side_set_id_ndx))) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Warning: dist factors not stored for side set %d in file id %d",
                side_set_id,exoid);
        ex_err("ex_get_side_set_dist_fact",errmsg,exerrval);
        return (EX_WARN);          /* complain - but not too loud */
    }

    if (ncdiminq (exoid, dimid, (char *) 0, &num_df_in_set) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of dist factors in side set %d in file id %d",
                side_set_id,exoid);
        ex_err("ex_get_side_set_dist_fact",errmsg,exerrval);
        return (EX_FATAL);
    }


    if ((dist_id = ncvarid (exoid, VAR_FACT_SS(side_set_id_ndx))) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to locate dist factors list for side set %d in file id %d",
                side_set_id,exoid);
        ex_err("ex_get_side_set_dist_fact",errmsg,exerrval);
        return (EX_FATAL);
    }


    /* read in the distribution factors array */

    start[0] = 0;

    count[0] = num_df_in_set;

    if (ncvarget (exoid, dist_id, start, count,
                  ex_conv_array(exoid,RTN_ADDRESS,side_set_dist_fact,
                                (int)num_df_in_set)) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get dist factors list for side set %d in file id %d",
                side_set_id,exoid);
        ex_err("ex_get_side_set_dist_fact",errmsg,exerrval);
        return (EX_FATAL);
    }


    ex_conv_array( exoid, READ_CONVERT, side_set_dist_fact, num_df_in_set );

    return (EX_NOERR);

}
Ejemplo n.º 4
0
Archivo: vc06c.c Proyecto: gavin971/ncl
int main(int argc, char *argv[])
{
    char const *wks_type = "x11";
    int appid,wid,vcid,vfid, sfid, mpid;
    int rlist;
    float U[73][73],V[73][73], PSL[73][73];
    char  smindist0[6] ;
    char  smindist1[5] ;
    char  smindist2[4] ;
    char  title[35];
    char  smindist[7] ;
    char slongitude[100] ;
/*
 * Declare variables for getting information from netCDF file.
 */
    int   uv, p, u_id, v_id, p_id, lon_id, lat_id, FRAME_COUNT;
    int  i, mindistval, longitudeval;
    ng_size_t icount[3];
    float val;
    long  start[2], count[2], lonlen, latlen; 
    float CenLonF;
    char  filenameUV[256];
    char  filenamePsl[256];
    const char *dirUV = _NGGetNCARGEnv("data");
    const char *dirPsl = _NGGetNCARGEnv("data");
/*
 * Generate vector data array
 */
    FRAME_COUNT=13;
/*
 * Open the netCDF file.
 */
    sprintf( filenameUV, "%s/cdf/941110_UV.cdf", dirUV );
    uv = ncopen(filenameUV,NC_NOWRITE);
/*
 * Open the netCDF file.
 */
    sprintf( filenamePsl, "%s/cdf/941110_P.cdf", dirPsl );
    p = ncopen(filenamePsl,NC_NOWRITE);
/*
 * Initialize the high level utility library
 */
    NhlInitialize();
/*
 * Create an application context. Set the app dir to the current
 * directory so the application looks for a resource file in the working
 * directory. 
 */
    rlist = NhlRLCreate(NhlSETRL);
    NhlRLClear(rlist);
    NhlRLSetString(rlist,NhlNappUsrDir,"./");
    NhlCreate(&appid,"vc06",NhlappClass,NhlDEFAULT_APP,rlist);

    if (!strcmp(wks_type,"ncgm") || !strcmp(wks_type,"NCGM")) {
/*
 * Create a meta file workstation.
 */
        NhlRLClear(rlist);
        NhlRLSetString(rlist,NhlNwkMetaName,"./vc06c.ncgm");
        NhlCreate(&wid,"vc06Work",
                  NhlncgmWorkstationClass,NhlDEFAULT_APP,rlist);
    }
    else if (!strcmp(wks_type,"x11") || !strcmp(wks_type,"X11")) {
/*
 * Create an X workstation.
 */
        NhlRLClear(rlist);
        NhlRLSetInteger(rlist,NhlNwkPause,True);
        NhlCreate(&wid,"vc06Work",NhlcairoWindowWorkstationClass,appid,rlist);
    }

    else if (!strcmp(wks_type,"oldps") || !strcmp(wks_type,"OLDPS")) {
/*
 * Create an older-style PostScript workstation.
 */
        NhlRLClear(rlist);
        NhlRLSetString(rlist,NhlNwkPSFileName,"vc06c.ps");
        NhlCreate(&wid,"vc06Work",NhlpsWorkstationClass,appid,rlist);
    }
    else if (!strcmp(wks_type,"oldpdf") || !strcmp(wks_type,"OLDPDF")) {
/*
 * Create an older-style PDF workstation.
 */
        NhlRLClear(rlist);
        NhlRLSetString(rlist,NhlNwkPDFFileName,"vc06c.pdf");
        NhlCreate(&wid,"vc06Work",NhlpdfWorkstationClass,appid,rlist);
    }
    else if (!strcmp(wks_type,"pdf") || !strcmp(wks_type,"PDF") ||
             !strcmp(wks_type,"ps") || !strcmp(wks_type,"PS")) {
/*
 * Create a cairo PS/PDF workstation.
 */
        NhlRLClear(rlist);
        NhlRLSetString(rlist,NhlNwkFileName,"vc06c");
        NhlRLSetString(rlist,NhlNwkFormat,(char*)wks_type);
        NhlCreate(&wid,"vc06Work",NhlcairoDocumentWorkstationClass,appid,rlist);
    }
    else if (!strcmp(wks_type,"png") || !strcmp(wks_type,"PNG")) {
/*
 * Create a cairo PNG workstation.
 */
        NhlRLClear(rlist);
        NhlRLSetString(rlist,NhlNwkFileName,"vc06c");
        NhlRLSetString(rlist,NhlNwkFormat,(char*)wks_type);
        NhlCreate(&wid,"vc06Work",NhlcairoImageWorkstationClass,appid,rlist);
    }
/*
 * Get the U and V and lat/lon dimensions.
 */
    lat_id = ncdimid(uv,"lat");
    lon_id = ncdimid(uv,"lon");
    u_id = ncvarid(uv,"u");
    v_id = ncvarid(uv,"v");
    ncdiminq(uv,lat_id,(char *)0,&latlen);
    ncdiminq(uv,lon_id,(char *)0,&lonlen);

    start[0] = start[1] = 0;
    count[0] = latlen; count[1] = lonlen;
    ncvarget(uv,u_id,(long const *)start,(long const *)count,U);
    ncvarget(uv,v_id,(long const *)start,(long const *)count,V);
/*
 * Create a VectorField data object using the data set defined above.
 * By default the array bounds will define the data boundaries (zero-based,
 * as in C language conventions)
 */
    icount[0] = latlen; icount[1] = lonlen;

    NhlRLClear(rlist);
    NhlRLSetMDFloatArray(rlist,NhlNvfUDataArray,&U[0][0],2,icount);
    NhlRLSetMDFloatArray(rlist,NhlNvfVDataArray,&V[0][0],2,icount);
    NhlRLSetFloat(rlist,NhlNvfXCStartV, -180.0);
    NhlRLSetFloat(rlist,NhlNvfXCEndV, 180.0);
    NhlRLSetFloat(rlist,NhlNvfYCStartV,-90.0);
    NhlRLSetFloat(rlist,NhlNvfYCEndV, 90.0);
    NhlCreate(&vfid,"vectorfield",NhlvectorFieldClass,appid,rlist);
/*
 * Get the PSL and lat/lon dimensions.
 */
    lat_id = ncdimid(p,"lat");
    lon_id = ncdimid(p,"lon");
    p_id = ncvarid(p,"Psl");
    ncdiminq(p,lat_id,(char *)0,&latlen);
    ncdiminq(p,lon_id,(char *)0,&lonlen);

    start[0] = start[1] = 0;
    count[0] = latlen; count[1] = lonlen;
    ncvarget(p,p_id,(long const *)start,(long const *)count,PSL);
    icount[0] = latlen; icount[1] = lonlen;

    NhlRLClear(rlist);
    NhlRLSetMDFloatArray(rlist,NhlNsfDataArray,&PSL[0][0],2,icount);
    NhlRLSetFloat(rlist,NhlNsfXCStartV, -180.0);
    NhlRLSetFloat(rlist,NhlNsfXCEndV, 180.0);
    NhlRLSetFloat(rlist,NhlNsfYCStartV, -90.0);
    NhlRLSetFloat(rlist,NhlNsfYCEndV, 90.0);
    NhlCreate(&sfid,"scalarfield",NhlscalarFieldClass,appid,rlist);
/*
 * Create a VectorPlot object, supplying the VectorField object as data
 * Setting vcMonoFillArrowFillColor False causes VectorPlot to color the
 * vector arrows individually based, by default, on the vector magnitude.
 * Also supply the ScalarField object that will be used to determine the
 * color of each individual vector arrow.
 * Setting vcMonoVectorLineColor False causes VectorPlot to color the
 * vector arrows individually and setting vcUseScalarArray True results
 * in VectorPlot applying the colors based on the contents of the scalarfield.
 */
    NhlRLClear(rlist);
    NhlRLSetFloat(rlist,NhlNvcRefMagnitudeF, 20.0);
    NhlRLSetString(rlist,NhlNvcUseScalarArray, "True");
    NhlRLSetString(rlist,NhlNvcFillArrowsOn, "True");
    NhlRLSetString(rlist,NhlNvcMonoFillArrowFillColor, "False");
    NhlRLSetFloat(rlist,NhlNvcMinFracLengthF, 0.25);
    NhlRLSetInteger(rlist,NhlNvcVectorFieldData,vfid);
    NhlRLSetInteger(rlist,NhlNvcScalarFieldData,sfid);
    NhlCreate(&vcid,"vectorplot",NhlvectorPlotClass,wid,rlist);

    NhlRLClear(rlist);
    NhlRLSetString(rlist,NhlNmpProjection, "ORTHOGRAPHIC");
    NhlRLSetFloat(rlist,NhlNmpCenterLatF, 50);
    NhlCreate(&mpid,"mapplot",NhlmapPlotClass,wid,rlist);

    NhlAddOverlay(mpid,vcid, -1);
/*
 * Strings used to create fixed length numbers
 */
    strcpy(smindist0 ,"0.000");
    strcpy(smindist1 ,"0.00");
    strcpy( smindist2 ,"0.0");
/*
 * Create FRAME_COUNT frames, increasing the value of vcMinDistanceF
 * and decreasing the value of mpCenterLonF at each successive frame.
 *
 * Note that the first frame and the last frame are equivalent in
 * longitude.
 */
    for(i = (FRAME_COUNT-1);i > -1; i--){
        NhlRLClear(rlist);       
        CenLonF =  i * 360./(FRAME_COUNT-1);
        NhlRLSetFloat(rlist,NhlNmpCenterLonF,CenLonF);
        NhlSetValues(mpid,rlist);
/*
 * create fixed length strings representing the current longitude
 * and the value of vcMinDistanceF
 */
        longitudeval = (int)(i * 360./(FRAME_COUNT-1) + 0.5);

        sprintf(slongitude,"%d:S:o:N:",longitudeval);

        val = ((FRAME_COUNT-1) - i) * 0.0175/(FRAME_COUNT-1);
        mindistval = (int)(10000*val + 0.5);

        if (mindistval < 10){
            sprintf(smindist,"%s%d",smindist0,mindistval);
        }
        else {
            if (mindistval < 100){
                sprintf(smindist,"%s%d",smindist1,mindistval);
            }
            else {
                sprintf(smindist,"%s%d",smindist2,mindistval);
            }
        }

        NhlRLClear(rlist);
        
        strcpy(title,"Varying vcMinDistanceF :: ");
        strcat(title,smindist);
        
        NhlRLSetString(rlist,NhlNtiMainString,title);
        NhlRLSetString(rlist,NhlNtiXAxisString,slongitude);
        NhlRLSetFloat(rlist,NhlNvcMinDistanceF,val);
        NhlSetValues(vcid,rlist);

        NhlDraw(mpid);
        NhlFrame(wid);

    }/*end for*/
/*
 * Destroy the objects created, close the HLU library and exit.
 */
    NhlDestroy(mpid);
    NhlDestroy(wid);
    NhlDestroy(appid);
    NhlClose();
    exit(0);
}
Ejemplo n.º 5
0
int ex_put_node_map (int exoid,
                     int map_id,
                     const int *node_map)
{
   int dimid, varid, iresult;
   long start[1]; 
   nclong ldum, *lptr;
   long num_node_maps, num_nodes, count[1];
   int cur_num_node_maps;
   char *cdum;
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

   cdum = 0;


   /* Return if node nodes stored in this file */
   if ((dimid = (ncdimid (exoid, DIM_NUM_NODES))) == -1 ) {
     return (EX_NOERR);
   }

/* first check if any node maps are specified */

   if ((dimid = (ncdimid (exoid, DIM_NUM_NM))) == -1 )
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: no node maps specified in file id %d",
             exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

/* Check for duplicate node map id entry */
   ex_id_lkup(exoid,VAR_NM_PROP(1),map_id);
   if (exerrval != EX_LOOKUPFAIL)   /* found the node map id */
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: node map %d already defined in file id %d",
             map_id,exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return(EX_FATAL);
   }

/* Get number of node maps initialized for this file */
   if ((ncdiminq (exoid,dimid,cdum,&num_node_maps)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to get number of node maps in file id %d",
             exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

/* Keep track of the total number of node maps defined using a counter stored
   in a linked list keyed by exoid.
   NOTE: ex_get_file_item  is used to find the number of node maps
         for a specific file and returns that value.
*/
   cur_num_node_maps = ex_get_file_item(exoid, &nm_ctr_list );
   if (cur_num_node_maps >= num_node_maps)
   {
     exerrval = EX_FATAL;
     sprintf(errmsg,
          "Error: exceeded number of node maps (%ld) specified in file id %d",
             num_node_maps,exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

/*   NOTE: ex_inc_file_item  is used to find the number of node maps
         for a specific file and returns that value incremented. */

   cur_num_node_maps = ex_inc_file_item(exoid, &nm_ctr_list );

/* write out information to previously defined variable */

   /* first get id of variable */

   if ((varid = ncvarid (exoid, VAR_NM_PROP(1))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to locate node map ids in file id %d",
             exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   /* then, write out node map id */

   start[0] = cur_num_node_maps;

   ldum = (nclong)map_id;
   if (ncvarput1 (exoid, varid, start, &ldum) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to store node map id %d in file id %d",
             map_id,exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

/* determine number of nodes */

   if ((dimid = (ncdimid (exoid, DIM_NUM_NODES))) == -1 )
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: couldn't determine number of nodes in file id %d",
             exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (ncdiminq (exoid, dimid, (char *) 0, &num_nodes) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to get number of nodes in file id %d",
             exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   /* find variable array in which to store the node map */
   if ((varid = ncvarid(exoid,VAR_NODE_MAP(cur_num_node_maps+1))) == -1)
     {
       exerrval = ncerr;
       sprintf(errmsg,
	       "Error: failed to locate node map %d in file id %d",
               map_id,exoid);
       ex_err("ex_put_node_map",errmsg,exerrval);
       return(EX_FATAL);
     }

/* write out the node map  */

/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */

   start[0] = 0;
   count[0] = num_nodes;

   if (sizeof(int) == sizeof(nclong)) {
      iresult = ncvarput (exoid, varid, start, count, node_map);
   } else {
      lptr = itol (node_map, (int)num_nodes);
      iresult = ncvarput (exoid, varid, start, count, lptr);
      free(lptr);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to store node map in file id %d",
             exoid);
     ex_err("ex_put_node_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   return (EX_NOERR);
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
   char **infiles, *outfiles[3];
   int nfiles, nout;
   char *arg_string;
   Norm_Data norm_data;
   Average_Data average_data;
   Loop_Options *loop_options;
   double *vol_mean, vol_total, nvols, global_mean, total_weight;
   int ifile, iweight;
   int weights_specified;
   int first_mincid, dimid, varid, dim[MAX_VAR_DIMS];
   int ndims;
   long start, count;
   int old_ncopts;
   int strlength;
   char dimname[MAX_NC_NAME];

   /* Save time stamp and args */
   arg_string = time_stamp(argc, argv);

   /* Get arguments */
   if (ParseArgv(&argc, argv, argTable, 0) || (argc < 2)) {
      (void) fprintf(stderr, 
      "\nUsage: %s [options] [<in1.mnc> ...] <out.mnc>\n",
                     argv[0]);
      (void) fprintf(stderr, 
        "       %s -help\n\n", argv[0]);
      exit(EXIT_FAILURE);
   }
   outfiles[0] = outfiles[1] = outfiles[2] = NULL;
   outfiles[0] = argv[argc-1];
   nout = 1;
   if( sdfile != NULL )
	   outfiles[nout++] = sdfile;
   if( weightfile != NULL )
	   outfiles[nout++] = weightfile;

   first_mincid = MI_ERROR;

   /* Get the list of input files either from the command line or
      from a file, or report an error if both are specified */
   nfiles = argc - 2;
   if (filelist == NULL) {
      infiles = &argv[1];
   }
   else if (nfiles <= 0) {
      infiles = read_file_names(filelist, &nfiles);
      if (infiles == NULL) {
         (void) fprintf(stderr, 
                        "Error reading in file names from file \"%s\"\n",
                        filelist);
         exit(EXIT_FAILURE);
      }
   }
   else {
      (void) fprintf(stderr, 
                     "Do not specify both -filelist and input file names\n");
      exit(EXIT_FAILURE);
   }

   /* Make sure that we have something to process */
   if (nfiles == 0) {
      (void) fprintf(stderr, "No input files specified\n");
      exit(EXIT_FAILURE);
   }

   /* Set default value of copy_all_header */
   if (copy_all_header == DEFAULT_BOOLEAN) {
      copy_all_header = (nfiles <= 1);
   }

   /* Are we averaging over a dimension? */
   average_data.averaging_over_dimension = (averaging_dimension != NULL);

   /* Check for weights and width-weighting */
   weights_specified = weights.numvalues > 0;
   if (weights_specified && width_weighted) {
      (void) fprintf(stderr, 
         "%s: Please do not specify weights and width-weighting.\n",
                     argv[0]);
      exit(EXIT_FAILURE);
   }

   /* Default is no weighting */
   average_data.num_weights = 0;
   average_data.weights = NULL;

   /* Check for weights */
   if (weights_specified) {
      if (averaging_dimension == NULL) {
         if (weights.numvalues != nfiles) {
            (void) fprintf(stderr, 
               "%s: Number of weights does not match number of files.\n",
                           argv[0]);
            exit(EXIT_FAILURE);
         }
      }
      else {
         if (nfiles > 1) {
            (void) fprintf(stderr,
               "%s: Only one input file allowed with -weights and -avgdim.\n",
                           argv[0]);
            exit(EXIT_FAILURE);
         }

         /* Check that the dimension size matches the number of weights */
         first_mincid = miopen(infiles[0], NC_NOWRITE);
         dimid = ncdimid(first_mincid, averaging_dimension);
         (void) ncdiminq(first_mincid, dimid, NULL, &count);
         if (weights.numvalues != count) {
            (void) fprintf(stderr,
               "%s: Number of weights does not match size of dimension.\n",
                           argv[0]);
         }
      }

      /* Save the weights */
      average_data.num_weights = weights.numvalues;
      average_data.weights = 
         malloc(sizeof(*average_data.weights) * average_data.num_weights);
      for (iweight=0; iweight < average_data.num_weights; iweight++) {
         average_data.weights[iweight] = weights.values[iweight];
      }

      free(weights.values);
   }

   /* Check for width weighting */
   if (width_weighted) {

      /* Check for errors */
      if (averaging_dimension == NULL) {
         (void) fprintf(stderr, 
                        "%s: Please specify -avgdim with -width_weighted.\n",
                        argv[0]);
         exit(EXIT_FAILURE);
      }
      if (nfiles > 1) {
         (void) fprintf(stderr,
                        "%s: Use -width_weighted with only one input file.\n",
                        argv[0]);
         exit(EXIT_FAILURE);
      }

      /* Open the file */
      first_mincid = miopen(infiles[0], NC_NOWRITE);

      /* Get the dimension id */
      dimid = ncdimid(first_mincid, averaging_dimension);

      /* Look for the width variable */
      strlength = MAX_NC_NAME - strlen(WIDTH_SUFFIX) - 1;
      (void) strncpy(dimname, averaging_dimension, strlength);
      dimname[strlength] = '\0';
      (void) strcat(dimname, WIDTH_SUFFIX);
      old_ncopts = ncopts; ncopts = 0;
      varid = ncvarid(first_mincid, dimname);
      (void) ncvarinq(first_mincid, varid, NULL, NULL, &ndims, dim, NULL);
      ncopts = old_ncopts;
      if (varid != MI_ERROR) {

         /* Check that things match up */
         if ((ndims != 1) || (dim[0] != dimid)) {
            (void) fprintf(stderr,
                "%s: Dimension width variable does not match avgdim.\n",
                           argv[0]);
         }

         /* Get the size of the dimension */
         (void) ncdiminq(first_mincid, dim[0], NULL, &count);
         average_data.num_weights = count;
         average_data.weights = 
            malloc(sizeof(*average_data.weights) * average_data.num_weights);

         /* Read in the widths */
         start = 0;
         (void) mivarget(first_mincid, varid, &start, &count, NC_DOUBLE, NULL,
                         average_data.weights);

      }
   }    /* If width_weighted */

   /* Check that weights sum to non-zero. We don't need to normalize them,
      since a running sum is done in the averaging. */
   if (average_data.num_weights > 0) {
      total_weight = 0.0;
      for (iweight=0; iweight < average_data.num_weights; iweight++) {
         total_weight += average_data.weights[iweight];
      }
      if (total_weight == 0.0) {
         (void) fprintf(stderr, "%s: Weights sum to zero.\n", argv[0]);
         exit(EXIT_FAILURE);
      }
   }

   /* If we don't have weights, each input will get a weight of 1 */
   if (average_data.num_weights == 0)
       total_weight = nfiles;

   /* Check the cumulative weight thresholding */
   if (weight_thresh > 0.0 && weight_thresh_fraction > 0.0){
      (void) fprintf(stderr, 
                     "Do not specify both -min_weight -min_weight_fraction\n");
      exit(EXIT_FAILURE);
   }
   else if( weight_thresh_fraction > 0.0 ){
       weight_thresh = weight_thresh_fraction * total_weight;
   }
   average_data.weight_thresh = weight_thresh;
   

   /* Check for binarization */
   if (binarize) {
      if (normalize == TRUE) {
         (void) fprintf(stderr, 
            "%s: Normalization and binarization cannot both be specified\n",
                        argv[0]);
         exit(EXIT_FAILURE);
      }
      normalize = FALSE;
      if (binvalue != -DBL_MAX) {
         binrange[0] = binvalue - 0.5;
         binrange[1] = binvalue + 0.5;
      }
      if (binrange[0] > binrange[1]) {
         (void) fprintf(stderr, 
         "%s: Please specify a binarization range with min less than max\n",
                        argv[0]);
         exit(EXIT_FAILURE);
      }
      average_data.binrange[0] = binrange[0];
      average_data.binrange[1] = binrange[1];
   }
   average_data.binarize = binarize;

   /* Store the ignore above/below values */
   average_data.ignore_below = ignore_below;
   average_data.ignore_above = ignore_above;

   /* Check for no specification of normalization */
#ifdef NO_DEFAULT_NORM
   if (normalize == -1) {
      (void) fprintf(stderr, "\n%s: %s\n\n%s\n%s\n%s\n%s\n%s\n\n", argv[0],
"Please specify either -norm or -nonorm.",
"The default setting for normalization is being changed from \"-norm\" to",
"\"-nonorm\". To prevent undetected problems with data, this program will ",
"not work unless one of these flags is explicitly given on the command-line",
"(ie. no default is permitted). The new default will come into effect some",
"time in the future."
                     );
      exit(EXIT_FAILURE);
   }
#endif

   /* Do normalization if needed */
   average_data.norm_factor = 
      malloc(sizeof(*average_data.norm_factor) * nfiles);
   if (normalize) {
      vol_mean = malloc(sizeof(*vol_mean) * nfiles);
      loop_options = create_loop_options();
      set_loop_verbose(loop_options, FALSE);
#if MINC2
      set_loop_v2format(loop_options, minc2_format);
#endif /* MINC2 */
      set_loop_accumulate(loop_options, TRUE, 0, NULL, NULL);
      set_loop_buffer_size(loop_options, (long) 1024 * max_buffer_size_in_kb);
      set_loop_check_dim_info(loop_options, check_dimensions);
      vol_total = 0.0;
      nvols = 0;
      if (verbose) {
         (void) fprintf(stderr, "Normalizing:");
         (void) fflush(stderr);
      }
      for (ifile=0; ifile < nfiles; ifile++) {
         norm_data.threshold_set = FALSE;
         norm_data.sum0 = 0.0;
         norm_data.sum1 = 0.0;
         if (verbose) {
            (void) fprintf(stderr, ".");
            (void) fflush(stderr);
         }
         if (first_mincid != MI_ERROR) {
            set_loop_first_input_mincid(loop_options, first_mincid);
            first_mincid = MI_ERROR;
         }
         voxel_loop(1, &infiles[ifile], 0, NULL, NULL, loop_options,
                    do_normalization, (void *) &norm_data);
         if (norm_data.sum0 > 0.0) {
            vol_mean[ifile] = norm_data.sum1 / norm_data.sum0;
            vol_total += vol_mean[ifile];
            nvols++;
         }
         else {
            vol_mean[ifile] = 0.0;
         }
         if (debug) {
            (void) fprintf(stderr, "Volume %d mean = %.15g\n",
                           ifile, vol_mean[ifile]);
         }
      }
      free_loop_options(loop_options);
      if (verbose) {
         (void) fprintf(stderr, "Done\n");
         (void) fflush(stderr);
      }
      if (nvols > 0)
         global_mean = vol_total / nvols;
      else
         global_mean = 0.0;
      for (ifile=0; ifile < nfiles; ifile++) {
         if (vol_mean[ifile] > 0.0)
            average_data.norm_factor[ifile] = global_mean / vol_mean[ifile];
         else
            average_data.norm_factor[ifile] = 0.0;
         if (debug) {
            (void) fprintf(stderr, "Volume %d norm factor = %.15g\n", 
                           ifile, average_data.norm_factor[ifile]);
         }
      }
      free(vol_mean);
   }
   else {
      for (ifile=0; ifile < nfiles; ifile++) {
         average_data.norm_factor[ifile] = 1.0;
      }
   }

   /* Do averaging */
   average_data.need_sd = (sdfile != NULL);
   average_data.need_weight = (weightfile != NULL);
   loop_options = create_loop_options();
   if (first_mincid != MI_ERROR) {
      set_loop_first_input_mincid(loop_options, first_mincid);
      first_mincid = MI_ERROR;
   }
   set_loop_verbose(loop_options, verbose);
   set_loop_clobber(loop_options, clobber);
   set_loop_datatype(loop_options, datatype, is_signed, 
                     valid_range[0], valid_range[1]);
   set_loop_accumulate(loop_options, TRUE, 1, start_average, finish_average);
   set_loop_copy_all_header(loop_options, copy_all_header);
   set_loop_dimension(loop_options, averaging_dimension);
   set_loop_buffer_size(loop_options, (long) 1024 * max_buffer_size_in_kb);
   set_loop_check_dim_info(loop_options, check_dimensions);
   voxel_loop(nfiles, infiles, nout, outfiles, arg_string, loop_options,
              do_average, (void *) &average_data);
   free_loop_options(loop_options);

   /* Free stuff */
   free(average_data.weights);
   free(average_data.norm_factor);

   exit(EXIT_SUCCESS);
}
Ejemplo n.º 7
0
int ex_put_coord (int   exoid,
                  const void *x_coor,
                  const void *y_coor,
                  const void *z_coor)
{
  int coordid;
  int coordidx, coordidy, coordidz;

  int numnoddim, ndimdim, i;
  long num_nod, num_dim, start[2], count[2];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* inquire id's of previously defined dimensions  */

  if ((numnoddim = ncdimid (exoid, DIM_NUM_NODES)) == -1)
    {
      /* If not found, then this file is storing 0 nodes.
         Return immediately */
      return (EX_NOERR);
    }

  if (ncdiminq (exoid, numnoddim, NULL, &num_nod) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: inquire failed to return number of nodes in file id %d",
              exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    }

  if ((ndimdim = ncdimid (exoid, DIM_NUM_DIM)) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to locate number of dimensions in file id %d",
              exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    }

  if (ncdiminq (exoid, ndimdim, NULL, &num_dim) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get number of dimensions in file id %d",
              exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    }

  /* write out the coordinates  */
  if (ex_large_model(exoid) == 0) {
    if ((coordid = ncvarid (exoid, VAR_COORD)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to locate nodal coordinates in file id %d", exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    } 

    for (i=0; i<num_dim; i++)
      {
        start[0] = i;
        start[1] = 0;

        count[0] = 1;
        count[1] = num_nod;

        if (i == 0 && x_coor != NULL)
          {
            if (ncvarput (exoid, coordid, start, count,
                          ex_conv_array(exoid,WRITE_CONVERT,x_coor,(int)num_nod)) == -1)
              {
                exerrval = ncerr;
                sprintf(errmsg,
                        "Error: failed to put X coord array in file id %d", exoid);
                ex_err("ex_put_coord",errmsg,exerrval);
                return (EX_FATAL);
              }
          }

        else if (i == 1 && y_coor != NULL)
          {
            if (ncvarput (exoid, coordid, start, count,
                          ex_conv_array(exoid,WRITE_CONVERT,y_coor,(int)num_nod)) == -1)
              {
                exerrval = ncerr;
                sprintf(errmsg,
                        "Error: failed to put Y coord array in file id %d", exoid);
                ex_err("ex_put_coord",errmsg,exerrval);
                return (EX_FATAL);
              }
          }

        else if (i == 2 && z_coor != NULL)
          {
            if (ncvarput (exoid, coordid, start, count,
                          ex_conv_array(exoid,WRITE_CONVERT,z_coor,(int)num_nod)) == -1)
              {
                exerrval = ncerr;
                sprintf(errmsg,
                        "Error: failed to put Z coord array in file id %d", exoid);
                ex_err("ex_put_coord",errmsg,exerrval);
                return (EX_FATAL);
              }
          }
      }
  } else {
    if ((coordidx = ncvarid (exoid, VAR_COORD_X)) == -1)
      {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to locate x nodal coordinates in file id %d", exoid);
        ex_err("ex_put_coord",errmsg,exerrval);
        return (EX_FATAL);
      }

    if (num_dim > 1) {
      if ((coordidy = ncvarid (exoid, VAR_COORD_Y)) == -1)
        {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: failed to locate y nodal coordinates in file id %d", exoid);
          ex_err("ex_put_coord",errmsg,exerrval);
          return (EX_FATAL);
        }
    } else {
      coordidy = 0;
    }
    if (num_dim > 2) {
      if ((coordidz = ncvarid (exoid, VAR_COORD_Z)) == -1)
        {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: failed to locate z nodal coordinates in file id %d", exoid);
          ex_err("ex_put_coord",errmsg,exerrval);
          return (EX_FATAL);
        }
    } else {
      coordidz = 0;
    }
    /* write out the coordinates  */
    for (i=0; i<num_dim; i++)
      {
        const void *coor;
        char *which;
        int status;
       
        if (i == 0) {
          coor = x_coor;
          which = "X";
          coordid = coordidx;
        } else if (i == 1) {
          coor = y_coor;
          which = "Y";
          coordid = coordidy;
        } else if (i == 2) {
          coor = z_coor;
          which = "Z";
          coordid = coordidz;
        }

        if (coor != NULL) {
        if (nc_flt_code(exoid) == NC_FLOAT) {
          status = nc_put_var_float(exoid, coordid, 
                                    static_cast<float*>(const_cast<void*>(ex_conv_array(exoid,WRITE_CONVERT,
											coor,(int)num_nod))));
        } else {
          status = nc_put_var_double(exoid, coordid, 
                                     static_cast<double*>(const_cast<void*>(ex_conv_array(exoid,WRITE_CONVERT,
											  coor,(int)num_nod))));
        }

        if (status == -1)
          {
            exerrval = ncerr;
            sprintf(errmsg,
                    "Error: failed to put %s coord array in file id %d", which, exoid);
            ex_err("ex_put_coord",errmsg,exerrval);
            return (EX_FATAL);
          }
        }
      }
  }
  return (EX_NOERR);
}
Ejemplo n.º 8
0
int ex_get_node_set_param (int  exoid,
                           int  node_set_id,
                           int *num_nodes_in_set,
                           int *num_df_in_set)
{
    int dimid, node_set_id_ndx;
    long lnum_nodes_in_set, lnum_df_in_set;
    char errmsg[MAX_ERR_LENGTH];

    exerrval = 0; /* clear error code */

    /* first check if any node sets are specified */

    if ((dimid = ncdimid (exoid, DIM_NUM_NS))  == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Warning: no node sets defined in file id %d",
                exoid);
        ex_err("ex_get_node_set_param",errmsg,exerrval);
        return (EX_WARN);
    }

    /* Lookup index of node set id in VAR_NS_IDS array */

    node_set_id_ndx = ex_id_lkup(exoid,VAR_NS_IDS,node_set_id);
    if (exerrval != 0)
    {
        if (exerrval == EX_NULLENTITY)     /* NULL node set ? */
        {
            *num_nodes_in_set = 0;
            *num_df_in_set = 0;
            return (EX_NOERR);
        }
        else
        {
            sprintf(errmsg,
                    "Error: failed to locate node set id %d in VAR_NS_IDS array in file id %d",
                    node_set_id,exoid);
            ex_err("ex_get_node_set_param",errmsg,exerrval);
            return (EX_FATAL);
        }

    }
    /* inquire value of dimension of number of nodes for this node set */

    if ((dimid = ncdimid (exoid, DIM_NUM_NOD_NS(node_set_id_ndx))) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to locate number of nodes in node set %d in file id %d",
                node_set_id,exoid);
        ex_err("ex_get_node_set_param",errmsg,exerrval);
        return (EX_FATAL);
    }

    if (ncdiminq (exoid, dimid, (char *) 0, &lnum_nodes_in_set) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of nodes in node set %d in file id %d",
                node_set_id,exoid);
        ex_err("ex_get_node_set_param",errmsg,exerrval);
        return (EX_FATAL);
    }
    *num_nodes_in_set = lnum_nodes_in_set;

    /* Inquire if the dist factors variable have been defined for this node set.
       NOTE: If the dist factor variable for this node set index doesn't exist,
             it is assumed to be zero, otherwise the dist factor count will be
             the same as the number of nodes in the set. */
    if ((ncvarid (exoid, VAR_FACT_NS(node_set_id_ndx))) == -1)
    {
        *num_df_in_set = 0;        /* signal dist factor doesn't exist */
        if (ncerr == NC_ENOTVAR)
            return (EX_NOERR);
        else
        {
            exerrval = ncerr;
            sprintf(errmsg,
                    "Error: failed to locate the dist factors for node set %d in file id %d",
                    node_set_id,exoid);
            ex_err("ex_get_node_set_param",errmsg,exerrval);
            return (EX_FATAL);
        }
    }
    else
    {
        /* dimension exists, retrieve value */
        if (ncdiminq (exoid, dimid, (char *) 0, &lnum_df_in_set) == -1)
        {
            exerrval = ncerr;
            sprintf(errmsg,
                    "Error: failed to get number of dist fact in node set %d in file id %d",
                    node_set_id,exoid);
            ex_err("ex_get_node_set_param",errmsg,exerrval);
            return (EX_FATAL);
        }
        *num_df_in_set = lnum_nodes_in_set;        /* # of df = # of nodes */
    }

    return (EX_NOERR);
}
Ejemplo n.º 9
0
int ex_get_init (int   exoid,
                 char *title,
                 int  *num_dim,
                 int  *num_nodes,
                 int  *num_elem, 
                 int  *num_elem_blk,
                 int  *num_node_sets,
                 int  *num_side_sets)
{
  int dimid;
  long lnum_dim, lnum_nodes, lnum_elem, lnum_elem_blk, lnum_node_sets; 
  long lnum_side_sets;
  char errmsg[MAX_ERR_LENGTH];
  int title_len;
  nc_type title_type;

  exerrval = 0; /* clear error code */

  if (ncattinq (exoid, NC_GLOBAL, ATT_TITLE, &title_type, &title_len) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to inquire title in file id %d", exoid);
      ex_err("ex_get_init",errmsg,exerrval);
      return (EX_FATAL);
    }

  /* Check title length to avoid overrunning clients memory space;
     include trailing null */
  if (title_len > MAX_LINE_LENGTH+1) {
    sprintf(errmsg,
            "Error: Title is too long (%d characters) in file id %d",
            title_len-1, exoid);
    exerrval = -1;
    ex_err("ex_get_init",errmsg,exerrval);
    return (EX_FATAL);
  }
  /* printf("[ex_get_init] title length: %d\n",title_len); */

  if (ncattget (exoid, NC_GLOBAL, ATT_TITLE, title) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get title in file id %d", exoid);
      ex_err("ex_get_init",errmsg,exerrval);
      return (EX_FATAL);
    }

    
  /* printf("[ex_get_init] title: %s\n",title); */


  if ((dimid = ncdimid (exoid, DIM_NUM_DIM)) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to locate number of dimensions in file id %d",
              exoid);
      ex_err("ex_get_init",errmsg,exerrval);
      return (EX_FATAL);
    }

  if (ncdiminq (exoid, dimid, (char *) 0, &lnum_dim) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get number of dimensions in file id %d",
              exoid);
      ex_err("ex_get_init",errmsg,exerrval);
      return (EX_FATAL);
    }
  *num_dim = lnum_dim;


  /* Handle case with zero-nodes */
  if ((dimid = ncdimid (exoid, DIM_NUM_NODES)) == -1) {
    *num_nodes = 0;
  } else {
     
    if (ncdiminq (exoid, dimid, (char *) 0, &lnum_nodes) == -1)
      {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of nodes in file id %d",
                exoid);
        ex_err("ex_get_init",errmsg,exerrval);
        return (EX_FATAL);
      }
    *num_nodes = lnum_nodes;
  }
   
  if ((dimid = ncdimid (exoid, DIM_NUM_ELEM)) == -1) {
    *num_elem = 0;
  } else {
    if (ncdiminq (exoid, dimid, (char *) 0, &lnum_elem) == -1)
      {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of elements in file id %d",
                exoid);
        ex_err("ex_get_init",errmsg,exerrval);
        return (EX_FATAL);
      }
    *num_elem = lnum_elem;
  }


  if (*num_elem > 0) {
    if ((dimid = ncdimid (exoid, DIM_NUM_EL_BLK)) == -1)
      {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to locate number of element blocks in file id %d",
                exoid);
        ex_err("ex_get_init",errmsg,exerrval);
        return (EX_FATAL);
      }

    if (ncdiminq (exoid, dimid, (char *) 0, &lnum_elem_blk) == -1)
      {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of element blocks in file id %d",
                exoid);
        ex_err("ex_get_init",errmsg,exerrval);
        return (EX_FATAL);
      }
    *num_elem_blk = lnum_elem_blk;
  } else {
    *num_elem_blk = 0;
  }


  /* node sets are optional */
  if ((dimid = ncdimid (exoid, DIM_NUM_NS)) == -1)
    *num_node_sets = 0;
  else
    {
      if (ncdiminq (exoid, dimid, (char *) 0, &lnum_node_sets) == -1)
        {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: failed to get number of node sets in file id %d",
                  exoid);
          ex_err("ex_get_init",errmsg,exerrval);
          return (EX_FATAL);
        }
      *num_node_sets = lnum_node_sets;
    }

  /* side sets are optional */
  if ((dimid = ncdimid (exoid, DIM_NUM_SS))  == -1)
    *num_side_sets = 0;
  else
    {
      if (ncdiminq (exoid, dimid, (char *) 0, &lnum_side_sets) == -1)
        {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: failed to get number of side sets in file id %d",
                  exoid);
          ex_err("ex_get_init",errmsg,exerrval);
          return (EX_FATAL);
        }
      *num_side_sets = lnum_side_sets;
    }

  return (EX_NOERR);
}
Ejemplo n.º 10
0
int ex_put_conn (int   exoid,
                 int   blk_type,
                 int   blk_id,
                 const int  *node_conn,
                 const int  *elem_edge_conn,
                 const int  *elem_face_conn)
{
   int numelbdim=-1, nelnoddim=-1, connid=-1, blk_id_ndx, iresult;
   char* var_id_blk;
   long num_entry_this_blk, num_id_per_entry, start[2], count[2]; 
   nclong *lptr;
   char errmsg[MAX_ERR_LENGTH];
   const char* blk_typename;

   exerrval = 0; /* clear error code */

   switch (blk_type) {
   case EX_ELEM_BLOCK:
     /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */
     var_id_blk = VAR_ID_EL_BLK;
     blk_typename = "element";
     break;
   case EX_FACE_BLOCK:
     var_id_blk = VAR_ID_FA_BLK;
     blk_typename = "face";
     break;
   case EX_EDGE_BLOCK:
     var_id_blk = VAR_ID_ED_BLK;
     blk_typename = "edge";
     break;
   default:
     sprintf(errmsg,"Error: Invalid block type %d passed for file id %d",
             blk_type,exoid);
     ex_err("ex_put_conn",errmsg,EX_MSG);
     return (EX_FATAL);
   }

   blk_id_ndx = ex_id_lkup(exoid,var_id_blk,blk_id);
   if (exerrval != 0) 
     {
     if (exerrval == EX_NULLENTITY)
       {
       sprintf(errmsg,
         "Warning: connectivity array not allowed for NULL %s block %d in file id %d",
         blk_typename,blk_id,exoid);
       ex_err("ex_put_conn",errmsg,EX_MSG);
       return (EX_WARN);
       }
     else
       {
       sprintf(errmsg,
         "Error: failed to locate %s block id %d in %s array in file id %d",
         blk_typename,blk_id,var_id_blk, exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return (EX_FATAL);
       }
     }

/* inquire id's of previously defined dimensions  */

   switch (blk_type) {
   case EX_ELEM_BLOCK:
     /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */
     numelbdim = ncdimid (exoid, DIM_NUM_EL_IN_BLK(blk_id_ndx));
     break;
   case EX_FACE_BLOCK:
     numelbdim = ncdimid (exoid, DIM_NUM_FA_IN_FBLK(blk_id_ndx));
     break;
   case EX_EDGE_BLOCK:
     numelbdim = ncdimid (exoid, DIM_NUM_ED_IN_EBLK(blk_id_ndx));
     break;
   }
   if (numelbdim == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
     "Error: failed to locate number of %ss in block %d in file id %d",
              blk_typename,blk_id,exoid);
     ex_err("ex_put_conn",errmsg, exerrval);
     return(EX_FATAL);
   }

   if (ncdiminq(exoid, numelbdim, NULL, &num_entry_this_blk) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to get number of elements in block %d in file id %d",
             blk_id,exoid);
     ex_err("ex_put_conn",errmsg,exerrval);
     return(EX_FATAL);
   }


   switch (blk_type) {
   case EX_ELEM_BLOCK:
     nelnoddim = ncdimid (exoid, DIM_NUM_NOD_PER_EL(blk_id_ndx));
     break;
   case EX_FACE_BLOCK:
     nelnoddim = ncdimid (exoid, DIM_NUM_NOD_PER_FA(blk_id_ndx));
     break;
   case EX_EDGE_BLOCK:
     nelnoddim = ncdimid (exoid, DIM_NUM_NOD_PER_ED(blk_id_ndx));
     break;
   }
   if (nelnoddim == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
       "Error: failed to locate number of nodes/%s in block %d in file id %d",
             blk_typename,blk_id,exoid);
     ex_err("ex_put_conn",errmsg,exerrval);
     return(EX_FATAL);
   }

   if (ncdiminq (exoid, nelnoddim, NULL, &num_id_per_entry) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
       "Error: failed to get number of nodes/elem in block %d in file id %d",
             blk_id,exoid);
     ex_err("ex_put_conn",errmsg,exerrval);
     return(EX_FATAL);
   }


   switch (blk_type) {
   case EX_ELEM_BLOCK:
     connid = ncvarid (exoid, VAR_CONN(blk_id_ndx));
     break;
   case EX_FACE_BLOCK:
     connid = ncvarid (exoid, VAR_FBCONN(blk_id_ndx));
     break;
   case EX_EDGE_BLOCK:
     connid = ncvarid (exoid, VAR_EBCONN(blk_id_ndx));
     break;
   }
   if (connid == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
"Error: failed to locate connectivity array for %s block %d in file id %d",
             blk_typename,blk_id,exoid);
     ex_err("ex_put_conn",errmsg, exerrval);
     return(EX_FATAL);
   }


/* write out the connectivity array */

/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */
#define EX_WRITE_CONN(TNAME,ARRDIM0,ARRDIM1,VARCONN,VARCONNVAL) \
   start[0] = 0; \
   start[1] = 0; \
 \
   count[0] = (ARRDIM0); \
   count[1] = (ARRDIM1); \
 \
   if (sizeof(int) == sizeof(nclong)) { \
      iresult = ncvarput (exoid, VARCONN, start, count, VARCONNVAL); \
   } else { \
      lptr = itol (VARCONNVAL, (int)((ARRDIM0)*(ARRDIM1))); \
      iresult = ncvarput (exoid, VARCONN, start, count, lptr); \
      free(lptr); \
   } \
 \
   if (iresult == -1) \
   { \
      exerrval = ncerr; \
      sprintf(errmsg, \
      "Error: failed to write connectivity array for %s block %d in file id %d", \
                TNAME,blk_id,exoid); \
      ex_err("ex_put_conn",errmsg, exerrval); \
      return(EX_FATAL); \
   }

   EX_WRITE_CONN(blk_typename,num_entry_this_blk,num_id_per_entry,connid,node_conn);

   /* If there are edge and face connectivity arrays that belong with the element
    * block, write them now. Warn if they are required but not specified or
    * specified but not required.
    */
   if ( blk_type == EX_ELEM_BLOCK ) {
     int nedpereldim, nfapereldim;
     long num_ed_per_elem, num_fa_per_elem;

     nedpereldim = ncdimid (exoid, DIM_NUM_EDG_PER_EL(blk_id_ndx));
     if (nedpereldim == -1 && elem_edge_conn != 0)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: edge connectivity specified but failed to "
         "locate number of edges/element in block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     nfapereldim = ncdimid (exoid, DIM_NUM_FAC_PER_EL(blk_id_ndx));
     if (nfapereldim == -1 && elem_face_conn != 0)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: face connectivity specified but failed to "
         "locate number of faces/element in block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     if (ncdiminq (exoid, nedpereldim, NULL, &num_ed_per_elem) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get number of edges/elem in block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     if (ncdiminq (exoid, nfapereldim, NULL, &num_fa_per_elem) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get number of edges/elem in block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     if ( (num_ed_per_elem == 0 && elem_edge_conn != 0) ||
          (num_ed_per_elem != 0 && elem_edge_conn == 0) )
       {
       exerrval = (EX_FATAL);
       sprintf(errmsg,
         "Error: number of edges per element (%ld) doesn't "
         "agree with elem_edge_conn (0x%p)",
         num_ed_per_elem, elem_edge_conn );
       ex_err("ex_put_conn",errmsg,exerrval);
       return (EX_FATAL);
       }

     if ( (num_fa_per_elem == 0 && elem_face_conn != 0) ||
          (num_fa_per_elem != 0 && elem_face_conn == 0) )
       {
       exerrval = (EX_FATAL);
       sprintf(errmsg,
         "Error: number of faces per element (%ld) doesn't "
         "agree with elem_face_conn (0x%p)",
         num_fa_per_elem, elem_face_conn );
       ex_err("ex_put_conn",errmsg,exerrval);
       return (EX_FATAL);
       }

     if ( num_ed_per_elem != 0 ) {
       connid = ncvarid (exoid, VAR_ECONN(blk_id_ndx));
       if (connid == -1)
         {
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to locate connectivity array for "
           "element edge block %d in file id %d",
           blk_id,exoid);
         ex_err("ex_put_conn",errmsg, exerrval);
         return(EX_FATAL);
         }
       EX_WRITE_CONN("element edge",num_entry_this_blk,num_ed_per_elem,connid,elem_edge_conn);
     }

     if ( num_fa_per_elem != 0 ) {
       connid = ncvarid (exoid, VAR_FCONN(blk_id_ndx));
       if (connid == -1)
         {
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to locate connectivity array for "
           "element face block %d in file id %d",
           blk_id,exoid);
         ex_err("ex_put_conn",errmsg, exerrval);
         return(EX_FATAL);
         }
       EX_WRITE_CONN("element face",num_entry_this_blk,num_fa_per_elem,connid,elem_face_conn);
     }
   }

   return (EX_NOERR);

}
Ejemplo n.º 11
0
int ex_get_block( int exoid,
  int blk_type,
  int blk_id,
  char* elem_type,
  int* num_entries_this_blk,
  int* num_nodes_per_entry,
  int* num_edges_per_entry,
  int* num_faces_per_entry,
  int* num_attr_per_entry )
{
   int dimid, connid, len, blk_id_ndx;
   long lnum_entries_this_blk, lnum_nodes_per_entry, lnum_attr_per_entry;
   long lnum_edges_per_entry, lnum_faces_per_entry;
   char *ptr;
   char  errmsg[MAX_ERR_LENGTH];
   nc_type dummy;
   const char* tname;
   const char* dnument;
   const char* dnumnod;
   const char* dnumedg;
   const char* dnumfac;
   const char* dnumatt;
   const char* ablknam;
   const char* vblkcon;
   const char* vblkids;

   exerrval = 0;

   /* First, locate index of element block id in VAR_ID_EL_BLK array */
   switch (blk_type) {
   case EX_EDGE_BLOCK:
     tname = "edge";
     vblkids = VAR_ID_ED_BLK;
     blk_id_ndx = ex_id_lkup(exoid,vblkids,blk_id);
     dnument = DIM_NUM_ED_IN_EBLK(blk_id_ndx);
     dnumnod = DIM_NUM_NOD_PER_ED(blk_id_ndx);
     dnumedg = 0;
     dnumfac = 0;
     dnumatt = DIM_NUM_ATT_IN_EBLK(blk_id_ndx);
     vblkcon = VAR_EBCONN(blk_id_ndx);
     ablknam = ATT_NAME_ELB;
     break;
   case EX_FACE_BLOCK:
     tname = "face";
     vblkids = VAR_ID_FA_BLK;
     blk_id_ndx = ex_id_lkup(exoid,vblkids,blk_id);
     dnument = DIM_NUM_FA_IN_FBLK(blk_id_ndx);
     dnumnod = DIM_NUM_NOD_PER_FA(blk_id_ndx);
     dnumedg = 0; /* it is possible this might be non-NULL some day */
     dnumfac = 0;
     dnumatt = DIM_NUM_ATT_IN_FBLK(blk_id_ndx);
     vblkcon = VAR_FBCONN(blk_id_ndx);
     ablknam = ATT_NAME_ELB;
     break;
   case EX_ELEM_BLOCK:
     tname = "element";
     vblkids = VAR_ID_EL_BLK;
     blk_id_ndx = ex_id_lkup(exoid,vblkids,blk_id);
     dnument = DIM_NUM_EL_IN_BLK(blk_id_ndx);
     dnumnod = DIM_NUM_NOD_PER_EL(blk_id_ndx);
     dnumedg = DIM_NUM_EDG_PER_EL(blk_id_ndx);
     dnumfac = DIM_NUM_FAC_PER_EL(blk_id_ndx);
     dnumatt = DIM_NUM_ATT_IN_BLK(blk_id_ndx);
     vblkcon = VAR_CONN(blk_id_ndx);
     ablknam = ATT_NAME_ELB;
     break;
   default:
     exerrval = EX_BADPARAM;
     sprintf( errmsg, "Bad block type parameter (%d) specified for file id %d.",
       blk_type, exoid );
     return (EX_FATAL);
   }

   if (exerrval != 0) 
     {
     if (exerrval == EX_NULLENTITY)     /* NULL element block?    */
       {
       if ( elem_type )
         strcpy(elem_type, "NULL");     /* NULL element type name */
       *num_entries_this_blk = 0;       /* no elements            */
       *num_nodes_per_entry = 0;        /* no nodes               */
       *num_attr_per_entry = 0;         /* no attributes          */
       return (EX_NOERR);
       }
     else
       {
       sprintf(errmsg,
        "Error: failed to locate element block id %d in %s array in file id %d",
               blk_id,vblkids,exoid);
       ex_err("ex_get_block",errmsg,exerrval);
       return (EX_FATAL);
       }
     }

   /* inquire values of some dimensions */
   if ( num_entries_this_blk )
     {
     if ((dimid = ncdimid (exoid, dnument)) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to locate number of %ss in block %d in file id %d",
         tname,blk_id,exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }

     if (ncdiminq (exoid, dimid, (char *) 0, &lnum_entries_this_blk) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get number of %ss in block %d in file id %d",
         tname,blk_id, exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }
     *num_entries_this_blk = lnum_entries_this_blk;
     }

   if ( num_nodes_per_entry )
     {
     if ((dimid = ncdimid (exoid, dnumnod)) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to locate number of nodes/%s in block %d in file id %d",
         tname,blk_id,exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }
     if (ncdiminq (exoid, dimid, (char *) 0, &lnum_nodes_per_entry) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get number of nodes/%s in block %d in file id %d",
         tname,blk_id, exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }
     *num_nodes_per_entry = lnum_nodes_per_entry;
     }

   if ( num_edges_per_entry )
     {
     if ( blk_type != EX_ELEM_BLOCK )
       {
       exerrval = (EX_WARN);
       sprintf(errmsg,
         "Warning: non-NULL pointer passed to num_edges_per_entry for %s block query in file id %d",
         tname,exoid);
       ex_err("ex_get_block",errmsg,exerrval);
       }
     else
       {
       if ((dimid = ncdimid (exoid, dnumedg)) == -1)
         {
         /* undefined => no edge entries per element */
         lnum_edges_per_entry = 0;
         }
       else
         {
         if (ncdiminq (exoid, dimid, (char *) 0, &lnum_edges_per_entry) == -1)
           {
           exerrval = ncerr;
           sprintf(errmsg,
             "Error: failed to get number of edges/%s in block %d in file id %d",
             tname,blk_id, exoid);
           ex_err("ex_get_block",errmsg, exerrval);
           return(EX_FATAL);
           }
         }
       *num_edges_per_entry = lnum_edges_per_entry;
       }
     }

   if ( num_faces_per_entry )
     {
     if ( blk_type != EX_ELEM_BLOCK )
       {
       exerrval = (EX_WARN);
       sprintf(errmsg,
         "Warning: non-NULL pointer passed to num_faces_per_entry for %s block query in file id %d",
         tname,exoid);
       ex_err("ex_get_block",errmsg,exerrval);
       }
     else
       {
       if ((dimid = ncdimid (exoid, dnumfac)) == -1)
         {
         /* undefined => no face entries per element */
         lnum_faces_per_entry = 0;
         }
       else
         {
         if (ncdiminq (exoid, dimid, (char *) 0, &lnum_faces_per_entry) == -1)
           {
           exerrval = ncerr;
           sprintf(errmsg,
             "Error: failed to get number of faces/%s in block %d in file id %d",
             tname,blk_id, exoid);
           ex_err("ex_get_block",errmsg, exerrval);
           return(EX_FATAL);
           }
         }
         *num_faces_per_entry = lnum_faces_per_entry;
       }
     }

   if ( num_attr_per_entry )
     {
     if ((dimid = ncdimid (exoid, dnumatt)) == -1)
       {
       /* dimension is undefined */
       *num_attr_per_entry = 0;
       }
     else
       {
       if (ncdiminq (exoid, dimid, (char *) 0, &lnum_attr_per_entry) == -1)
         {
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to get number of attributes in %s block %d in file id %d",
           tname,blk_id, exoid);
         ex_err("ex_get_block",errmsg, exerrval);
         return(EX_FATAL);
         }
       *num_attr_per_entry = lnum_attr_per_entry;
       }
     }

   if ( elem_type )
     {
     /* look up connectivity array for this element block id */
     if ((connid = ncvarid (exoid, vblkcon)) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to locate connectivity array for element block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }

     if (ncattinq (exoid, connid, ablknam, &dummy, &len) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get element block %d type in file id %d",
         blk_id,exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }

     if (len > (MAX_STR_LENGTH+1))
       {
       len = MAX_STR_LENGTH;
       sprintf (errmsg,
         "Warning: element block %d type will be truncated to %d chars", 
         blk_id,len);
       ex_err("ex_get_block",errmsg,EX_MSG);
       }
     /* get the element type name */

     if (ncattget (exoid, connid, ablknam, elem_type) == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,"Error: failed to get element block %d type in file id %d",
         blk_id, exoid);
       ex_err("ex_get_block",errmsg, exerrval);
       return(EX_FATAL);
       }

     /* get rid of trailing blanks */
     ptr = elem_type;
     /* fprintf(stderr,"[exgblk] %s, len: %d\n",ptr,len); */
     while (ptr < elem_type + len && *ptr != ' ')
       {
       ptr++;
       }
     *(ptr) = '\0';
     }

   return (EX_NOERR);
}
Ejemplo n.º 12
0
int ex_get_coord_names (int    exoid,
                        char **coord_names)
{
    int i, j, ndimdim, varid;
    long num_dim, start[2];
    char *ptr;
    char errmsg[MAX_ERR_LENGTH];

    exerrval = 0;

    /* inquire previously defined dimensions and variables  */

    if ((ndimdim = ncdimid (exoid, DIM_NUM_DIM)) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to locate number of dimensions in file id %d",
                exoid);
        ex_err("ex_get_coord_names",errmsg,exerrval);
        return (EX_FATAL);
    }

    if (ncdiminq (exoid, ndimdim, (char *) 0, &num_dim) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of dimensions in file id %d",
                exoid);
        ex_err("ex_get_coord_names",errmsg,exerrval);
        return (EX_FATAL);
    }

    if ((varid = ncvarid (exoid, VAR_NAME_COOR)) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Warning: failed to locate coordinate names in file id %d",
                exoid);
        ex_err("ex_get_coord_names",errmsg,exerrval);
        return (EX_WARN);
    }


    /* read the coordinate names */

    for (i=0; i<num_dim; i++)
    {
        start[0] = i;
        start[1] = 0;

        j = 0;
        ptr = coord_names[i];

        if (ncvarget1 (exoid, varid, start, ptr) == -1)
        {
            exerrval = ncerr;
            sprintf(errmsg,
                    "Error: failed to get coordinate names in file id %d", exoid);
            ex_err("ex_get_coord_names",errmsg,exerrval);
            return (EX_FATAL);
        }


        while ((*ptr++ != '\0') && (j < MAX_STR_LENGTH))
        {
            start[1] = ++j;
            if (ncvarget1 (exoid, varid, start, ptr) == -1)
            {
                exerrval = ncerr;
                sprintf(errmsg,
                        "Error: failed to get coordinate names in file id %d", exoid);
                ex_err("ex_get_coord_names",errmsg,exerrval);
                return (EX_FATAL);
            }
        }
        --ptr;
        if (ptr > coord_names[i]) {
            /*    get rid of trailing blanks */
            while (*(--ptr) == ' ');
        }
        *(++ptr) = '\0';
    }

    return (EX_NOERR);

}
Ejemplo n.º 13
0
int ex_put_set (int   exoid,
		int   set_type,
		int   set_id,
		const int  *set_entry_list,
		const int  *set_extra_list)
{
   int dimid, iresult;
   int entry_list_id, extra_list_id, set_id_ndx;
   long  num_entries_in_set, start[1], count[1]; 
   nclong *lptr;
   char errmsg[MAX_ERR_LENGTH];
   char* typeName;
   char* dimptr;
   char* idsptr;
   char* numentryptr;
   char* entryptr;
   char* extraptr;

   exerrval = 0; /* clear error code */

   /* setup pointers based on set_type 
    NOTE: there is another block that sets more stuff later ... */
   if (set_type == EX_NODE_SET) {
     typeName = "node";
     dimptr = DIM_NUM_NS;
     idsptr = VAR_NS_IDS;
   }
   else if (set_type == EX_EDGE_SET) {
     typeName = "edge";
     dimptr = DIM_NUM_ES;
     idsptr = VAR_ES_IDS;
   }
   else if (set_type == EX_FACE_SET) {
     typeName = "face";
     dimptr = DIM_NUM_FS;
     idsptr = VAR_FS_IDS;
   }
   else if (set_type == EX_SIDE_SET) {
     typeName = "side";
     dimptr = DIM_NUM_SS;
     idsptr = VAR_SS_IDS;
   }
   else if (set_type == EX_ELEM_SET) {
     typeName = "elem";
     dimptr = DIM_NUM_ELS;
     idsptr = VAR_ELS_IDS;
   }
   else {
     exerrval = EX_FATAL;
     sprintf(errmsg,
	     "Error: invalid set type (%d)", set_type);
     ex_err("ex_put_set_param",errmsg,exerrval);
     return (EX_FATAL);
   }

/* first check if any sets are specified */

   if ((dimid = ncdimid (exoid, dimptr)) < 0)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: no %s sets defined in file id %d",
             typeName, exoid);
     ex_err("ex_put_set",errmsg,exerrval);
     return (EX_FATAL);
   }

/* Lookup index of set id in VAR_*S_IDS array */

   set_id_ndx = ex_id_lkup(exoid,idsptr,set_id);
   if (exerrval != 0) 
   {
     if (exerrval == EX_NULLENTITY)
     {
       sprintf(errmsg,
              "Warning: no data allowed for NULL %s set %d in file id %d",
               typeName,set_id,exoid);
       ex_err("ex_put_set",errmsg,EX_MSG);
       return (EX_WARN);
     }
     else
     {
       sprintf(errmsg,
     "Error: failed to locate %s set id %d in VAR_*S_IDS array in file id %d",
               typeName, set_id,exoid);
       ex_err("ex_put_set",errmsg,exerrval);
       return (EX_FATAL);
     }
   }

  /* setup more pointers based on set_type */
   if (set_type == EX_NODE_SET) {
     numentryptr = DIM_NUM_NOD_NS(set_id_ndx);
     entryptr = VAR_NODE_NS(set_id_ndx);
     extraptr = NULL;
   }
   else if (set_type == EX_EDGE_SET) {
     numentryptr = DIM_NUM_EDGE_ES(set_id_ndx);
     entryptr = VAR_EDGE_ES(set_id_ndx);
     extraptr = VAR_ORNT_ES(set_id_ndx);
   }
   else if (set_type == EX_FACE_SET) {
     numentryptr = DIM_NUM_FACE_FS(set_id_ndx);
     entryptr = VAR_FACE_FS(set_id_ndx);
     extraptr = VAR_ORNT_FS(set_id_ndx);
   }
   else if (set_type == EX_SIDE_SET) {
     numentryptr = DIM_NUM_SIDE_SS(set_id_ndx);
     entryptr = VAR_ELEM_SS(set_id_ndx);
     extraptr = VAR_SIDE_SS(set_id_ndx);
   }
   if (set_type == EX_ELEM_SET) {
     numentryptr = DIM_NUM_ELE_ELS(set_id_ndx);
     entryptr = VAR_ELEM_ELS(set_id_ndx);
     extraptr = NULL;
   }

/* inquire id's of previously defined dimensions  */

   if ((dimid = ncdimid (exoid, numentryptr)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to locate number of entities in %s set %d in file id %d",
             typeName, set_id,exoid);
     ex_err("ex_put_set",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (ncdiminq (exoid, dimid, (char *) 0, &num_entries_in_set) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
         "Error: failed to get number of entities in %s set %d in file id %d",
             typeName, set_id,exoid);
     ex_err("ex_put_set",errmsg,exerrval);
     return (EX_FATAL);
   }

/* inquire id's of previously defined variables  */

   if ((entry_list_id = ncvarid (exoid, entryptr)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
           "Error: failed to locate entry list for %s set %d in file id %d",
	     typeName, set_id,exoid);
     ex_err("ex_put_set",errmsg,exerrval);
     return (EX_FATAL);
   }

   /* only do for edge, face and side sets */
   if (extraptr) 
     {
       if ((extra_list_id = ncvarid (exoid, extraptr)) == -1)
	 {
	   exerrval = ncerr;
	   sprintf(errmsg,
		   "Error: failed to locate extra list for %s set %d in file id %d",
		   typeName, set_id,exoid);
	   ex_err("ex_put_set",errmsg,exerrval);
	   return (EX_FATAL);
	 }
     }


/* write out the entry list and extra list arrays */

/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */

   start[0] = 0;
   count[0] = num_entries_in_set;

   if (sizeof(int) == sizeof(nclong)) {
      iresult = ncvarput(exoid, entry_list_id, start, count, set_entry_list);
   } else {
      lptr = itol (set_entry_list, (int)num_entries_in_set);
      iresult = ncvarput (exoid, entry_list_id, start, count, lptr);
      free(lptr);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to store entry list for %s set %d in file id %d",
             typeName, set_id,exoid);
     ex_err("ex_put_set",errmsg,exerrval);
     return (EX_FATAL);
   }


/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */

   /* only do for edge, face and side sets */
   if (extraptr)
     {
       if (sizeof(int) == sizeof(nclong)) {
	 iresult = ncvarput(exoid, extra_list_id, start, count, set_extra_list);
       } else {
	 lptr = itol (set_extra_list, (int)num_entries_in_set);
	 iresult = ncvarput (exoid, extra_list_id, start, count, lptr);
	 free(lptr);
       }

       if (iresult == -1)
	 {
	   exerrval = ncerr;
	   sprintf(errmsg,
		   "Error: failed to store extra list for %s set %d in file id %d",
		   typeName, set_id,exoid);
	   ex_err("ex_put_set",errmsg,exerrval);
	   return (EX_FATAL);
	 }
     }

   /* warn if extra data was sent in for node sets and elem sets */
   if ((set_type == EX_NODE_SET || set_type == EX_ELEM_SET) &&
       set_extra_list != NULL)
     {
       sprintf(errmsg,
	       "Warning: extra list was ignored for %s set %d in file id %d",
	       typeName, set_id, exoid);
       ex_err("ex_put_set",errmsg,EX_MSG);
       return(EX_WARN); 
     }

   return (EX_NOERR);

}
Ejemplo n.º 14
0
int ex_put_side_set_dist_fact (int   exoid,
                               int   side_set_id,
                               const void *side_set_dist_fact)
{
   int dimid, side_set_id_ndx;
   int dist_id;
   long num_df_in_set,  start[1], count[1];
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

/* first check if any side sets are specified */

   if ((dimid = ncdimid (exoid, DIM_NUM_SS)) < 0)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: no side sets specified in file id %d",
             exoid);
     ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
     return (EX_FATAL);
   }

/* Lookup index of side set id in VAR_SS_IDS array */

   side_set_id_ndx = ex_id_lkup(exoid,VAR_SS_IDS,side_set_id);
   if (exerrval != 0) 
   {
     if (exerrval == EX_NULLENTITY)
     {
       sprintf(errmsg,
              "Warning: no data allowed for NULL side set %d in file id %d",
               side_set_id,exoid);
       ex_err("ex_put_side_set_fact",errmsg,EX_MSG);
       return (EX_WARN);
     }
     else
     {
      sprintf(errmsg,
     "Error: failed to locate side set id %d in VAR_SS_IDS array in file id %d",
               side_set_id,exoid);
       ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
       return (EX_FATAL);
     }
   }

/* inquire id's of previously defined dimension and variable */

   if ((dimid = ncdimid (exoid, DIM_NUM_DF_SS(side_set_id_ndx))) == -1)
   {
     if (ncerr == NC_EBADDIM)
     {
       exerrval = EX_BADPARAM;
       sprintf(errmsg,
              "Warning: no dist factors defined for side set %d in file id %d",
               side_set_id,exoid);
       ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
       return (EX_WARN);

     }
     else
     {
       exerrval = ncerr;
       sprintf(errmsg,
  "Error: failed to locate number of dist factors in side set %d in file id %d",
               side_set_id,exoid);
       ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
       return (EX_FATAL);
     }
   }

   if (ncdiminq (exoid, dimid, (char *) 0, &num_df_in_set) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
     "Error: failed to get number of dist factors in side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
     return (EX_FATAL);
   }


   if ((dist_id = ncvarid (exoid, VAR_FACT_SS(side_set_id_ndx))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to locate dist factors list for side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
     return (EX_FATAL);
   }


/* write out the distribution factors array */

   start[0] = 0;

   count[0] = num_df_in_set;

   if (ncvarput (exoid, dist_id, start, count,
             ex_conv_array(exoid,WRITE_CONVERT,side_set_dist_fact,
                           (int)num_df_in_set)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to store dist factors for side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set_dist_fact",errmsg,exerrval);
     return (EX_FATAL);
   }

   return (EX_NOERR);

}
Ejemplo n.º 15
0
int ex_put_one_attr( int   exoid,
                     int   obj_type,
                     int   obj_id,
                     int   attrib_index,
                     const void *attrib )
{
  int numobjentdim, numattrdim, attrid, obj_id_ndx;
  long num_entries_this_obj, num_attr;
  size_t start[2], count[2];
  ptrdiff_t stride[2];
  int error;
  char errmsg[MAX_ERR_LENGTH];
  const char* tname;
  const char* vobjids;
  const char* dnumobjent = 0;
  const char* dnumobjatt = 0;
  const char* vattrbname = 0;

  switch (obj_type) {
  case EX_EDGE_BLOCK:
    tname = "edge block";
    vobjids = VAR_ID_ED_BLK;
    break;
  case EX_FACE_BLOCK:
    tname = "face block";
    vobjids = VAR_ID_FA_BLK;
    break;
  case EX_ELEM_BLOCK:
    tname = "element block";
    vobjids = VAR_ID_EL_BLK;
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Bad block type (%d) specified for file id %d",
      obj_type, exoid );
    ex_err("ex_put_attr",errmsg,exerrval);
    return (EX_FATAL);
  }

  exerrval = 0; /* clear error code */

  /* Determine index of obj_id in vobjids array */
  obj_id_ndx = ex_id_lkup(exoid,vobjids,obj_id);
  if (exerrval != 0) 
    {
      if (exerrval == EX_NULLENTITY)
        {
          sprintf(errmsg,
                  "Warning: no attributes allowed for NULL %s %d in file id %d",
                  tname,obj_id,exoid);
          ex_err("ex_put_one_attr",errmsg,EX_MSG);
          return (EX_WARN);              /* no attributes for this element block */
        }
      else
        {
          sprintf(errmsg,
                  "Error: no %s id %d in %s array in file id %d",
                  tname, obj_id, vobjids, exoid);
          ex_err("ex_put_one_attr",errmsg,exerrval);
          return (EX_FATAL);
        }
    }

  switch (obj_type) {
  case EX_EDGE_BLOCK:
    dnumobjent = DIM_NUM_ED_IN_EBLK(obj_id_ndx);
    dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx);
    vattrbname = VAR_EATTRIB(obj_id_ndx);
    break;
  case EX_FACE_BLOCK:
    dnumobjent = DIM_NUM_FA_IN_FBLK(obj_id_ndx);
    dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx);
    vattrbname = VAR_FATTRIB(obj_id_ndx);
    break;
  case EX_ELEM_BLOCK:
    dnumobjent = DIM_NUM_EL_IN_BLK(obj_id_ndx);
    dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx);
    vattrbname = VAR_ATTRIB(obj_id_ndx);
    break;
  }

  /* inquire id's of previously defined dimensions  */
  if ((numobjentdim = ncdimid (exoid, dnumobjent)) == -1)
    {
      if (ncerr == NC_EBADDIM)
        {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: no %s with id %d in file id %d",
                  tname, obj_id, exoid);
          ex_err("ex_put_one_attr",errmsg,exerrval);
          return (EX_FATAL);
        }
      else
        {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: failed to locate number of entries for %s %d in file id %d",
                  tname, obj_id, exoid);
          ex_err("ex_put_one_attr",errmsg,exerrval);
          return (EX_FATAL);
        }
    }


  if (ncdiminq (exoid, numobjentdim, (char *) 0, &num_entries_this_obj) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get number of entries for %s %d in file id %d",
              tname,obj_id,exoid);
      ex_err("ex_put_one_attr",errmsg,exerrval);
      return (EX_FATAL);
    }


  if ((numattrdim = ncdimid(exoid, dnumobjatt)) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: number of attributes not defined for %s %d in file id %d",
              tname,obj_id,exoid);
      ex_err("ex_put_one_attr",errmsg,EX_MSG);
      return (EX_FATAL);              /* number of attributes not defined */
    }

  if (ncdiminq (exoid, numattrdim, (char *) 0, &num_attr) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get number of attributes for block %d in file id %d",
              obj_id,exoid);
      ex_err("ex_put_one_attr",errmsg,exerrval);
      return (EX_FATAL);
    }

  if (attrib_index < 1 || attrib_index > num_attr) {
    exerrval = EX_FATAL;
    sprintf(errmsg,
            "Error: Invalid attribute index specified: %d.  Valid range is 1 to %ld for %s %d in file id %d",
            attrib_index, num_attr, tname, obj_id, exoid);
    ex_err("ex_put_one_attr",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((attrid = ncvarid (exoid, vattrbname)) == -1)
    {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to locate attribute variable for %s %d in file id %d",
              tname,obj_id,exoid);
      ex_err("ex_put_one_attr",errmsg,exerrval);
      return (EX_FATAL);
    }


  /* write out the attributes  */

  start[0] = 0;
  start[1] = attrib_index-1;

  count[0] = num_entries_this_obj;
  count[1] = 1;

  stride[0] = 1;
  stride[1] = num_attr;
  
  if (nc_flt_code(exoid) == NC_FLOAT) {
    error = nc_put_vars_float(exoid, attrid, start, count, stride,
                              ex_conv_array(exoid,WRITE_CONVERT,attrib,
                                            (int)num_attr*num_entries_this_obj));
  } else {
    error = nc_put_vars_double(exoid, attrid, start, count, stride,
                               ex_conv_array(exoid,WRITE_CONVERT,attrib,
                                             (int)num_attr*num_entries_this_obj));
  }
  if (error == -1) {
    exerrval = ncerr;
    sprintf(errmsg,
            "Error: failed to put attribute %d for %s %d in file id %d",
            attrib_index, tname, obj_id, exoid);
    ex_err("ex_put_one_attr",errmsg,exerrval);
    return (EX_FATAL);
  }


  return(EX_NOERR);

}
Ejemplo n.º 16
0
int ex_put_map (int  exoid,
                const int *elem_map)
{
   int numelemdim, dims[1], mapid, iresult;
   long num_elem, start[1], count[1]; 
   nclong *lptr;
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

/* inquire id's of previously defined dimensions  */

  /* determine number of elements. Return if zero... */
   if ((numelemdim = ncdimid (exoid, DIM_NUM_ELEM)) == -1)
   {
     return (EX_NOERR);
   }

   if (ncdiminq (exoid, numelemdim, (char *) 0, &num_elem) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to get number of elements in file id %d",
             exoid);
     ex_err("ex_put_map",errmsg,exerrval);
     return (EX_FATAL);
   }


/* put netcdf file into define mode  */

   if (ncredef (exoid) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to put file id %d into define mode",
             exoid);
     ex_err("ex_put_map",errmsg,exerrval);
     return (EX_FATAL);
   }


/* create a variable array in which to store the element map  */

   dims[0] = numelemdim;

   if ((mapid = ncvardef (exoid, VAR_MAP, NC_LONG, 1, dims)) == -1)
   {
   if (ncerr == NC_ENAMEINUSE)
     {
       exerrval = ncerr;
       sprintf(errmsg,
              "Error: element map already exists in file id %d",
               exoid);
       ex_err("ex_put_map",errmsg,exerrval);
     }
     else
     {
       exerrval = ncerr;
       sprintf(errmsg,
              "Error: failed to create element map array in file id %d",
               exoid);
       ex_err("ex_put_map",errmsg,exerrval);
     }
     goto error_ret;         /* exit define mode and return */
   }


/* leave define mode  */

   if (ncendef (exoid) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to complete definition in file id %d",
             exoid);
     ex_err("ex_put_map",errmsg,exerrval);
     return (EX_FATAL);
   }


/* write out the element order map  */

/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */

   start[0] = 0;
   count[0] = num_elem;

   if (sizeof(int) == sizeof(nclong)) {
      iresult = ncvarput (exoid, mapid, start, count, elem_map);
   } else {
      lptr = itol (elem_map, (int)num_elem);
      iresult = ncvarput (exoid, mapid, start, count, lptr);
      free(lptr);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to store element map in file id %d",
             exoid);
     ex_err("ex_put_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   return (EX_NOERR);

/* Fatal error: exit definition mode and return */
error_ret:
       if (ncendef (exoid) == -1)     /* exit define mode */
       {
         sprintf(errmsg,
                "Error: failed to complete definition for file id %d",
                 exoid);
         ex_err("ex_put_map",errmsg,exerrval);
       }
       return (EX_FATAL);
}
Ejemplo n.º 17
0
void
mexFunction	(
	INT			nlhs,
	Matrix	*	plhs[],
	INT			nrhs,
	const Matrix	*	prhs[]
	)

{
	char		*	opname;
	OPCODE			opcode;
	
	Matrix		*	mat;
	
	int				status;
	char		*	path;
	int				cmode;
	int				mode;
	int				cdfid;
	int				ndims;
	int				nvars;
	int				natts;
	int				recdim;
	char		*	name;
	long			length;
	int				dimid;
	nc_type			datatype;
	int			*	dim;
	int				varid;
	long		*	coords;
	VOIDP			value;
	long		*	start;
	long		*	count;
	int			*	intcount;
	long		*	stride;
	long		*	imap;
	long			recnum;
	int				nrecvars;
	int			*	recvarids;
	long		*	recsizes;
	VOIDPP			datap;		/*	pointers for record access.	*/
	int				len;
	int				incdf;
	int				invar;
	int				outcdf;
	int				outvar;
	int				attnum;
	char		*	attname;
	char		*	newname;
	int				fillmode;
	
	int				i;
	int				m;
	int				n;
	char		*	p;
	char			buffer[MAX_BUFFER];
	
	DOUBLE		*	pr;
	DOUBLE			addoffset;
	DOUBLE			scalefactor;
	int				autoscale;		/*	do auto-scaling if this flag is non-zero.	*/
	
	/*	Disable the NC_FATAL option from ncopts.	*/
	
	if (ncopts & NC_FATAL)	{
		ncopts -= NC_FATAL;
	}
	
	/*	Display usage if less than one input argument.	*/
	
	if (nrhs < 1)	{
	
		Usage();
		
		return;
	}
	
	/*	Convert the operation name to its opcode.	*/
	
	opname = Mat2Str(prhs[0]);
	for (i = 0; i < strlen(opname); i++)	{
		opname[i] = (char) tolower((int) opname[i]);
	}
	p = opname;
	if (strncmp(p, "nc", 2) == 0)	{	/*	Trim away "nc".	*/
		p += 2;
	}
	
	i = 0;
	opcode = NONE;
	while (ops[i].opcode != NONE)	{
		if (!strcmp(p, ops[i].opname))	{
			opcode = ops[i].opcode;
			if (ops[i].nrhs > nrhs)	{
				mexPrintf("MEXCDF: opname = %s\n", opname);
				mexErrMsgTxt("MEXCDF: Too few input arguments.\n");
			}
			else if (0 && ops[i].nlhs > nlhs)	{	/*	Disabled.	*/
				mexPrintf("MEXCDF: opname = %s\n", opname);
				mexErrMsgTxt("MEXCDF: Too few output arguments.\n");
			}
			break;
		}
		else	{
			i++;
		}
	}
	
	if (opcode == NONE)	{
		mexPrintf("MEXCDF: opname = %s\n", opname);
		mexErrMsgTxt("MEXCDF: No such operation.\n");
	}
	
	Free((VOIDPP) & opname);
	
	/*	Extract the cdfid by number.	*/
	
	switch (opcode)	{
	
	case USAGE:
	case CREATE:
	case OPEN:
	case TYPELEN:
	case SETOPTS:
	case ERR:
	case PARAMETER:
	
		break;
	
	default:

		cdfid = Scalar2Int(prhs[1]);
	
		break;
	}
	
	/*	Extract the dimid by number or name.	*/
	
	switch (opcode)	{

	case DIMINQ:
	case DIMRENAME:
	
		if (mxIsNumeric(prhs[2]))	{
			dimid = Scalar2Int(prhs[2]);
		}
		else	{
			name = Mat2Str(prhs[2]);
			dimid = ncdimid(cdfid, name);
			Free((VOIDPP) & name);
		}
		break;
	
	default:
	
		break;
	}
	
	/*	Extract the varid by number or name.	*/
	
	switch (opcode)	{

	case VARINQ:
	case VARPUT1:
	case VARGET1:
	case VARPUT:
	case VARGET:
	case VARPUTG:
	case VARGETG:
	case VARRENAME:
	case VARCOPY:
	case ATTPUT:
	case ATTINQ:
	case ATTGET:
	case ATTCOPY:
	case ATTNAME:
	case ATTRENAME:
	case ATTDEL:
	
		if (mxIsNumeric(prhs[2]))	{
			varid = Scalar2Int(prhs[2]);
		}
		else	{
			name = Mat2Str(prhs[2]);
			varid = ncvarid(cdfid, name);
			Free((VOIDPP) & name);
			if (varid == -1)	{
				varid = Parameter(prhs[2]);
			}
		}
		break;
	
	default:
	
		break;
	}
	
	/*	Extract the attname by name or number.	*/
	
	switch (opcode)	{
	
	case ATTPUT:
	case ATTINQ:
	case ATTGET:
	case ATTCOPY:
	case ATTRENAME:
	case ATTDEL:
	
		if (mxIsNumeric(prhs[3]))	{
			attnum = Scalar2Int(prhs[3]);
			attname = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
			status = ncattname(cdfid, varid, attnum, attname);
		}
		else	{
			attname = Mat2Str(prhs[3]);
		}
		break;
	
	default:
	
		break;
	}
	
	/*	Extract the "add_offset" and "scale_factor" attributes.	*/
	
	switch (opcode)	{
	
	case VARPUT1:
	case VARGET1:
	case VARPUT:
	case VARGET:
	case VARPUTG:
	case VARGETG:

		addoffset = Add_Offset(cdfid, varid);
		scalefactor = Scale_Factor(cdfid, varid);
		if (scalefactor == 0.0)	{
			scalefactor = 1.0;
		}
		
		break;
	
	default:
	
		break;
	}
	
	/*	Perform the NetCDF operation.	*/
	
	switch (opcode)	{
		
	case USAGE:
	
		Usage();
		
		break;
	
	case CREATE:
		
		path = Mat2Str(prhs[1]);
		
		if (nrhs > 2)	{
			cmode = Parameter(prhs[2]);
		}
		else	{
			cmode = NC_NOCLOBBER;	/*	Default.	*/
		}
		
		cdfid = nccreate(path, cmode);
		
		plhs[0] = Int2Scalar(cdfid);
		plhs[1] = Int2Scalar((cdfid >= 0) ? 0 : -1);
		
		Free((VOIDPP) & path);
		
		break;
		
	case OPEN:
		
		path = Mat2Str(prhs[1]);
		
		if (nrhs > 2)	{
			mode = Parameter(prhs[2]);
		}
		else	{
			mode = NC_NOWRITE;	/*	Default.	*/
		}
		
		cdfid = ncopen(path, mode);
		
		plhs[0] = Int2Scalar(cdfid);
		plhs[1] = Int2Scalar((cdfid >= 0) ? 0 : -1);
		
		Free((VOIDPP) & path);
		
		break;
		
	case REDEF:
		
		status = ncredef(cdfid);
		
		plhs[0] = Int2Scalar(status);
		
		break;
		
	case ENDEF:
		
		status = ncendef(cdfid);
		
		plhs[0] = Int2Scalar(status);
		
		break;
		
	case CLOSE:
		
		status = ncclose(cdfid);
		
		plhs[0] = Int2Scalar(status);
		
		break;
		
	case INQUIRE:
	
		status = ncinquire(cdfid, & ndims, & nvars, & natts, & recdim);
		
		if (nlhs > 1)	{
			plhs[0] = Int2Scalar(ndims);
			plhs[1] = Int2Scalar(nvars);
			plhs[2] = Int2Scalar(natts);
			plhs[3] = Int2Scalar(recdim);
			plhs[4] = Int2Scalar(status);
		}
		else	{	/*	Default to 1 x 5 row vector.	*/
			plhs[0] = mxCreateFull(1, 5, REAL);
			pr = mxGetPr(plhs[0]);
			if (status == 0)	{
				pr[0] = (DOUBLE) ndims;
				pr[1] = (DOUBLE) nvars;
				pr[2] = (DOUBLE) natts;
				pr[3] = (DOUBLE) recdim;
			}
			pr[4] = (DOUBLE) status;
		}
		
		break;
		
	case SYNC:
	
		status = ncsync(cdfid);
		
		plhs[0] = Int2Scalar(status);
		
		break;
		
	case ABORT:
	
		status = ncabort(cdfid);
		
		plhs[0] = Int2Scalar(status);
		
		break;
		
	case DIMDEF:
	
		name = Mat2Str(prhs[2]);
		length = Parameter(prhs[3]);
		
		dimid = ncdimdef(cdfid, name, length);
		
		plhs[0] = Int2Scalar(dimid);
		plhs[1] = Int2Scalar((dimid >= 0) ? 0 : dimid);
		
		Free((VOIDPP) & name);
		
		break;
		
	case DIMID:
	
		name = Mat2Str(prhs[2]);
		
		dimid = ncdimid(cdfid, name);
		
		plhs[0] = Int2Scalar(dimid);
		plhs[1] = Int2Scalar((dimid >= 0) ? 0 : dimid);
		
		Free((VOIDPP) & name);
		
		break;
		
	case DIMINQ:
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		
		status = ncdiminq(cdfid, dimid, name, & length);
		
		plhs[0] = Str2Mat(name);
		plhs[1] = Long2Scalar(length);
		plhs[2] = Int2Scalar(status);
		
		Free((VOIDPP) & name);
		
		break;
		
	case DIMRENAME:
		
		name = Mat2Str(prhs[3]);
		
		status = ncdimrename(cdfid, dimid, name);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & name);
		
		break;
		
	case VARDEF:
	
		name = Mat2Str(prhs[2]);
		datatype = (nc_type) Parameter(prhs[3]);
		ndims = Scalar2Int(prhs[4]);
		if (ndims == -1)	{
			ndims = Count(prhs[5]);
		}
		dim = Mat2Int(prhs[5]);
		
		varid = ncvardef(cdfid, name, datatype, ndims, dim);
		
		Free((VOIDPP) & name);
		
		plhs[0] = Int2Scalar(varid);
		plhs[1] = Int2Scalar((varid >= 0) ? 0 : varid);
		
		break;
		
	case VARID:
	
		name = Mat2Str(prhs[2]);
		
		varid = ncvarid(cdfid, name);
		
		Free((VOIDPP) & name);
		
		plhs[0] = Int2Scalar(varid);
		plhs[1] = Int2Scalar((varid >= 0) ? 0 : varid);
		
		break;
		
	case VARINQ:
	
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		plhs[0] = Str2Mat(name);
		plhs[1] = Int2Scalar(datatype);
		plhs[2] = Int2Scalar(ndims);
		plhs[3] = Int2Mat(dim, 1, ndims);
		plhs[4] = Int2Scalar(natts);
		plhs[5] = Int2Scalar(status);
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		break;
		
	case VARPUT1:
		
		coords = Mat2Long(prhs[3]);
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		if (datatype == NC_CHAR)	{
			mat = SetNum(prhs[4]);
		}
		else	{
			mat = prhs[4];
		}
		if (mat == NULL)	{
			mat = prhs[4];
		}
		
		pr = mxGetPr(mat);
		
		autoscale = (nrhs > 5 && Scalar2Int(prhs[5]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		status = Convert(opcode, datatype, 1, buffer, scalefactor, addoffset, pr);
		status = ncvarput1(cdfid, varid, coords, buffer);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & coords);
		
		break;
		
	case VARGET1:
		
		coords = Mat2Long(prhs[3]);
		
		autoscale = (nrhs > 4 && Scalar2Int(prhs[4]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		mat = Int2Scalar(0);
		
		pr = mxGetPr(mat);
		
		status = ncvarget1(cdfid, varid, coords, buffer);
		status = Convert(opcode, datatype, 1, buffer, scalefactor, addoffset, pr);
		
		if (datatype == NC_CHAR)	{
			plhs[0] = SetStr(mat);
		}
		else	{
			plhs[0] = mat;
		}
		if (plhs[0] == NULL)	{
/*			prhs[0] = mat;		*/
			plhs[0] = mat;		/*	ZYDECO 24Jan2000	*/
		}
		
		plhs[1] = Int2Scalar(status);
		
		Free((VOIDPP) & coords);
		
		break;
		
	case VARPUT:
		
		start = Mat2Long(prhs[3]);
		count = Mat2Long(prhs[4]);
		
		autoscale = (nrhs > 6 && Scalar2Int(prhs[6]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		if (datatype == NC_CHAR)	{
			mat = SetNum(prhs[5]);
		}
		else	{
			mat = prhs[5];
		}
		if (mat == NULL)	{
			mat = prhs[5];
		}
		
		pr = mxGetPr(mat);
		
		for (i = 0; i < ndims; i++)	{
			if (count[i] == -1)	{
				status = ncdiminq(cdfid, dim[i], name, & count[i]);
				count[i] -= start[i];
			}
		}
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		len = 0;
		if (ndims > 0)	{
			len = 1;
			for (i = 0; i < ndims; i++)	{
				len *= count[i];
			}
		}
		
		value = (VOIDP) mxCalloc(len, nctypelen(datatype));
		status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr);
		status = ncvarput(cdfid, varid, start, count, value);
		Free((VOIDPP) & value);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & start);
		Free((VOIDPP) & count);
		
		break;
		
	case VARGET:
		
		start = Mat2Long(prhs[3]);
		count = Mat2Long(prhs[4]);
        intcount = Mat2Int(prhs[4]);
		
		autoscale = (nrhs > 5 && Scalar2Int(prhs[5]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		for (i = 0; i < ndims; i++)	{
			if (count[i] == -1)	{
				status = ncdiminq(cdfid, dim[i], name, & count[i]);
				count[i] -= start[i];
			}
		}
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		m = 0;
		n = 0;
		if (ndims > 0)	{
			m = count[0];
			n = count[0];
			for (i = 1; i < ndims; i++)	{
				n *= count[i];
				if (count[i] > 1)	{
					m = count[i];
				}
			}
			n /= m;
		}
		len = m * n;
		if (ndims < 2)	{
			m = 1;
			n = len;
		}
		
		for (i = 0; i < ndims; i++)	{
			intcount[i] = count[ndims-i-1];   /*	Reverse order.	*/
		}
		
		if (MEXCDF_4 || ndims < 2)	{
			mat = mxCreateFull(m, n, mxREAL);	/*	mxCreateDoubleMatrix	*/
		}
# if MEXCDF_5
		else	{
			mat = mxCreateNumericArray(ndims, intcount, mxDOUBLE_CLASS, mxREAL);
		}
# endif
		
		pr = mxGetPr(mat);
		
		value = (VOIDP) mxCalloc(len, nctypelen(datatype));
		status = ncvarget(cdfid, varid, start, count, value);
		status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr);
		Free((VOIDPP) & value);
		
		if (datatype == NC_CHAR)	{
			plhs[0] = SetStr(mat);
		}
		else	{
			plhs[0] = mat;
		}
		if (plhs[0] == NULL)	{
			plhs[0] = mat;
		}
		
		plhs[1] = Int2Scalar(status);
		
		Free((VOIDPP) & intcount);
		Free((VOIDPP) & count);
		Free((VOIDPP) & start);
		
		break;
		
	case VARPUTG:
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		if (nrhs > 7)	{
			if (datatype == NC_CHAR)	{
				mat = SetStr(prhs[7]);
			}
			else	{
				mat = prhs[7];
			}
			if (mat == NULL)	{
				mat = prhs[7];
			}
		}
		else	{
			if (datatype == NC_CHAR)	{
				mat = SetStr(prhs[6]);
			}
			else	{
				mat = prhs[6];
			}
			if (mat == NULL)	{
				mat = prhs[6];
			}
		}
		pr = mxGetPr(mat);
		
		start = Mat2Long(prhs[3]);
		count = Mat2Long(prhs[4]);
		stride = Mat2Long(prhs[5]);
		imap = NULL;
		
		for (i = 0; i < ndims; i++)	{
			if (count[i] == -1)	{
				status = ncdiminq(cdfid, dim[i], name, & count[i]);
				count[i] -= start[i];
			}
		}
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		len = 0;
		if (ndims > 0)	{
			len = 1;
			for (i = 0; i < ndims; i++)	{
				len *= count[i];
			}
		}
		
		autoscale = (nrhs > 8 && Scalar2Int(prhs[8]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		value = (VOIDP) mxCalloc(len, nctypelen(datatype));
		status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr);
		status = ncvarputg(cdfid, varid, start, count, stride, imap, value);
		Free((VOIDPP) & value);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & stride);
		Free((VOIDPP) & count);
		Free((VOIDPP) & start);
		
		break;
		
	case VARGETG:
		
		start = Mat2Long(prhs[3]);
		count = Mat2Long(prhs[4]);
        intcount = Mat2Int(prhs[4]);
		stride = Mat2Long(prhs[5]);
		imap = NULL;
		
		autoscale = (nrhs > 7 && Scalar2Int(prhs[7]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int));
		
		status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts);
		
		datatype = RepairBadDataType(datatype);
		
		for (i = 0; i < ndims; i++)	{
			if (count[i] == -1)	{
				status = ncdiminq(cdfid, dim[i], name, & count[i]);
				count[i] -= start[i];
			}
		}
		
		Free((VOIDPP) & name);
		Free((VOIDPP) & dim);
		
		m = 0;
		n = 0;
		if (ndims > 0)	{
			m = count[0];
			n = count[0];
			for (i = 1; i < ndims; i++)	{
				n *= count[i];
				if (count[i] > 1)	{
					m = count[i];
				}
			}
			n /= m;
		}
		len = m * n;
		if (ndims < 2)	{
			m = 1;
			n = len;
		}
		
		for (i = 0; i < ndims; i++)	{
			intcount[i] = count[ndims-i-1];   /*	Reverse order.	*/
		}
		
		if (MEXCDF_4 || ndims < 2)	{
			mat = mxCreateFull(m, n, mxREAL);	/*	mxCreateDoubleMatrix	*/
		}
# if MEXCDF_5
		else	{
			mat = mxCreateNumericArray(ndims, intcount, mxDOUBLE_CLASS, mxREAL);
		}
# endif
		
		pr = mxGetPr(mat);
		
		value = (VOIDP) mxCalloc(len, nctypelen(datatype));
		status = ncvargetg(cdfid, varid, start, count, stride, imap, value);
		status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr);
		Free((VOIDPP) & value);
		
		if (datatype == NC_CHAR)	{
			plhs[0] = SetStr(mat);
		}
		else	{
			plhs[0] = mat;
		}
		if (plhs[0] == NULL)	{
/*			prhs[0] = mat;		*/
			plhs[0] = mat;		/*	ZYDECO 24Jan2000	*/
		}
		
		plhs[1] = Int2Scalar(status);
		
		Free((VOIDPP) & stride);
		Free((VOIDPP) & intcount);
		Free((VOIDPP) & count);
		Free((VOIDPP) & start);
		
		break;

	case VARRENAME:
		
		name = Mat2Str(prhs[3]);
		
		status = ncvarrename(cdfid, varid, name);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & name);
		
		break;
		
	case VARCOPY:
	
		incdf = cdfid;
		
		invar = varid;
		
		outcdf = Scalar2Int(prhs[3]);
	
		outvar = -1;
/*		outvar = ncvarcopy(incdf, invar, outcdf);	*/
		
		plhs[0] = Int2Scalar(outvar);
		plhs[1] = Int2Scalar((outvar >= 0) ? 0 : outvar);
		
		break;
		
	case ATTPUT:
		
		datatype = (nc_type) Parameter(prhs[4]);
		
		datatype = RepairBadDataType(datatype);
		
		if (datatype == NC_CHAR)	{
			mat = SetNum(prhs[6]);
		}
		else	{
			mat = prhs[6];
		}
		if (mat == NULL)	{
			mat = prhs[6];
		}
		
		len = Scalar2Int(prhs[5]);
		if (len == -1)	{
			len = Count(mat);
		}
		
		pr = mxGetPr(mat);
		value = (VOIDP) mxCalloc(len, nctypelen(datatype));
		status = Convert(opcode, datatype, len, value, (DOUBLE) 1.0, (DOUBLE) 0.0, pr);
		
		status = ncattput(cdfid, varid, attname, datatype, len, value);
		
		if (value != NULL)	{
			Free((VOIDPP) & value);
		}
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		
		break;
		
	case ATTINQ:
		
		status = ncattinq(cdfid, varid, attname, & datatype, & len);
		
		datatype = RepairBadDataType(datatype);
		
		plhs[0] = Int2Scalar((int) datatype);
		plhs[1] = Int2Scalar(len);
		plhs[2] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		
		break;
		
	case ATTGET:
		
		status = ncattinq(cdfid, varid, attname, & datatype, & len);
		
		datatype = RepairBadDataType(datatype);
		
		value = (VOIDP) mxCalloc(len, nctypelen(datatype));
		status = ncattget(cdfid, varid, attname, value);
		
		mat = mxCreateDoubleMatrix(1, len, mxREAL);
		
		pr = mxGetPr(mat);
		
		status = Convert(opcode, datatype, len, value, (DOUBLE) 1.0, (DOUBLE) 0.0, pr);
		
		if (value != NULL)	{
			Free((VOIDPP) & value);
		}
		
		if (datatype == NC_CHAR)	{
			plhs[0] = SetStr(mat);
		}
		else	{
			plhs[0] = mat;
		}
		if (plhs[0] == NULL)	{
/*			prhs[4] = mat;		*/
			plhs[0] = mat;		/*	ZYDECO 24Jan2000	*/
		}
		
		plhs[1] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		
		break;
		
	case ATTCOPY:
	
		incdf = cdfid;
		
		invar = varid;
		
		outcdf = Scalar2Int(prhs[4]);
	
		if (mxIsNumeric(prhs[5]))	{
			outvar = Scalar2Int(prhs[2]);
		}
		else	{
			name = Mat2Str(prhs[5]);
			outvar = ncvarid(cdfid, name);
			Free((VOIDPP) & name);
		}
	
		status = ncattcopy(incdf, invar, attname, outcdf, outvar);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		
		break;
		
	case ATTNAME:
		
		attnum = Scalar2Int(prhs[3]);
		attname = (char *) mxCalloc(MAX_NC_NAME, sizeof(char));
		
		status = ncattname(cdfid, varid, attnum, attname);
		
		plhs[0] = Str2Mat(attname);
		plhs[1] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		
		break;
		
	case ATTRENAME:
	
		newname = Mat2Str(prhs[4]);
		
		status = ncattrename(cdfid, varid, attname, newname);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		Free((VOIDPP) & newname);
		
		break;
		
	case ATTDEL:
		
		status = ncattdel(cdfid, varid, attname);
		
		plhs[0] = Int2Scalar(status);
		
		Free((VOIDPP) & attname);
		
		break;
		
	case RECPUT:
		
		recnum = Scalar2Long(prhs[2]);
		pr = mxGetPr(prhs[3]);
		
		autoscale = (nrhs > 4 && Scalar2Int(prhs[4]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		recvarids = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int));
		recsizes = (long *) mxCalloc(MAX_VAR_DIMS, sizeof(long));
		datap = (VOIDPP) mxCalloc(MAX_VAR_DIMS, sizeof(VOIDP));
		
		status = ncrecinq(cdfid, & nrecvars, recvarids, recsizes);
		
		if (status == -1)	{
			plhs[0] = Int2Scalar(status);
			break;
		}
		
		length = 0;
		n = 0;
		for (i = 0; i < nrecvars; i++)	{
			ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL);
		
			datatype = RepairBadDataType(datatype);
			
			length += recsizes[i];
			n += (recsizes[i] / nctypelen(datatype));
		}
		
		if (Count(prhs[3]) < n)	{
			status = -1;
			plhs[0] = Int2Scalar(status);
			break;
		}
		
		if ((value = (VOIDP) mxCalloc((int) length, sizeof(char))) == NULL)	{
			status = -1;
			plhs[0] = Int2Scalar(status);
			break;
		}
		
		length = 0;
		p = value;
		for (i = 0; i < nrecvars; i++)	{
			datap[i] = p;
			p += recsizes[i];
		}
		
		p = (char *) value;
		pr = mxGetPr(prhs[3]);
		
		for (i = 0; i < nrecvars; i++)	{
			ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL);
		
			datatype = RepairBadDataType(datatype);
		
			length = recsizes[i] / nctypelen(datatype);
			if (autoscale)	{
				addoffset = Add_Offset(cdfid, recvarids[i]);
				scalefactor = Scale_Factor(cdfid, recvarids[i]);
				if (scalefactor == 0.0)	{
					scalefactor = 1.0;
				}
			}
			Convert(opcode, datatype, length, (VOIDP) p,  scalefactor, addoffset, pr);
			pr += length;
			p += recsizes[i];
		}
		
		status = ncrecput(cdfid, recnum, datap);
		
		plhs[0] = Int2Scalar(status);
		
		Free ((VOIDPP) & value);
		Free ((VOIDPP) & datap);
		Free ((VOIDPP) & recsizes);
		Free ((VOIDPP) & recvarids);
		
		break;
		
	case RECGET:
		
		recnum = Scalar2Long(prhs[2]);
		
		autoscale = (nrhs > 3 && Scalar2Int(prhs[3]) != 0);
		
		if (!autoscale)	{
			scalefactor = 1.0;
			addoffset = 0.0;
		}
		
		recvarids = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int));
		recsizes = (long *) mxCalloc(MAX_VAR_DIMS, sizeof(long));
		datap = (VOIDPP) mxCalloc(MAX_VAR_DIMS, sizeof(VOIDP));
		
		status = ncrecinq(cdfid, & nrecvars, recvarids, recsizes);
		
		if (status == -1)	{
			Free ((VOIDPP) & recsizes);
			Free ((VOIDPP) & recvarids);
			plhs[1] = Int2Scalar(status);
			break;
		}
		
		if (nrecvars == 0)	{
			Free ((VOIDPP) & recsizes);
			Free ((VOIDPP) & recvarids);
			plhs[0] = mxCreateFull(0, 0, REAL);
			break;
		}
		
		length = 0;
		n = 0;
		for (i = 0; i < nrecvars; i++)	{
			ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL);
		
			datatype = RepairBadDataType(datatype);
			
			length += recsizes[i];
			n += (recsizes[i] / nctypelen(datatype));
		}
		
		if ((value = (VOIDP) mxCalloc((int) length, sizeof(char))) == NULL)	{
			status = -1;
			plhs[1] = Int2Scalar(status);
			break;
		}
		
		if (value == NULL)	{
			status = -1;
			plhs[1] = Int2Scalar(status);
			break;
		}
		
		length = 0;
		p = value;
		for (i = 0; i < nrecvars; i++)	{
			datap[i] = p;
			p += recsizes[i];
		}
		
		if ((status = ncrecget(cdfid, recnum, datap)) == -1)	{
			plhs[1] = Int2Scalar(status);
			break;
		}
		
		m = 1;
		
		plhs[0] = mxCreateFull(m, n, REAL);
		
		if (plhs[0] == NULL)	{
			status = -1;
			plhs[1] = Int2Scalar(status);
			break;
		}
		
		pr = mxGetPr(plhs[0]);
		p = (char *) value;
		
		for (i = 0; i < nrecvars; i++)	{
			status = ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL);
		
			datatype = RepairBadDataType(datatype);
			
			if (status == -1)	{
				plhs[1] = Int2Scalar(status);
				break;
			}
			length = recsizes[i] / nctypelen(datatype);
			if (autoscale)	{
				addoffset = Add_Offset(cdfid, recvarids[i]);
				scalefactor = Scale_Factor(cdfid, recvarids[i]);
				if (scalefactor == 0.0)	{
					scalefactor = 1.0;
				}
			}
			Convert(opcode, datatype, length, (VOIDP) p,  scalefactor, addoffset, pr);
			pr += length;
			p += recsizes[i];
		}
		
		plhs[1] = Int2Scalar(status);
		
		Free ((VOIDPP) & value);
		Free ((VOIDPP) & datap);
		Free ((VOIDPP) & recsizes);
		Free ((VOIDPP) & recvarids);
		
		break;

	case RECINQ:
		
		recvarids = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int));
		recsizes = (long *) mxCalloc(MAX_VAR_DIMS, sizeof(long));
		
		status = ncrecinq(cdfid, & nrecvars, recvarids, recsizes);
		
		if (status != -1)	{
			for (i = 0; i < nrecvars; i++)	{
				ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL);
		
				datatype = RepairBadDataType(datatype);
			
				recsizes[i] /= nctypelen(datatype);
			}
			m = 1;
			n = nrecvars;
			plhs[0] = Int2Mat(recvarids, m, n);
			plhs[1] = Long2Mat(recsizes, m, n);
		}
		
		plhs[2] = Int2Scalar(status);
		
		Free ((VOIDPP) & recsizes);
		Free ((VOIDPP) & recvarids);
		
		break;
		
	case TYPELEN:
	
		datatype = (nc_type) Parameter(prhs[1]);
		
		len = nctypelen(datatype);
		
		plhs[0] = Int2Scalar(len);
		plhs[1] = Int2Scalar((len >= 0) ? 0 : 1);
		
		break;
		
	case SETFILL:
	
		fillmode = Scalar2Int(prhs[1]);
		
		status = ncsetfill(cdfid, fillmode);
		
		plhs[0] = Int2Scalar(status);
		plhs[1] = Int2Scalar(0);
		
		break;

	case SETOPTS:
		
		plhs[0] = Int2Scalar(ncopts);
		plhs[1] = Int2Scalar(0);
		ncopts = Scalar2Int(prhs[1]);
		
		break;
		
	case ERR:
	
		plhs[0] = Int2Scalar(ncerr);
		ncerr = 0;
		plhs[1] = Int2Scalar(0);
		
		break;
		
	case PARAMETER:
	
		if (nrhs > 1)	{
			plhs[0] = Int2Scalar(Parameter(prhs[1]));
			plhs[1] = Int2Scalar(0);
		}
		else	{
			i = 0;
			while (strcmp(parms[i].name, "NONE") != 0)	{
				mexPrintf("%12d %s\n", parms[i].code, parms[i].name);
				i++;
			}
			plhs[0] = Int2Scalar(0);
			plhs[1] = Int2Scalar(-1);
		}
		
		break;
		
	default:
	
		break;
	}
	
	return;
}
Ejemplo n.º 18
0
int ex_get_elem_blk_ids (int  exoid,
                         int *ids)
{
   int dimid, varid, iresult;
   long num_elem_blocks, start[1], count[1]; 
   nclong *longs;
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

/* inquire id's of previously defined dimensions and variables  */

   if ((dimid = ncdimid (exoid, DIM_NUM_EL_BLK)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
          "Error: failed to locate dimension DIM_NUM_EL_BLK in file id %d",
             exoid);
     ex_err("ex_get_elem_blk_ids",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (ncdiminq (exoid, dimid, (char *) 0, &num_elem_blocks) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to return number of element blocks in file id %d",
             exoid);
     ex_err("ex_get_get_elem_blk_ids",errmsg,exerrval);
     return (EX_FATAL);
   }


   if ((varid = ncvarid (exoid, VAR_ID_EL_BLK)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
       "Error: failed to locate element block ids variable in file id %d",
             exoid);
     ex_err("ex_get_get_elem_blk_ids",errmsg,exerrval);
     return (EX_FATAL);
   }


/* read in the element block ids  */

/* application code has allocated an array of ints but netcdf is expecting
   a pointer to nclongs;  if ints are different sizes than nclongs,
   we must allocate an array of nclongs then convert them to ints with ltoi */

   start[0] = 0;
   count[0] = num_elem_blocks;

   if (sizeof(int) == sizeof(nclong)) {
      iresult = ncvarget (exoid, varid, start, count, ids);
   } else {
     if (!(longs = malloc(num_elem_blocks * sizeof(nclong)))) {
       exerrval = EX_MEMFAIL;
       sprintf(errmsg,
               "Error: failed to allocate memory for element block ids for file id %d",
               exoid);
       ex_err("ex_get_elem_blk_ids",errmsg,exerrval);
       return (EX_FATAL);
     }
     iresult = ncvarget (exoid, varid, start, count, longs);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
       "Error: failed to return element block ids in file id %d",
             exoid);
     ex_err("ex_get_get_elem_blk_ids",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (sizeof(int) != sizeof(nclong)) {
      ltoi (longs, ids, num_elem_blocks);
      free (longs);
   }

   return(EX_NOERR);

}
Ejemplo n.º 19
0
/* ----------------------------- MNI Header -----------------------------------
@NAME       : find_mincfile_range
@INPUT      : mincid - id of minc file
@OUTPUT     : minimum - minimum for file
              maximum - maximum for file
@RETURNS    : (nothing)
@DESCRIPTION: Routine to find the min and max in a minc file
@METHOD     : 
@GLOBALS    : 
@CALLS      : 
@CREATED    : April 25, 1995 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
static void find_mincfile_range(int mincid, double *minimum, double *maximum)
{
   int varid;
   char *varname;
   double sign, value;
   double *extreme;
   long index[MAX_VAR_DIMS], count[MAX_VAR_DIMS];
   int ndims, dim[MAX_VAR_DIMS];
   int idim, imm;
   int old_ncopts;

   *minimum = 0.0;
   *maximum = 1.0;
   for (imm=0; imm < 2; imm++) {

      /* Set up for max or min */
      if (imm == 0) {
         varname = MIimagemin;
         sign = -1.0;
         extreme = minimum;
      }
      else {
         varname = MIimagemax;
         sign = 1.0;
         extreme = maximum;
      }

      /* Get the variable id */
      old_ncopts = ncopts; ncopts = 0;
      varid = ncvarid(mincid, varname);
      ncopts = old_ncopts;
      if (varid == MI_ERROR) continue;

      /* Get the dimension info */
      (void) ncvarinq(mincid, varid, NULL, NULL, &ndims, dim, NULL);
      for (idim=0; idim < ndims; idim++) {
         (void) ncdiminq(mincid, dim[idim], NULL, &count[idim]);
      }
      if (ndims <= 0) {
         ndims = 1;
         count[0] = 1;
      }

      /* Loop through values, getting extrema */
      (void) miset_coords(ndims, (long) 0, index);
      *extreme = sign * (-DBL_MAX);
      while (index[0] < count[0]) {
         (void) mivarget1(mincid, varid, index, NC_DOUBLE, NULL, &value);
         if ((value * sign) > (*extreme * sign)) {
            *extreme = value;
         }
         idim = ndims-1;
         index[idim]++;
         while ((index[idim] > count[idim]) && (idim > 0)) {
            idim--;
            index[idim]++;
         }
      }
   }

}
Ejemplo n.º 20
0
int ex_get_qa (int exoid,
               char *qa_record[][4])
{
    int i, j, k, dimid, varid;
    long num_qa_records, start[3];

    char *ptr;
    char errmsg[MAX_ERR_LENGTH];

    exerrval = 0; /* clear error code */

    /* inquire previously defined dimensions and variables  */

    if ((dimid = ncdimid (exoid, DIM_NUM_QA)) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Warning: no qa records stored in file id %d",
                exoid);
        ex_err("ex_get_qa",errmsg,exerrval);
        return (EX_WARN);
    }

    if (ncdiminq (exoid, dimid, (char *) 0, &num_qa_records) == -1)
    {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get number of qa records in file id %d",
                exoid);
        ex_err("ex_get_qa",errmsg,exerrval);
        return (EX_FATAL);
    }


    /* do this only if there are any QA records */

    if (num_qa_records > 0)
    {
        if ((varid = ncvarid (exoid, VAR_QA_TITLE)) == -1)
        {
            exerrval = ncerr;
            sprintf(errmsg,
                    "Error: failed to locate qa record data in file id %d", exoid);
            ex_err("ex_get_qa",errmsg,exerrval);
            return (EX_FATAL);
        }


        /* read the QA records */

        for (i=0; i<num_qa_records; i++)
        {
            for (j=0; j<4; j++)
            {
                start[0] = i;
                start[1] = j;
                start[2] = 0;

                k = 0;
                ptr = qa_record[i][j];

                if (ncvarget1 (exoid, varid, start, ptr) == -1)
                {
                    exerrval = ncerr;
                    sprintf(errmsg,
                            "Error: failed to get qa record data in file id %d", exoid);
                    ex_err("ex_get_qa",errmsg,exerrval);
                    return (EX_FATAL);
                }


                while ((*(ptr++) != '\0') && (k < MAX_STR_LENGTH))
                {
                    start[2] = ++k;
                    if (ncvarget1 (exoid, varid, start, ptr) == -1)
                    {
                        exerrval = ncerr;
                        sprintf(errmsg,
                                "Error: failed to get qa record data in file id %d", exoid);
                        ex_err("ex_get_qa",errmsg,exerrval);
                        return (EX_FATAL);
                    }

                }

                /* remove trailing blanks */

                if(start[2] != 0)
                {
                    --ptr;
                    while ( --ptr >= qa_record[i][j] && *ptr == ' ' );
                    *(++ptr) = '\0';
                }
            }
        }

    }

    return (EX_NOERR);

}
Ejemplo n.º 21
0
Archivo: cn08c.c Proyecto: gavin971/ncl
int main()
{
/*
 * Declare variables for the HLU routine calls.
 */
    int     appid, workid, field1, con1;
    int     srlist, i, j, k;
    ng_size_t   icount[2];
    float cmap[NCOLORS][3];
/*
 * Declare variables for getting information from netCDF file.
 */
    int   ncid, lon_id, lat_id, level_id, temp_id;
    float temp[10][33], special_value;
    float lon[36], lat[33], level[10];
    float min_lat, min_level, max_lat, max_level;
    long  start[4], count[4], lonlen, latlen, levellen;
    char  filename[256], string[50];
    const char *dir = _NGGetNCARGEnv("data");
/*
 * Default is to create an NCGM file.
 */
    char const *wks_type = "ncgm";

/*
 * Initialize the HLU library and set up resource template.
 */
    NhlInitialize();
    srlist = NhlRLCreate(NhlSETRL);
/*
 * Create Application object.
 */
    NhlRLClear(srlist);

    NhlRLSetString(srlist,NhlNappDefaultParent,"True");
    NhlRLSetString(srlist,NhlNappUsrDir,"./");
    NhlCreate(&appid,"cn08",NhlappClass,NhlDEFAULT_APP,srlist);

	cmap[0][0] = 0.0; cmap[0][1] = 0.0; cmap[0][2] = 0.0;
	cmap[1][0] = 1.0; cmap[1][1] = 1.0; cmap[1][2] = 1.0;
	cmap[2][0] = 1.0; cmap[2][1] = 1.0; cmap[2][2] = 1.0;
	cmap[3][0] = 1.0; cmap[3][1] = 0.0; cmap[3][2] = 0.0;
	cmap[4][0] = 0.0; cmap[4][1] = 1.0; cmap[4][2] = 0.0;
	cmap[5][0] = 0.0; cmap[5][1] = 0.0; cmap[5][2] = 1.0;
	cmap[6][0] = 1.0; cmap[6][1] = 1.0; cmap[6][2] = 0.0;
	cmap[7][0] = 0.0; cmap[7][1] = 1.0; cmap[7][2] = 1.0;
	cmap[8][0] = 1.0; cmap[8][1] = 0.0; cmap[8][2] = 1.0;
	cmap[9][0] = 0.5; cmap[9][1] = 0.0; cmap[9][2] = 0.0;
	cmap[10][0] = 0.5; cmap[10][1] = 1.0; cmap[10][2] = 1.0;
	cmap[11][0] = 0.0; cmap[11][1] = 0.0; cmap[11][2] = 0.5;
	cmap[12][0] = 1.0; cmap[12][1] = 1.0; cmap[12][2] = 0.5;
	cmap[13][0] = 0.5; cmap[13][1] = 0.0; cmap[13][2] = 1.0;
	cmap[14][0] = 1.0; cmap[14][1] = 0.5; cmap[14][2] = 0.0;
	cmap[15][0] = 0.0; cmap[15][1] = 0.5; cmap[15][2] = 1.0;
	cmap[16][0] = 0.5; cmap[16][1] = 1.0; cmap[16][2] = 0.0;
	cmap[17][0] = 0.5; cmap[17][1] = 0.0; cmap[17][2] = 0.5;
	cmap[18][0] = 0.5; cmap[18][1] = 1.0; cmap[18][2] = 0.5;
	cmap[19][0] = 1.0; cmap[19][1] = 0.5; cmap[19][2] = 1.0;
	cmap[20][0] = 0.0; cmap[20][1] = 0.5; cmap[20][2] = 0.0;
	cmap[21][0] = 0.5; cmap[21][1] = 0.5; cmap[21][2] = 1.0;
	cmap[22][0] = 1.0; cmap[22][1] = 0.0; cmap[22][2] = 0.5;

    icount[0] = NCOLORS;
    icount[1] = 3;

    if (!strcmp(wks_type,"ncgm") || !strcmp(wks_type,"NCGM")) {
/*
 * Create a meta file object.
 */
        NhlRLClear(srlist);
		NhlRLSetMDFloatArray(srlist,NhlNwkColorMap,&cmap[0][0],2,icount);
        NhlRLSetString(srlist,NhlNwkMetaName,"./cn08c.ncgm");
        NhlCreate(&workid,"cn08Work",NhlncgmWorkstationClass,
                  NhlDEFAULT_APP,srlist);
    }
    else if (!strcmp(wks_type,"x11") || !strcmp(wks_type,"X11")) {
/*
 * Create an X11 workstation.
 */
        NhlRLClear(srlist);
		NhlRLSetMDFloatArray(srlist,NhlNwkColorMap,&cmap[0][0],2,icount);
        NhlRLSetString(srlist,NhlNwkPause,"True");
        NhlCreate(&workid,"cn08Work",NhlcairoWindowWorkstationClass,
              NhlDEFAULT_APP,srlist);
    }
    else if (!strcmp(wks_type,"oldps") || !strcmp(wks_type,"OLDPS")) {
/*
 * Create an older-style PostScript workstation.
 */
        NhlRLClear(srlist);
		NhlRLSetMDFloatArray(srlist,NhlNwkColorMap,&cmap[0][0],2,icount);
        NhlRLSetString(srlist,NhlNwkPSFileName,"./cn08c.ps");
        NhlCreate(&workid,"cn08Work",NhlpsWorkstationClass,
                  NhlDEFAULT_APP,srlist);
    }
    else if (!strcmp(wks_type,"oldpdf") || !strcmp(wks_type,"OLDPDF")) {
/*
 * Create an older-style PDF workstation.
 */
        NhlRLClear(srlist);
		NhlRLSetMDFloatArray(srlist,NhlNwkColorMap,&cmap[0][0],2,icount);
        NhlRLSetString(srlist,NhlNwkPDFFileName,"./cn08c.pdf");
        NhlCreate(&workid,"cn08Work",NhlpdfWorkstationClass,
                  NhlDEFAULT_APP,srlist);
    }
    else if (!strcmp(wks_type,"pdf") || !strcmp(wks_type,"PDF") ||
             !strcmp(wks_type,"ps") || !strcmp(wks_type,"PS")) {
/*
 * Create a cairo PS/PDF workstation.
 */
        NhlRLClear(srlist);
		NhlRLSetMDFloatArray(srlist,NhlNwkColorMap,&cmap[0][0],2,icount);
        NhlRLSetString(srlist,NhlNwkFileName,"./cn08c");
        NhlRLSetString(srlist,NhlNwkFormat,(char*)wks_type);
        NhlCreate(&workid,"cn08Work",NhlcairoDocumentWorkstationClass,
                  NhlDEFAULT_APP,srlist);
    }
    else if (!strcmp(wks_type,"png") || !strcmp(wks_type,"PNG")) {
/*
 * Create a cairo PNG workstation.
 */
        NhlRLClear(srlist);
		NhlRLSetMDFloatArray(srlist,NhlNwkColorMap,&cmap[0][0],2,icount);
        NhlRLSetString(srlist,NhlNwkFileName,"./cn08c");
        NhlRLSetString(srlist,NhlNwkFormat,(char*)wks_type);
        NhlCreate(&workid,"cn08Work",NhlcairoImageWorkstationClass,
                  NhlDEFAULT_APP,srlist);
    }
/*
 * Open data file containing grid of global temperatures.
 */
    sprintf( filename, "%s/cdf/contour.cdf", dir );
    ncid = ncopen(filename,NC_NOWRITE);
/*
 * Get the lat/lon/level dimensions.
 */
    lat_id = ncdimid(ncid,"lat");
    lon_id = ncdimid(ncid,"lon");
    level_id  = ncdimid(ncid,"level");
    ncdiminq(ncid,lat_id,(char *)0,&latlen);
    ncdiminq(ncid,lon_id,(char *)0,&lonlen);
    ncdiminq(ncid,level_id,(char *)0,&levellen);
/*
 * Read in temperature values and convert from degrees F to degrees K.
 */
    temp_id = ncvarid(ncid,"T");
    start[0] = start[1] = start[2] = start[3] = 0;
    count[0] = 1; count[1] = levellen; count[2] = latlen; count[3] = 1;
    ncvarget(ncid,temp_id,(long const *)start,(long const *)count,temp);
    ncattget(ncid,temp_id,"_FillValue",&special_value);
    for( j = 0; j < levellen; j++ ) {
        for( k = 0; k < latlen; k++ ) {
            temp[j][k] = (temp[j][k] - 273.15) * 9./5. + 32.;
        }
    }
/*
 * Read in lat/lon/level values.
 */
    lat_id = ncvarid(ncid,"lat");
    count[0] = latlen;
    ncvarget(ncid,lat_id,(long const *)start,(long const *)count,lat);

    lon_id = ncvarid(ncid,"lon");
    count[0] = lonlen;
    ncvarget(ncid,lon_id,(long const *)start,(long const *)count,lon);

    level_id = ncvarid(ncid,"level");
    count[0] = levellen;
    ncvarget(ncid,level_id,(long const *)start,(long const *)count,level);
/*
 * Set up initial scalar field with longitude of temperature data.
 */
    icount[0] = levellen; icount[1] = latlen;
    NhlRLClear(srlist);
    NhlRLSetMDFloatArray(srlist,NhlNsfDataArray,&temp[0][0],2,icount);
    NhlRLSetFloat(srlist,NhlNsfMissingValueV,special_value);
    NhlRLSetFloat(srlist,NhlNsfXCStartV,lat[0]);
    NhlRLSetFloat(srlist,NhlNsfXCEndV,lat[latlen-1]);
    NhlRLSetFloatArray(srlist,NhlNsfXArray,lat,latlen);
    NhlRLSetFloatArray(srlist,NhlNsfYArray,level,levellen);
    NhlCreate(&field1,"field1",NhlscalarFieldClass,appid,srlist);
/*
 * Determine extents of grid
 */
    if(lat[0] < lat[latlen-1]) {
        min_lat = lat[0];
        max_lat = lat[latlen-1];
    }
    else {
        max_lat = lat[0];
        min_lat = lat[latlen-1];
    }
    if(level[0] < level[levellen-1]) {
        min_level = level[0];
        max_level = level[levellen-1];
    }
    else {
        max_level = level[0];
        min_level = level[levellen-1];
    }
/*
 * Create contour using manual spacing.
 */
    NhlRLClear(srlist);
    NhlRLSetFloat(srlist,NhlNvpXF,.2);
    NhlRLSetFloat(srlist,NhlNvpYF,.8);
    NhlRLSetFloat(srlist,NhlNvpWidthF, .6);
    NhlRLSetFloat(srlist,NhlNvpHeightF, .6);
    NhlRLSetString(srlist,NhlNcnFillOn, "True");
    NhlRLSetInteger(srlist,NhlNcnScalarFieldData, field1);
    NhlRLSetString(srlist,NhlNcnLevelSelectionMode, "ManualLevels");
    NhlRLSetInteger(srlist,NhlNcnMaxLevelCount, 25);
    NhlRLSetFloat(srlist,NhlNcnMinLevelValF, -80.0);
    NhlRLSetFloat(srlist,NhlNcnMaxLevelValF, 110.0);
    NhlRLSetFloat(srlist,NhlNcnLevelSpacingF, 10.0);
    NhlRLSetFloat(srlist,NhlNtrXMinF, min_lat);
    NhlRLSetFloat(srlist,NhlNtrXMaxF, max_lat);
    NhlRLSetFloat(srlist,NhlNtrYMinF, min_level);
    NhlRLSetFloat(srlist,NhlNtrYMaxF, max_level);
    NhlRLSetString(srlist,NhlNtrYReverse, "True");
    sprintf(string,"Longitude %g Degrees", lon[0] );
    NhlRLSetString(srlist,NhlNtiMainString,string);
    NhlCreate(&con1,"con1",NhlcontourPlotClass,workid,srlist);
/* 
 * Draw first step
 */
    NhlDraw(con1);
    NhlFrame(workid);
/*
 * Loop on remaining longitude values and reset the title every
 * iteration.
 */
    for( i = 1; i <= lonlen-1; i++ ) {
/*
 * Read in temperature values and convert from degrees F to degrees K.
 */
        start[0] = start[1] = start[2] = 0;
        start[3] = i;
        count[0] = 1; count[1] = levellen;
        count[2] = latlen; count[3] = 1;
        ncvarget(ncid,temp_id,(long const *)start,(long const *)count,
                 temp);
        for( j = 0; j < levellen; j++ ) {
            for( k = 0; k < latlen; k++ ) {
                temp[j][k] = (temp[j][k] - 273.15) * 9./5. + 32.;
            }
        }
        NhlRLClear(srlist);
        icount[0] = levellen; icount[1] = latlen;
        NhlRLSetMDFloatArray(srlist,NhlNsfDataArray,&temp[0][0],2,icount);
/*
 * Create new scalar field.
 */
        NhlSetValues(field1,srlist);
        NhlRLClear(srlist);
        sprintf(string,"Longitude %g Degrees", lon[i] );
        NhlRLSetString(srlist,NhlNtiMainString,string);
        NhlSetValues(con1,srlist);
        NhlDraw(con1);
        NhlFrame(workid);
    }
/*
 * Close the netCDF file.
 */
    ncclose(ncid);
/*
 * NhlDestroy destroys the given id and all of its children.
 */
    NhlRLDestroy(srlist);
    NhlDestroy(appid);
/*
 * Restores state.
 */
    NhlClose();
    exit(0);
}
Ejemplo n.º 22
0
/*
 * reads the attribute names for an element block
 */
int ex_get_attr_names( int   exoid,
                       int   obj_type,
                       int   obj_id,
                       char **names)
{
  int varid, numattrdim, obj_id_ndx;
  long num_attr, start[2];
  char *ptr;
  char errmsg[MAX_ERR_LENGTH];
  int i, j;
  const char* tname;
  const char* vobjids;
  const char* dnumobjatt = 0;
  const char* vattrbname = 0;

  switch (obj_type) {
  case EX_EDGE_BLOCK:
    tname = "edge block";
    vobjids = VAR_ID_ED_BLK;
    break;
  case EX_FACE_BLOCK:
    tname = "face block";
    vobjids = VAR_ID_FA_BLK;
    break;
  case EX_ELEM_BLOCK:
    tname = "element block";
    vobjids = VAR_ID_EL_BLK;
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf( errmsg, "Error: Invalid object type (%d) specified for file id %d",
      obj_type, exoid );
    ex_err( "ex_get_attr_names", errmsg, exerrval );
    return (EX_FATAL);
  }
 
  exerrval = 0; /* clear error code */

  /* Determine index of obj_id in vobjids array */
  obj_id_ndx = ex_id_lkup(exoid,vobjids,obj_id);
  if (exerrval != 0) 
  {
    if (exerrval == EX_NULLENTITY)
    {
      sprintf(errmsg,
              "Warning: no attributes found for NULL block %d in file id %d",
              obj_id,exoid);
      ex_err("ex_get_attr_names",errmsg,EX_MSG);
      return (EX_WARN);              /* no attributes for this object */
    }
    else
    {
      sprintf(errmsg,
      "Warning: failed to locate %s id %d in %s array in file id %d",
              tname, obj_id,vobjids, exoid);
      ex_err("ex_get_attr_names",errmsg,exerrval);
      return (EX_WARN);
    }
  }


  switch (obj_type) {
  case EX_EDGE_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx);
    vattrbname = VAR_NAME_EATTRIB(obj_id_ndx);
    break;
  case EX_FACE_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx);
    vattrbname = VAR_NAME_FATTRIB(obj_id_ndx);
    break;
  case EX_ELEM_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx);
    vattrbname = VAR_NAME_ATTRIB(obj_id_ndx);
    break;
  }
/* inquire id's of previously defined dimensions  */

  if ((numattrdim = ncdimid(exoid, dnumobjatt)) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
            "Warning: no attributes found for %s %d in file id %d",
            tname,obj_id,exoid);
    ex_err("ex_get_attr_names",errmsg,EX_MSG);
    return (EX_WARN);              /* no attributes for this object */
  }

  if (ncdiminq (exoid, numattrdim, (char *) 0, &num_attr) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
         "Error: failed to get number of attributes for block %d in file id %d",
            obj_id,exoid);
    ex_err("ex_get_attr_names",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* It is OK if we don't find the attribute names since they were
     added at version 4.26; earlier databases won't have the names.
  */
  varid = ncvarid (exoid, vattrbname);

/* read in the attributes */

  if (varid != -1) {
    /* read the names */
    for (i=0; i < num_attr; i++) {
      start[0] = i;
      start[1] = 0;
      
      j = 0;
      ptr = names[i];
      
      if (ncvarget1 (exoid, varid, start, ptr) == -1) {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get names for %s %d in file id %d",
                tname, obj_id, exoid);
        ex_err("ex_get_attr_names",errmsg,exerrval);
        return (EX_FATAL);
      }
      
      while ((*ptr++ != '\0') && (j < MAX_STR_LENGTH)) {
        start[1] = ++j;
        if (ncvarget1 (exoid, varid, start, ptr) == -1) {
          exerrval = ncerr;
          sprintf(errmsg,
                  "Error: failed to get names for %s %d in file id %d",
                  tname, obj_id, exoid);
          ex_err("ex_get_attr_names",errmsg,exerrval);
          return (EX_FATAL);
        }
       }
       --ptr;
       if (ptr > names[i]) {
         /*    get rid of trailing blanks */
         while (*(--ptr) == ' ');
       }
       *(++ptr) = '\0';
     }
   } else {
     /* Names variable does not exist on the database; probably since this is an
      * older version of the database.  Return an empty array...
      */
     for (i=0; i<num_attr; i++) {
       names[i][0] = '\0';
     }
   }
  return(EX_NOERR);
}
Ejemplo n.º 23
0
int ex_put_side_set (int   exoid,
                     int   side_set_id,
                     const int  *side_set_elem_list,
                     const int  *side_set_side_list)
{
   int dimid, iresult;
   int elem_list_id, side_list_id, side_set_id_ndx;
   long  num_side_in_set, start[1], count[1]; 
   nclong *lptr;
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

/* first check if any side sets are specified */

   if ((dimid = ncdimid (exoid, DIM_NUM_SS)) < 0)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: no side sets defined in file id %d",
             exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }

/* Lookup index of side set id in VAR_SS_IDS array */

   side_set_id_ndx = ex_id_lkup(exoid,VAR_SS_IDS,side_set_id);
   if (exerrval != 0) 
   {
     if (exerrval == EX_NULLENTITY)
     {
       sprintf(errmsg,
              "Warning: no data allowed for NULL side set %d in file id %d",
               side_set_id,exoid);
       ex_err("ex_put_side_set",errmsg,EX_MSG);
       return (EX_WARN);
     }
     else
     {
       sprintf(errmsg,
     "Error: failed to locate side set id %d in VAR_SS_IDS array in file id %d",
               side_set_id,exoid);
       ex_err("ex_put_side_set",errmsg,exerrval);
       return (EX_FATAL);
     }
   }

/* inquire id's of previously defined dimensions  */

   if ((dimid = ncdimid (exoid, DIM_NUM_SIDE_SS(side_set_id_ndx))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to locate number of sides in side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (ncdiminq (exoid, dimid, (char *) 0, &num_side_in_set) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
         "Error: failed to get number of sides in side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }

/* inquire id's of previously defined variables  */

   if ((elem_list_id = ncvarid (exoid, VAR_ELEM_SS(side_set_id_ndx))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
           "Error: failed to locate element list for side set %d in file id %d",
               side_set_id,exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }

   if ((side_list_id = ncvarid (exoid, VAR_SIDE_SS(side_set_id_ndx))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
              "Error: failed to locate side list for side set %d in file id %d",
               side_set_id,exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }


/* write out the element list and side list arrays */

/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */

   start[0] = 0;
   count[0] = num_side_in_set;

   if (sizeof(int) == sizeof(nclong)) {
      iresult = ncvarput(exoid, elem_list_id, start, count, side_set_elem_list);
   } else {
      lptr = itol (side_set_elem_list, (int)num_side_in_set);
      iresult = ncvarput (exoid, elem_list_id, start, count, lptr);
      free(lptr);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to store element list for side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }


/* this contortion is necessary because netCDF is expecting nclongs; fortunately
   it's necessary only when ints and nclongs aren't the same size */

   if (sizeof(int) == sizeof(nclong)) {
      iresult = ncvarput(exoid, side_list_id, start, count, side_set_side_list);
   } else {
      lptr = itol (side_set_side_list, (int)num_side_in_set);
      iresult = ncvarput (exoid, side_list_id, start, count, lptr);
      free(lptr);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to store side list for side set %d in file id %d",
             side_set_id,exoid);
     ex_err("ex_put_side_set",errmsg,exerrval);
     return (EX_FATAL);
   }


   return (EX_NOERR);

}
Ejemplo n.º 24
0
int ex_get_node_set (int   exoid,
                     int   node_set_id,
                     int  *node_set_node_list)
{
   int dimid, node_list_id, node_set_id_ndx, iresult;
   long num_nodes_in_set, start[1], count[1]; 
   nclong *longs;
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

/* first check if any node sets are specified */

   if ((dimid = ncdimid (exoid, DIM_NUM_NS))  == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Warning: no node sets defined in file id %d",
             exoid);
     ex_err("ex_get_node_set",errmsg,exerrval);
     return (EX_WARN);
   }

/* Lookup index of node set id in VAR_NS_IDS array */

   node_set_id_ndx = ex_id_lkup(exoid,VAR_NS_IDS,node_set_id);
   if (exerrval != 0) 
   {
     if (exerrval == EX_NULLENTITY)
     {
       sprintf(errmsg,
              "Warning: node set %d is NULL in file id %d",
               node_set_id,exoid);
       ex_err("ex_get_node_set",errmsg,EX_MSG);
       return (EX_WARN);
     }
     else
     {

       sprintf(errmsg,
              "Error: failed to locate node set id %d in %s in file id %d",
               node_set_id,VAR_NS_IDS,exoid);
       ex_err("ex_get_node_set",errmsg,exerrval);
       return (EX_FATAL);
     }
   }

/* inquire id's of previously defined dimensions and variables */

   if ((dimid = ncdimid (exoid, DIM_NUM_NOD_NS(node_set_id_ndx))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
         "Error: failed to locate number of nodes in node set %d in file id %d",
             node_set_id,exoid);
     ex_err("ex_get_node_set",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (ncdiminq (exoid, dimid, (char *) 0, &num_nodes_in_set) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to get number of nodes in set %d in file id %d",
             node_set_id, exoid);
     ex_err("ex_get_node_set",errmsg,exerrval);
     return (EX_FATAL);
   }


   if ((node_list_id = ncvarid (exoid, VAR_NODE_NS(node_set_id_ndx))) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to locate node set %d node list in file id %d",
             node_set_id,exoid);
     ex_err("ex_get_node_set",errmsg,exerrval);
     return (EX_FATAL);
   }


/* read in the node list array */

/* application code has allocated an array of ints but netcdf is expecting
   a pointer to nclongs;  if ints are different sizes than nclongs,
   we must allocate an array of nclongs then convert them to ints with ltoi */

   start[0] = 0;
   count[0] = num_nodes_in_set;

   if (sizeof(int) == sizeof(nclong)) {
     iresult = ncvarget (exoid, node_list_id, start, count, node_set_node_list);
   } else {
     if (!(longs = static_cast<nclong*>(malloc(num_nodes_in_set * sizeof(nclong))))) {
       exerrval = EX_MEMFAIL;
       sprintf(errmsg,
               "Error: failed to allocate memory for node set node list for file id %d",
               exoid);
       ex_err("ex_get_node_set",errmsg,exerrval);
       return (EX_FATAL);
     }
      iresult = ncvarget (exoid, node_list_id, start, count, longs);
   }

   if (iresult == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
            "Error: failed to get node set node list in file id %d",
             exoid);
     ex_err("ex_get_node_set",errmsg,exerrval);
     return (EX_FATAL);
   }

   if (sizeof(int) != sizeof(nclong)) {
      ltoi (longs, node_set_node_list, num_nodes_in_set);
      free (longs);
   }

   return (EX_NOERR);

}
Ejemplo n.º 25
0
int ex_get_conn( int   exoid,
                 int   blk_type,
                 int   blk_id,
                 int*  nodeconn,
                 int*  edgeconn,
                 int*  faceconn )
{
   int numblkentriesdim, connid, econnid, fconnid, blk_id_ndx, iresult;
   int numnodperentdim, numedgperentdim, numfacperentdim;
   int iexit = (EX_NOERR); /* exit status */
   long num_entries_this_blk, num_nodes_per_entry, num_edges_per_entry, num_faces_per_entry;
   long start[2], count[2]; 
   nclong *longs;
   char errmsg[MAX_ERR_LENGTH];

   const char* tname;
   const char* vblkids;
   const char* dnumblkent;
   const char* dnumnodent;
   const char* dnumedgent;
   const char* dnumfacent;
   const char* vnodeconn;
   const char* vedgeconn;
   const char* vfaceconn;

   /* Should we warn if edgeconn or faceconn are non-NULL?
    * No, fail silently so the same code can be used to read any type of block info.
    * However, we will warn if edgeconn or faceconn are NULL but num_edges_per_entry
    * or num_faces_per_entry (respectively) are positive.
    */
   switch (blk_type) {
   case EX_EDGE_BLOCK:
     tname = "edge";
     vblkids = VAR_ID_ED_BLK;
     break;
   case EX_FACE_BLOCK:
     tname = "face";
     vblkids = VAR_ID_FA_BLK;
     break;
   case EX_ELEM_BLOCK:
     tname = "element";
     vblkids = VAR_ID_EL_BLK;
     break;
   default:
     exerrval = EX_BADPARAM;
     sprintf( errmsg, "Error: Invalid block type (%d) specified in file id %d", blk_type, exoid );
     ex_err( "ex_get_conn", errmsg, exerrval );
     return (EX_FATAL);
   }

   exerrval = 0; /* clear error code */

   /* Locate index of element block id in VAR_ID_EL_BLK array */

   blk_id_ndx = ex_id_lkup(exoid,vblkids,blk_id);
   if (exerrval != 0) 
   {
     if (exerrval == EX_NULLENTITY)
     {
       sprintf(errmsg,
              "Warning: no connectivity array for NULL %s block %d in file id %d",
               tname,blk_id,exoid);
       ex_err("ex_get_conn",errmsg,EX_MSG);
       return (EX_WARN); /* no connectivity array for this element block */
     }
     else
     {
       sprintf(errmsg,
        "Error: failed to locate %s block id %d in %s array in file id %d",
               tname,blk_id,vblkids,exoid);
       ex_err("ex_get_conn",errmsg,exerrval);
       return (EX_FATAL);
     }
   }

   switch (blk_type) {
   case EX_EDGE_BLOCK:
     dnumblkent = DIM_NUM_ED_IN_EBLK(blk_id_ndx);
     dnumnodent = DIM_NUM_NOD_PER_ED(blk_id_ndx);
     dnumedgent = 0;
     dnumfacent = 0;
     vnodeconn = VAR_EBCONN(blk_id_ndx);
     vedgeconn = 0;
     vfaceconn = 0;
     break;
   case EX_FACE_BLOCK:
     dnumblkent = DIM_NUM_FA_IN_FBLK(blk_id_ndx);
     dnumnodent = DIM_NUM_NOD_PER_FA(blk_id_ndx);
     dnumedgent = 0;
     dnumfacent = 0;
     vnodeconn = VAR_FBCONN(blk_id_ndx);
     vedgeconn = 0;
     vfaceconn = 0;
     break;
   case EX_ELEM_BLOCK:
     dnumblkent = DIM_NUM_EL_IN_BLK(blk_id_ndx);
     dnumnodent = DIM_NUM_NOD_PER_EL(blk_id_ndx);
     dnumedgent = DIM_NUM_EDG_PER_EL(blk_id_ndx);
     dnumfacent = DIM_NUM_FAC_PER_EL(blk_id_ndx);
     vnodeconn = VAR_CONN(blk_id_ndx);
     vedgeconn = VAR_ECONN(blk_id_ndx);
     vfaceconn = VAR_FCONN(blk_id_ndx);
     break;
   }
/* inquire id's of previously defined dimensions  */

   if ((numblkentriesdim = ncdimid (exoid, dnumblkent)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
     "Error: failed to locate number of elements in %s block %d in file id %d",
              tname,blk_id,exoid);
     ex_err("ex_get_conn",errmsg, exerrval);
     return(EX_FATAL);
   }

   if (ncdiminq (exoid, numblkentriesdim, (char *) 0, &num_entries_this_blk) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
           "Error: failed to get number of entries in %s block %d in file id %d",
             tname,blk_id,exoid);
     ex_err("ex_get_conn",errmsg,exerrval);
     return(EX_FATAL);
   }


   if ((numnodperentdim = ncdimid (exoid, dnumnodent)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
      "Error: failed to locate number of nodes/elem for block %d in file id %d",
             blk_id,exoid);
     ex_err("ex_get_conn",errmsg,exerrval);
     return(EX_FATAL);
   }

   if (ncdiminq (exoid, numnodperentdim, (char *) 0, &num_nodes_per_entry) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
       "Error: failed to get number of nodes/elem for block %d in file id %d",
             blk_id,exoid);
     ex_err("ex_get_conn",errmsg, exerrval);
     return(EX_FATAL);
   }

   if ( dnumedgent ) {
     num_edges_per_entry = 0;
     if ((numedgperentdim = ncdimid (exoid, dnumedgent)) == -1) {
       numedgperentdim = -1;
     } else {
       if (ncdiminq (exoid, numedgperentdim, (char *) 0, &num_edges_per_entry) == -1) {
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to get number of edges/entry for %s block %d in file id %d",
           tname,blk_id,exoid);
         ex_err("ex_get_conn",errmsg, exerrval);
         return(EX_FATAL);
       }
       if ( num_edges_per_entry < 0 )
         num_edges_per_entry = 0;
     }
     if ( num_edges_per_entry > 0 && (!edgeconn) ) {
       exerrval = EX_BADPARAM;
       sprintf( errmsg, "Edge connectivity present but NULL pointer passed for file id %d", exoid );
       ex_err( "ex_get_conn", errmsg, exerrval );
       iexit = exerrval;
     }
   }

   if ( dnumfacent ) {
     num_faces_per_entry = 0;
     if ((numfacperentdim = ncdimid (exoid, dnumfacent)) == -1) {
       numfacperentdim = -1;
     } else {
       if (ncdiminq (exoid, numfacperentdim, (char *) 0, &num_faces_per_entry) == -1) {
         exerrval = ncerr;
         sprintf(errmsg,
           "Error: failed to get number of faces/entry for %s block %d in file id %d",
           tname,blk_id,exoid);
         ex_err("ex_get_conn",errmsg, exerrval);
         return(EX_FATAL);
       }
       if ( num_faces_per_entry < 0 )
         num_faces_per_entry = 0;
     }
     if ( num_faces_per_entry > 0 && (!faceconn) ) {
       exerrval = EX_BADPARAM;
       sprintf( errmsg, "Face connectivity present but NULL pointer passed for file id %d", exoid );
       ex_err( "ex_get_conn", errmsg, exerrval );
       iexit = exerrval;
     }
   }


   if ((connid = ncvarid (exoid, vnodeconn)) == -1)
   {
     exerrval = ncerr;
     sprintf(errmsg,
        "Error: failed to locate connectivity array for block %d in file id %d",
             blk_id,exoid);
     ex_err("ex_get_conn",errmsg, exerrval);
     return(EX_FATAL);
   }

   if ( edgeconn && (numedgperentdim > 0) && ((econnid = ncvarid (exoid, vedgeconn)) == -1) )
   {
     exerrval = ncerr;
     sprintf(errmsg,
        "Error: failed to locate edge connectivity array for %s block %d in file id %d",
             tname,blk_id,exoid);
     ex_err("ex_get_conn",errmsg, exerrval);
     return(EX_FATAL);
   }

   if ( faceconn && (numfacperentdim > 0) && ((fconnid = ncvarid (exoid, vfaceconn)) == -1) )
   {
     exerrval = ncerr;
     sprintf(errmsg,
        "Error: failed to locate face connectivity array for %s block %d in file id %d",
             tname,blk_id,exoid);
     ex_err("ex_get_conn",errmsg, exerrval);
     return(EX_FATAL);
   }


/* read in the connectivity array */

/* application code has allocated an array of ints but netcdf is expecting
   a pointer to nclongs;  if ints are different sizes than nclongs,
   we must allocate an array of nclongs then convert them to ints with ltoi */

   start[0] = 0;
   start[1] = 0;

   if ( edgeconn && num_edges_per_entry ) {
     count[0] = num_entries_this_blk;
     count[1] = num_edges_per_entry;

     if (sizeof(int) == sizeof(nclong)) {
       iresult = ncvarget (exoid, econnid, start, count, edgeconn);
     } else {
       if (!(longs = malloc (num_entries_this_blk*num_edges_per_entry * sizeof(nclong)))) {
         exerrval = EX_MEMFAIL;
         sprintf(errmsg,
           "Error: failed to allocate memory for edge connectivity array for file id %d",
           exoid);
         ex_err("ex_get_conn",errmsg,exerrval);
         return (EX_FATAL);
       }
       iresult = ncvarget (exoid, econnid, start, count, longs);
     }

     if (iresult == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get edge connectivity array for block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_get_conn",errmsg, exerrval);
       return(EX_FATAL);
       }

     if (sizeof(int) != sizeof(nclong)) {
       ltoi (longs, edgeconn, num_entries_this_blk*num_edges_per_entry);
       free (longs);
     }
   }

   if ( faceconn && num_faces_per_entry ) {
     count[0] = num_entries_this_blk;
     count[1] = num_faces_per_entry;

     if (sizeof(int) == sizeof(nclong)) {
       iresult = ncvarget (exoid, fconnid, start, count, faceconn);
     } else {
       if (!(longs = malloc (num_entries_this_blk*num_faces_per_entry * sizeof(nclong)))) {
         exerrval = EX_MEMFAIL;
         sprintf(errmsg,
           "Error: failed to allocate memory for face connectivity array of %s blockfor file id %d",
           tname,exoid);
         ex_err("ex_get_conn",errmsg,exerrval);
         return (EX_FATAL);
       }
       iresult = ncvarget (exoid, fconnid, start, count, longs);
     }

     if (iresult == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get face connectivity array for %s block %d in file id %d",
         tname,blk_id,exoid);
       ex_err("ex_get_conn",errmsg, exerrval);
       return(EX_FATAL);
       }

     if (sizeof(int) != sizeof(nclong)) {
       ltoi (longs, faceconn, num_entries_this_blk*num_faces_per_entry);
       free (longs);
     }
   }

   if ( nodeconn && num_nodes_per_entry ) {
     count[0] = num_entries_this_blk;
     count[1] = num_nodes_per_entry;

     if (sizeof(int) == sizeof(nclong)) {
       iresult = ncvarget (exoid, connid, start, count, nodeconn);
     } else {
       if (!(longs = malloc (num_entries_this_blk*num_nodes_per_entry * sizeof(nclong)))) {
         exerrval = EX_MEMFAIL;
         sprintf(errmsg,
           "Error: failed to allocate memory for element connectivity array for file id %d",
           exoid);
         ex_err("ex_get_conn",errmsg,exerrval);
         return (EX_FATAL);
       }
       iresult = ncvarget (exoid, connid, start, count, longs);
     }

     if (iresult == -1)
       {
       exerrval = ncerr;
       sprintf(errmsg,
         "Error: failed to get connectivity array for block %d in file id %d",
         blk_id,exoid);
       ex_err("ex_get_conn",errmsg, exerrval);
       return(EX_FATAL);
       }

     if (sizeof(int) != sizeof(nclong)) {
       ltoi (longs, nodeconn, num_entries_this_blk*num_nodes_per_entry);
       free (longs);
     }
   }

   return iexit;
}
Ejemplo n.º 26
0
int
main(int argc, char **argv)
{
    /* NIFTI stuff */
    nifti_image *nii_ptr;
    nifti_image nii_rec;
    int nii_dimids[MAX_NII_DIMS];
    int nii_dir[MAX_NII_DIMS];
    int nii_map[MAX_NII_DIMS];
    unsigned long nii_lens[MAX_NII_DIMS];
    int nii_ndims;
    static int nifti_filetype;
    static int nifti_datatype;
    static int nifti_signed = 1;

    /* MINC stuff */
    int mnc_fd;                 /* MINC file descriptor */
    nc_type mnc_type;           /* MINC data type as read */
    int mnc_ndims;              /* MINC image dimension count */
    int mnc_dimids[MAX_VAR_DIMS]; /* MINC image dimension identifiers */
    long mnc_dlen;              /* MINC dimension length value */
    double mnc_dstep;           /* MINC dimension step value */
    int mnc_icv;                /* MINC image conversion variable */
    int mnc_vid;                /* MINC Image variable ID */
    long mnc_start[MAX_VAR_DIMS]; /* MINC data starts */
    long mnc_count[MAX_VAR_DIMS]; /* MINC data counts */
    int mnc_signed;             /* MINC if output voxels are signed */
    double mnc_rrange[2];       /* MINC real range (min, max) */
    double mnc_vrange[2];       /* MINC valid range (min, max) */

    /* Other stuff */
    char out_str[1024];         /* Big string for filename */
    char att_str[1024];         /* Big string for attribute values */
    int i;                      /* Generic loop counter the first */
    int j;                      /* Generic loop counter the second */
    char *str_ptr;              /* Generic ASCIZ string pointer */
    int r;                      /* Result code. */
    static int qflag = 0;       /* Quiet flag (default is non-quiet) */

    static ArgvInfo argTable[] = {
        {NULL, ARGV_HELP, NULL, NULL,
         "Output voxel data type specification"},
        {"-byte", ARGV_CONSTANT, (char *)DT_INT8, (char *)&nifti_datatype,
         "Write voxel data in 8-bit signed integer format."},
        {"-short", ARGV_CONSTANT, (char *)DT_INT16, (char *)&nifti_datatype,
         "Write voxel data in 16-bit signed integer format."},
        {"-int", ARGV_CONSTANT, (char *)DT_INT32, (char *)&nifti_datatype,
         "Write voxel data in 32-bit signed integer format."},
        {"-float", ARGV_CONSTANT, (char *)DT_FLOAT32, (char *)&nifti_datatype,
         "Write voxel data in 32-bit floating point format."},
        {"-double", ARGV_CONSTANT, (char *)DT_FLOAT64, (char *)&nifti_datatype,
         "Write voxel data in 64-bit floating point format."},
        {"-signed", ARGV_CONSTANT, (char *)1, (char *)&nifti_signed,
         "Write integer voxel data in signed format."},
        {"-unsigned", ARGV_CONSTANT, (char *)0, (char *)&nifti_signed,
         "Write integer voxel data in unsigned format."},
        {NULL, ARGV_HELP, NULL, NULL,
         "Output file format specification"},
        {"-dual", ARGV_CONSTANT, (char *)FT_NIFTI_DUAL, 
         (char *)&nifti_filetype,
         "Write NIfTI-1 two-file format (.img and .hdr)"},
        {"-ASCII", ARGV_CONSTANT, (char *)FT_NIFTI_ASCII, 
         (char *)&nifti_filetype,
         "Write NIfTI-1 ASCII header format (.nia)"},
        {"-nii", ARGV_CONSTANT, (char *)FT_NIFTI_SINGLE, 
         (char *)&nifti_filetype,
         "Write NIfTI-1 one-file format (.nii)"},
        {"-analyze", ARGV_CONSTANT, (char *)FT_ANALYZE, 
         (char *)&nifti_filetype,
         "Write an Analyze two-file format file (.img and .hdr)"},
        {NULL, ARGV_HELP, NULL, NULL,
         "Other options"},
        {"-quiet", ARGV_CONSTANT, (char *)0, 
         (char *)&qflag,
         "Quiet operation"},
        {NULL, ARGV_END, NULL, NULL, NULL}
    };

    ncopts = 0;                 /* Clear global netCDF error reporting flag */

    /* Default NIfTI file type is "NII", single binary file
     */
    nifti_filetype = FT_UNSPECIFIED;
    nifti_datatype = DT_UNKNOWN;

    if (ParseArgv(&argc, argv, argTable, 0) || (argc < 2)) {
        fprintf(stderr, "Too few arguments\n");
        return usage();
    }

    if (!nifti_signed) {
        switch (nifti_datatype) {
        case DT_INT8:
            nifti_datatype = DT_UINT8;
            break;
        case DT_INT16:
            nifti_datatype = DT_UINT16;
            break;
        case DT_INT32:
            nifti_datatype = DT_UINT32;
            break;
        }
    }
    switch (nifti_datatype){
    case DT_INT8:
    case DT_UINT8:
        mnc_type = NC_BYTE;
        break;
    case DT_INT16:
    case DT_UINT16:
        mnc_type = NC_SHORT;
        break;
    case DT_INT32:
    case DT_UINT32:
        mnc_type = NC_INT;
        break;
    case DT_FLOAT32:
        mnc_type = NC_FLOAT;
        break;
    case DT_FLOAT64:
        mnc_type = NC_DOUBLE;
        break;
    }

    if (argc == 2) {
        strcpy(out_str, argv[1]);
        str_ptr = strrchr(out_str, '.');
        if (str_ptr != NULL && !strcmp(str_ptr, ".mnc")) {
            *str_ptr = '\0';
        }
    }
    else if (argc == 3) {
        strcpy(out_str, argv[2]);
        str_ptr = strrchr(out_str, '.');
        if (str_ptr != NULL) {
            /* See if a recognized file extension was specified.  If so,
             * we trim it off and set the output file type if none was
             * specified.  If the extension is not recognized, assume
             * that we will form the filename by just adding the right
             * extension for the selected output format.
             */
            if (!strcmp(str_ptr, ".nii")) {
                if (nifti_filetype == FT_UNSPECIFIED) {
                    nifti_filetype = FT_NIFTI_SINGLE;
                }
                *str_ptr = '\0';
            }
            else if (!strcmp(str_ptr, ".img") || 
                     !strcmp(str_ptr, ".hdr")) {
                if (nifti_filetype == FT_UNSPECIFIED) {
                    nifti_filetype = FT_NIFTI_DUAL;
                }
                *str_ptr = '\0';
            }
            else if (!strcmp(str_ptr, ".nia")) {
                if (nifti_filetype == FT_UNSPECIFIED) {
                    nifti_filetype = FT_NIFTI_ASCII;
                }
                *str_ptr = '\0';
            }
        }
    }
    else {
        fprintf(stderr, "Filename argument required\n");
        return usage();
    }

    /* Open the MINC file.  It needs to exist.
     */
    mnc_fd = miopen(argv[1], NC_NOWRITE);
    if (mnc_fd < 0) {
        fprintf(stderr, "Can't find input file '%s'\n", argv[1]);
        return (-1);
    }

    /* Find the MINC image variable.  If we can't find it, there is no
     * further processing possible...
     */
    mnc_vid = ncvarid(mnc_fd, MIimage);
    if (mnc_vid < 0) {
        fprintf(stderr, "Can't locate the image variable (mnc_vid=%d)\n", mnc_vid);
        return (-1);
    }

    /* Find out about the MINC image variable - specifically, how many
     * dimensions, and which dimensions.
     */
    r = ncvarinq(mnc_fd, mnc_vid, NULL, NULL, &mnc_ndims, mnc_dimids, NULL);
    if (r < 0) {
        fprintf(stderr, "Can't read information from image variable\n");
        return (-1);
    }
    if (mnc_ndims > MAX_NII_DIMS) {
        fprintf(stderr, "NIfTI-1 files may contain at most %d dimensions\n", 
                MAX_NII_DIMS);
        return (-1);
    }

    /* Initialize the NIfTI structure 
     */
    nii_ptr = &nii_rec;

    init_nifti_header(nii_ptr);

    /* For now we just use the mnc2nii command line as the description
     * field.  Probably we should use something better, perhaps a
     * combination of some other standard MINC fields that might
     * provide more information.
     */
    str_ptr = nii_ptr->descrip;
    for (i = 0; i < argc; i++) {
        char *arg_ptr = argv[i];

        if ((str_ptr - nii_ptr->descrip) >= MAX_NII_DESCRIP) {
            break;
        }

        if (i != 0) {
            *str_ptr++ = ' ';
        }

        while (*arg_ptr != '\0' && 
               (str_ptr - nii_ptr->descrip) < MAX_NII_DESCRIP) {
            *str_ptr++ = *arg_ptr++;
        }
        *str_ptr = '\0';
    }

    nii_ptr->fname = malloc(strlen(out_str) + 4 + 1);
    nii_ptr->iname = malloc(strlen(out_str) + 4 + 1);
    strcpy(nii_ptr->fname, out_str);
    strcpy(nii_ptr->iname, out_str);

    switch (nifti_filetype) {
    case FT_ANALYZE:
        strcat(nii_ptr->fname, ".hdr");
        strcat(nii_ptr->iname, ".img");
        break;
    case FT_NIFTI_SINGLE:
        strcat(nii_ptr->fname, ".nii");
        strcat(nii_ptr->iname, ".nii");
        break;
    case FT_NIFTI_DUAL:
        strcat(nii_ptr->fname, ".hdr");
        strcat(nii_ptr->iname, ".img");
        break;
    case FT_NIFTI_ASCII:
        strcat(nii_ptr->fname, ".nia");
        strcat(nii_ptr->iname, ".nia");
        break;
    default:
        fprintf(stderr, "Unknown output file type %d\n", nifti_filetype);
        return (-1);
    }

    miget_image_range(mnc_fd, mnc_rrange); /* Get real range */
    miget_valid_range(mnc_fd, mnc_vid, mnc_vrange); /* Get voxel range */

    if (mnc_vrange[1] != mnc_vrange[0] && mnc_rrange[1] != mnc_rrange[0]) {
        nii_ptr->scl_slope = ((mnc_rrange[1] - mnc_rrange[0]) / 
                              (mnc_vrange[1] - mnc_vrange[0]));
        nii_ptr->scl_inter = mnc_rrange[0] - (mnc_vrange[0] * nii_ptr->scl_slope);
    }
    else {
        nii_ptr->scl_slope = 0.0;
    }

    nii_ptr->nvox = 1;          /* Initial value for voxel count */

    /* Find all of the dimensions of the MINC file, in the order they 
     * will be listed in the NIfTI-1/Analyze file.  We use this to build
     * a map for restructuring the data according to the normal rules
     * of NIfTI-1.
     */
    nii_ndims = 0;
    for (i = 0; i < MAX_NII_DIMS; i++) {
        if (dimnames[i] == NULL) {
            nii_dimids[nii_ndims] = -1;
            continue;
        }

        nii_dimids[nii_ndims] = ncdimid(mnc_fd, dimnames[i]);
        if (nii_dimids[nii_ndims] == -1) {
            continue;
        }

        /* Make sure the dimension is actually used to define the image.
         */
        for (j = 0; j < mnc_ndims; j++) {
            if (nii_dimids[nii_ndims] == mnc_dimids[j]) {
                nii_map[nii_ndims] = j;
                break;
            }
        }

        if (j < mnc_ndims) {
            mnc_dlen = 1;
            mnc_dstep = 0;

            ncdiminq(mnc_fd, nii_dimids[nii_ndims], NULL, &mnc_dlen);
            ncattget(mnc_fd, ncvarid(mnc_fd, dimnames[i]), MIstep, &mnc_dstep);

            if (mnc_dstep < 0) {
                nii_dir[nii_ndims] = -1;
                mnc_dstep = -mnc_dstep;
            }
            else {
                nii_dir[nii_ndims] = 1;
            }

            nii_lens[nii_ndims] = mnc_dlen;
            nii_ndims++;
        }

        nii_ptr->dim[dimmap[i]] = (int) mnc_dlen;
        nii_ptr->nvox *= mnc_dlen;

        nii_ptr->pixdim[dimmap[i]] = (float) mnc_dstep;
    }

    /* Here we do some "post-processing" of the results. Make certain that
     * the nt value is never zero, and make certain that ndim is set to
     * 4 if there is a time dimension and 5 if there is a vector dimension
     */

    if (nii_ptr->dim[3] > 1 && nii_ndims < 4) {
        nii_ndims = 4;
    }

    if (nii_ptr->dim[4] > 1) {
        nii_ptr->intent_code = NIFTI_INTENT_VECTOR;
        nii_ndims = 5;
    }

    nii_ptr->ndim = nii_ndims; /* Total number of dimensions in file */
    nii_ptr->nx = nii_ptr->dim[0];
    nii_ptr->ny = nii_ptr->dim[1];
    nii_ptr->nz = nii_ptr->dim[2];
    nii_ptr->nt = nii_ptr->dim[3];
    nii_ptr->nu = nii_ptr->dim[4];

    nii_ptr->dx = nii_ptr->pixdim[0];
    nii_ptr->dy = nii_ptr->pixdim[1];
    nii_ptr->dz = nii_ptr->pixdim[2];
    nii_ptr->dt = nii_ptr->pixdim[3];
    nii_ptr->du = 1; /* MINC files don't define a sample size for a vector_dimension */

    nii_ptr->nifti_type = nifti_filetype;

    if (nifti_datatype == DT_UNKNOWN) {
        nii_ptr->datatype = DT_FLOAT32; /* Default */
        mnc_type = NC_FLOAT;
        mnc_signed = 1;
    }
    else {
        nii_ptr->datatype = nifti_datatype;
    }


    /* Load the direction_cosines and start values into the NIfTI-1 
     * sform structure.
     *
     */
    for (i = 0; i < MAX_SPACE_DIMS; i++) {
        int id = ncvarid(mnc_fd, mnc_spatial_names[i]);
        double start;
        double step;
        double dircos[MAX_SPACE_DIMS];
        int tmp;

        if (id < 0) {
            continue;
        }

        /* Set default values */
        start = 0.0;
        step = 1.0;
        dircos[DIM_X] = dircos[DIM_Y] = dircos[DIM_Z] = 0.0;
        dircos[i] = 1.0;

        miattget(mnc_fd, id, MIstart, NC_DOUBLE, 1, &start, &tmp);
        miattget(mnc_fd, id, MIstep, NC_DOUBLE, 1, &step, &tmp);
        miattget(mnc_fd, id, MIdirection_cosines, NC_DOUBLE, MAX_SPACE_DIMS, 
                 dircos, &tmp);
        ncdiminq(mnc_fd, ncdimid(mnc_fd, mnc_spatial_names[i]), NULL, 
                 &mnc_dlen);

        if (step < 0) {
            step = -step;
            start = start - step * (mnc_dlen - 1);
        }

        nii_ptr->sto_xyz.m[0][i] = step * dircos[0];
        nii_ptr->sto_xyz.m[1][i] = step * dircos[1];
        nii_ptr->sto_xyz.m[2][i] = step * dircos[2];

        nii_ptr->sto_xyz.m[0][3] += start * dircos[0];
        nii_ptr->sto_xyz.m[1][3] += start * dircos[1];
        nii_ptr->sto_xyz.m[2][3] += start * dircos[2];

        miattgetstr(mnc_fd, id, MIspacetype, sizeof(att_str), att_str);

        /* Try to set the S-transform code correctly.
         */
        if (!strcmp(att_str, MI_TALAIRACH)) {
            nii_ptr->sform_code = NIFTI_XFORM_TALAIRACH;
        }
        else if (!strcmp(att_str, MI_CALLOSAL)) {
            /* TODO: Not clear what do do here... */
            nii_ptr->sform_code = NIFTI_XFORM_SCANNER_ANAT;
        }
        else {                  /* MI_NATIVE or unknown */
            nii_ptr->sform_code = NIFTI_XFORM_SCANNER_ANAT;
        }
    }

    /* So the last row is right... */
    nii_ptr->sto_xyz.m[3][0] = 0.0;
    nii_ptr->sto_xyz.m[3][1] = 0.0;
    nii_ptr->sto_xyz.m[3][2] = 0.0;
    nii_ptr->sto_xyz.m[3][3] = 1.0;

    nii_ptr->sto_ijk = nifti_mat44_inverse(nii_ptr->sto_xyz);

    nifti_datatype_sizes(nii_ptr->datatype, 
                         &nii_ptr->nbyper, &nii_ptr->swapsize);


    if (!qflag) {
        nifti_image_infodump(nii_ptr);
    }

    /* Now load the actual MINC data. */

    nii_ptr->data = malloc(nii_ptr->nbyper * nii_ptr->nvox);
    if (nii_ptr->data == NULL) {
        fprintf(stderr, "Out of memory.\n");
        return (-1);
    }

    if (!qflag) {
        fprintf(stderr, "MINC type %d signed %d\n", mnc_type, mnc_signed);
    }

    mnc_icv = miicv_create();
    miicv_setint(mnc_icv, MI_ICV_TYPE, mnc_type);
    miicv_setstr(mnc_icv, MI_ICV_SIGN, (mnc_signed) ? MI_SIGNED : MI_UNSIGNED);
    miicv_setdbl(mnc_icv, MI_ICV_VALID_MAX, mnc_vrange[1]);
    miicv_setdbl(mnc_icv, MI_ICV_VALID_MIN, mnc_vrange[0]);
    miicv_setint(mnc_icv, MI_ICV_DO_NORM, 1);

    miicv_attach(mnc_icv, mnc_fd, mnc_vid);

    /* Read in the entire hyperslab from the file.
     */
    for (i = 0; i < mnc_ndims; i++) {
        ncdiminq(mnc_fd, mnc_dimids[i], NULL, &mnc_count[i]);
        mnc_start[i] = 0;
    }

    r = miicv_get(mnc_icv, mnc_start, mnc_count, nii_ptr->data);
    if (r < 0) {
        fprintf(stderr, "Read error\n");
        return (-1);
    }

    /* Shut down the MINC stuff now that it has done its work. 
     */
    miicv_detach(mnc_icv);
    miicv_free(mnc_icv);
    miclose(mnc_fd);

    if (!qflag) {
        /* Debugging stuff - just to check the contents of these arrays.
         */
        for (i = 0; i < nii_ndims; i++) {
            printf("%d: %ld %d %d\n", 
                   i, nii_lens[i], nii_map[i], nii_dir[i]);
        }
        printf("bytes per voxel %d\n", nii_ptr->nbyper);
        printf("# of voxels %ld\n", nii_ptr->nvox);
    }

    /* Rearrange the data to correspond to the NIfTI dimension ordering.
     */
    restructure_array(nii_ndims,
                      nii_ptr->data,
                      nii_lens,
                      nii_ptr->nbyper,
                      nii_map,
                      nii_dir);

    if (!qflag) {
        /* More debugging stuff - check coordinate transform.
         */
        test_xform(nii_ptr->sto_xyz, 0, 0, 0);
        test_xform(nii_ptr->sto_xyz, 10, 0, 0);
        test_xform(nii_ptr->sto_xyz, 0, 10, 0);
        test_xform(nii_ptr->sto_xyz, 0, 0, 10);
        test_xform(nii_ptr->sto_xyz, 10, 10, 10);
    }
    
    fprintf(stdout, "Calling NIFTI-1 Write routine\n");
    nifti_image_write(nii_ptr);

    return (0);
}
Ejemplo n.º 27
0
/*
 * TODO, lots of declared, but unused variables here
 */
static void do_netcdfquery_proc(Widget, XtPointer, XtPointer)
{
    int setno, src;
    char xvar[256], yvar[256];
    char buf[256], fname[512];
    XmString xms;
    XmString *s, cs;
    int *pos_list;
    int i, j, pos_cnt, cnt;
    char *cstr;

    int cdfid; /* netCDF id */
    int ndims, nvars, ngatts, recdim;
    int var_id;
    long start[2];
    long count[2];
    char varname[256];
    nc_type datatype = 0;
    int dim[100], natts;
    long dimlen[100];
    long len;

    int x_id, y_id;
    nc_type xdatatype = 0;
    nc_type ydatatype = 0;
    int xndims, xdim[10], xnatts;
    int yndims, ydim[10], ynatts;
    long nx, ny;

    int atlen;
    char attname[256];
    char atcharval[256];

    extern int ncopts;

    ncopts = 0; /* no crash on error */

    set_wait_cursor();

    strcpy(fname, xv_getstr(netcdf_file_item));

    if ((cdfid = ncopen(fname, NC_NOWRITE)) == -1)
    {
        errwin("Can't open file.");
        goto out2;
    }
    if (XmListGetSelectedPos(netcdf_listx_item, &pos_list, &pos_cnt))
    {
        XtVaGetValues(netcdf_listx_item,
                      XmNselectedItemCount, &cnt,
                      XmNselectedItems, &s,
                      NULL);
        cs = XmStringCopy(*s);
        if (XmStringGetLtoR(cs, charset, &cstr))
        {
            strcpy(xvar, cstr);
            XtFree(cstr);
        }
        XmStringFree(cs);
    }
    else
    {
        errwin("Need to select X, either variable name or INDEX");
        goto out1;
    }
    if (XmListGetSelectedPos(netcdf_listy_item, &pos_list, &pos_cnt))
    {
        XtVaGetValues(netcdf_listy_item,
                      XmNselectedItemCount, &cnt,
                      XmNselectedItems, &s,
                      NULL);
        cs = XmStringCopy(*s);
        if (XmStringGetLtoR(cs, charset, &cstr))
        {
            strcpy(yvar, cstr);
            XtFree(cstr);
        }
        XmStringFree(cs);
    }
    else
    {
        errwin("Need to select Y");
        goto out1;
    }
    if (strcmp(xvar, "INDEX") == 0)
    {
        stufftext("X is the index of the Y variable\n", STUFF_START);
    }
    else
    {
        if ((x_id = ncvarid(cdfid, xvar)) == -1)
        {
            char ebuf[256];
            sprintf(ebuf, "do_query(): No such variable %s for X", xvar);
            errwin(ebuf);
            goto out1;
        }
        ncvarinq(cdfid, x_id, NULL, &xdatatype, &xndims, xdim, &xnatts);
        ncdiminq(cdfid, xdim[0], NULL, &nx);
        sprintf(buf, "X is %s, data type %s \t length [%d]\n", xvar, getcdf_type(xdatatype), nx);
        stufftext(buf, STUFF_TEXT);
        sprintf(buf, "\t%d Attributes:\n", xnatts);
        stufftext(buf, STUFF_TEXT);
        for (i = 0; i < xnatts; i++)
        {
            atcharval[0] = 0;
            ncattname(cdfid, x_id, i, attname);
            ncattinq(cdfid, x_id, attname, &datatype, &atlen);
            switch (datatype)
            {
            case NC_CHAR:
                ncattget(cdfid, x_id, attname, (void *)atcharval);
                break;
            }
            sprintf(buf, "\t\t%s: %s\n", attname, atcharval);
            stufftext(buf, STUFF_TEXT);
        }
    }
    if ((y_id = ncvarid(cdfid, yvar)) == -1)
    {
        char ebuf[256];
        sprintf(ebuf, "do_query(): No such variable %s for Y", yvar);
        errwin(ebuf);
        goto out1;
    }
    ncvarinq(cdfid, y_id, NULL, &ydatatype, &yndims, ydim, &ynatts);
    ncdiminq(cdfid, ydim[0], NULL, &ny);
    sprintf(buf, "Y is %s, data type %s \t length [%d]\n", yvar, getcdf_type(ydatatype), ny);
    stufftext(buf, STUFF_TEXT);
    sprintf(buf, "\t%d Attributes:\n", ynatts);
    stufftext(buf, STUFF_TEXT);
    for (i = 0; i < ynatts; i++)
    {
        atcharval[0] = 0;
        ncattname(cdfid, y_id, i, attname);
        ncattinq(cdfid, y_id, attname, &datatype, &atlen);
        switch (datatype)
        {
        case NC_CHAR:
            ncattget(cdfid, y_id, attname, (void *)atcharval);
            break;
        }
        sprintf(buf, "\t\t%s: %s\n", attname, atcharval);
        stufftext(buf, STUFF_TEXT);
    }

out1:
    ;
    ncclose(cdfid);

out2:
    ;
    stufftext("\n", STUFF_STOP);
    unset_wait_cursor();
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
   char *filename;
   int mincid, imgid, icvid, ndims, dims[MAX_VAR_DIMS];
   nc_type datatype;
   int is_signed;
   long start[MAX_VAR_DIMS], count[MAX_VAR_DIMS], end[MAX_VAR_DIMS];
   long size;
   int idim;
   void *data;
   double temp;

   /* Check arguments */
   if (ParseArgv(&argc, argv, argTable, 0) || (argc != 2)) {
      (void) fprintf(stderr, "\nUsage: %s [<options>] <mincfile>\n", argv[0]);
      (void) fprintf(stderr,   "       %s -help\n\n", argv[0]);
      exit(EXIT_FAILURE);
   }
   filename = argv[1];

   /* Check that a normalization option was specified */
   if (normalize_output == VIO_BOOL_DEFAULT) {
      (void) fprintf(stderr, 
                     "Please specify either -normalize or -nonormalize\n");
      (void) fprintf(stderr, "Usually -normalize is most appropriate\n");
      exit(EXIT_FAILURE);
   }

   /* Open the file */
   mincid = miopen(filename, NC_NOWRITE);

   /* Inquire about the image variable */
   imgid = ncvarid(mincid, MIimage);
   (void) ncvarinq(mincid, imgid, NULL, NULL, &ndims, dims, NULL);
   (void)miget_datatype(mincid, imgid, &datatype, &is_signed);

   /* Check if arguments set */

   /* Get output data type */
   if (output_datatype == INT_MAX) output_datatype = datatype;

   /* Get output sign */ 
   if (output_signed == INT_MAX) {
      if (output_datatype == datatype)
         output_signed = is_signed;
      else 
         output_signed = (output_datatype != NC_BYTE);
   }

   /* Get output range */
   if (valid_range[0] == DBL_MAX) {
      if ((output_datatype == datatype) && (output_signed == is_signed)) {
         (void) miget_valid_range(mincid, imgid, valid_range);
      }
      else {
         (void) miget_default_range(output_datatype, output_signed, 
                                    valid_range);
      }
   }
   if (valid_range[0] > valid_range[1]) {
      temp = valid_range[0];
      valid_range[0] = valid_range[1];
      valid_range[1] = temp;
   }

   /* Set up image conversion */
   icvid = miicv_create();
   (void) miicv_setint(icvid, MI_ICV_TYPE, output_datatype);
   (void) miicv_setstr(icvid, MI_ICV_SIGN, (output_signed ? 
                                            MI_SIGNED : MI_UNSIGNED));
   (void) miicv_setdbl(icvid, MI_ICV_VALID_MIN, valid_range[0]);
   (void) miicv_setdbl(icvid, MI_ICV_VALID_MAX, valid_range[1]);
   if ((output_datatype == NC_FLOAT) || (output_datatype == NC_DOUBLE)) {
      (void) miicv_setint(icvid, MI_ICV_DO_NORM, TRUE);
      (void) miicv_setint(icvid, MI_ICV_USER_NORM, TRUE);
   }
   else if (normalize_output) {
      (void) miicv_setint(icvid, MI_ICV_DO_NORM, TRUE);
   }
   (void) miicv_attach(icvid, mincid, imgid);

   /* Set input file start, count and end vectors for reading a slice
      at a time */
   for (idim=0; idim < ndims; idim++) {
      (void) ncdiminq(mincid, dims[idim], NULL, &end[idim]);
   }
   (void) miset_coords(ndims, (long) 0, start);
   (void) miset_coords(ndims, (long) 1, count);
   size = nctypelen(output_datatype);
   for (idim=ndims-2; idim < ndims; idim++) {
      count[idim] = end[idim];
      size *= count[idim];
   }

   /* Allocate space */
   data = malloc(size);

   /* Loop over input slices */

   while (start[0] < end[0]) {

      /* Read in the slice */
      (void) miicv_get(icvid, start, count, data);

      /* Write out the slice */
      if (fwrite(data, sizeof(char), (size_t) size, stdout) != size) {
         (void) fprintf(stderr, "Error writing data.\n");
         exit(EXIT_FAILURE);
      }

      /* Increment start counter */
      idim = ndims-1;
      start[idim] += count[idim];
      while ( (idim>0) && (start[idim] >= end[idim])) {
         start[idim] = 0;
         idim--;
         start[idim] += count[idim];
      }

   }       /* End loop over slices */

   /* Clean up */
   (void) miclose(mincid);
   (void) miicv_free(icvid);
   free(data);

   exit(EXIT_SUCCESS);
}
Ejemplo n.º 29
0
int ex_put_elem_attr (int   exoid,
                      int   elem_blk_id,
                      const void *attrib)
{
   int numelbdim, numattrdim, attrid, elem_blk_id_ndx;
   long num_elem_this_blk, num_attr, start[2], count[2];
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

  /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */
  elem_blk_id_ndx = ex_id_lkup(exoid,VAR_ID_EL_BLK,elem_blk_id);
  if (exerrval != 0) 
  {
    if (exerrval == EX_NULLENTITY)
    {
      sprintf(errmsg,
              "Warning: no attributes allowed for NULL block %d in file id %d",
              elem_blk_id,exoid);
      ex_err("ex_put_elem_attr",errmsg,EX_MSG);
      return (EX_WARN);              /* no attributes for this element block */
    }
    else
    {
      sprintf(errmsg,
             "Error: no element block id %d in %s array in file id %d",
              elem_blk_id, VAR_ID_EL_BLK, exoid);
      ex_err("ex_put_elem_attr",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

/* inquire id's of previously defined dimensions  */

  if ((numelbdim = ncdimid (exoid, DIM_NUM_EL_IN_BLK(elem_blk_id_ndx))) == -1)
  {
    if (ncerr == NC_EBADDIM)
    {
      exerrval = ncerr;
      sprintf(errmsg,
         "Error: no element block with id %d in file id %d",
             elem_blk_id, exoid);
      ex_err("ex_put_elem_attr",errmsg,exerrval);
      return (EX_FATAL);
    }
    else
    {
      exerrval = ncerr;
      sprintf(errmsg,
        "Error: failed to locate number of elements for block %d in file id %d",
             elem_blk_id, exoid);
      ex_err("ex_put_elem_attr",errmsg,exerrval);
      return (EX_FATAL);
    }
  }


  if (ncdiminq (exoid, numelbdim, (char *) 0, &num_elem_this_blk) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
           "Error: failed to get number of elements for block %d in file id %d",
            elem_blk_id,exoid);
    ex_err("ex_put_elem_attr",errmsg,exerrval);
    return (EX_FATAL);
  }


  if ((numattrdim = ncdimid(exoid, DIM_NUM_ATT_IN_BLK(elem_blk_id_ndx))) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
           "Error: number of attributes not defined for block %d in file id %d",
            elem_blk_id,exoid);
    ex_err("ex_put_elem_attr",errmsg,EX_MSG);
    return (EX_FATAL);              /* number of attributes not defined */
  }

  if (ncdiminq (exoid, numattrdim, (char *) 0, &num_attr) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
         "Error: failed to get number of attributes for block %d in file id %d",
            elem_blk_id,exoid);
    ex_err("ex_put_elem_attr",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((attrid = ncvarid (exoid, VAR_ATTRIB(elem_blk_id_ndx))) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
        "Error: failed to locate attribute variable for block %d in file id %d",
            elem_blk_id,exoid);
    ex_err("ex_put_elem_attr",errmsg,exerrval);
    return (EX_FATAL);
  }


/* write out the attributes  */

  start[0] = 0;
  start[1] = 0;

  count[0] = num_elem_this_blk;
  count[1] = num_attr;

  if (ncvarput (exoid, attrid, start, count,
                ex_conv_array(exoid,WRITE_CONVERT,attrib,
                (int)num_attr*num_elem_this_blk)) == -1)
  {
    exerrval = ncerr;
    sprintf(errmsg,
            "Error: failed to put attributes for block %d in file id %d",
            elem_blk_id,exoid);
    ex_err("ex_put_elem_attr",errmsg,exerrval);
    return (EX_FATAL);
  }


  return(EX_NOERR);

}
Ejemplo n.º 30
0
int ex_get_nodal_varid(int exoid, int *varid)
{
  int i, dimid, nvarid;
  long num_vars;
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  if ((dimid = ncdimid (exoid, DIM_NUM_NOD_VAR)) == -1) {
    num_vars = 0;
    if (ncerr == NC_EBADDIM)
      return(EX_NOERR);     /* no nodal variables defined */
    else
      {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to locate nodal variable names in file id %d",
                exoid);
        ex_err("ex_get_nodal_varid",errmsg,exerrval);
        return (EX_FATAL);
      }
  }

  if (ncdiminq (exoid, dimid, (char *) 0, &num_vars) == -1) {
    exerrval = ncerr;
    sprintf(errmsg,
            "Error: failed to get number of nodal variables in file id %d",
            exoid);
    ex_err("ex_get_nodal_varid",errmsg,exerrval);
    return (EX_FATAL);
  }
   
  if (ex_large_model(exoid) == 0) {
    /* All varids are the same; */
    if ((nvarid = ncvarid (exoid, VAR_NOD_VAR)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Warning: could not find nodal variables in file id %d",
              exoid);
      ex_err("ex_get_nodal_varid",errmsg,exerrval);
      return (EX_WARN);
    }
    for (i=0; i < num_vars; i++) {
      varid[i] = nvarid;
    }
  } else {
    /* Variables stored separately; each has a unique varid */
    for (i=0; i < num_vars; i++) {
      if ((nvarid = ncvarid (exoid, VAR_NOD_VAR_NEW(i+1))) == -1) {
        exerrval = ncerr;
        sprintf(errmsg,
                "Warning: could not find nodal variable %d in file id %d",
                i+1, exoid);
        ex_err("ex_get_nodal_varid",errmsg,exerrval);
        return (EX_WARN);
      }
      varid[i] = nvarid;
    }
  }
  return(EX_NOERR);
}