MakeMili.C 50.2 KB
Newer Older
hrchilds's avatar
hrchilds committed
1 2
/*****************************************************************************
*
bonnell's avatar
bonnell committed
3
* Copyright (c) 2000 - 2015, Lawrence Livermore National Security, LLC
hrchilds's avatar
hrchilds committed
4
* Produced at the Lawrence Livermore National Laboratory
5
* LLNL-CODE-442911
hrchilds's avatar
hrchilds committed
6 7
* All rights reserved.
*
8
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
hrchilds's avatar
hrchilds committed
9 10 11 12 13 14 15 16 17 18
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
19 20 21
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
hrchilds's avatar
hrchilds committed
22 23 24 25 26
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
27 28 29
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
hrchilds's avatar
hrchilds committed
30 31 32 33 34 35 36 37 38
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

hrchilds's avatar
hrchilds committed
39 40 41 42 43 44 45 46 47 48 49 50 51
// ***************************************************************************
//  Program: MakeMili
//
//  Purpose: 
//    Create a .mili file from a single or multi domained Mili dataset,
//    suitable for the Mili reader in VisIt. It will read the directory
//    (given by the path of the argument) to determine how many domains
//    there are.
//
//  Arguments:
//    Takes in a root name. Name can either be the Mili family name for
//    a single domained dataset, or the root of a Mili family name for
//    a multi domained dataset.
hrchilds's avatar
hrchilds committed
52 53 54
//
//    Also takes the optional arguments:
//      -dynapart <DynaPart partition file>
hrchilds's avatar
hrchilds committed
55 56 57 58 59
// 
//  Programmer:     Akira Haddox
//  Creation:       June 25, 2003
//
// ***************************************************************************
60 61
// Modifications:
//  I. R. Corey - May 10, 2011: Modified to build standalone from Visit.
62 63 64 65
//     Compile Line: /usr/bin/c++ -I/usr/apps/mdg/include -L/usr/apps/mdg/lib
//                   -g -c MakeMili.C
//     Link Line:    /usr/bin/c++ MakeMili.o -L/usr/apps/mdg/lib -lmili 
//                   -o mdgmakemili  
66 67 68 69 70 71 72
//
//  I. R. Corey - June 11, 2011: Added ability to update number of states.
// ***************************************************************************
//

#define VERSION_STRING "V11.0"
#define DATE_STRING    "June 30, 2011"
hrchilds's avatar
hrchilds committed
73 74

#include <sys/types.h>
75
#include <sys/stat.h> 
hrchilds's avatar
hrchilds committed
76 77 78 79
#include <dirent.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
80
#include <stdlib.h>
81
#include <unistd.h>
hrchilds's avatar
hrchilds committed
82 83 84 85

#include <vector>
#include <string>

86 87 88 89 90 91 92
using namespace std; 
using std::string;

#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
hrchilds's avatar
hrchilds committed
93

hrchilds's avatar
hrchilds committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107
extern "C"{
#include <mili.h>
#include <mili_enum.h>
}

#ifdef PARALLEL
#include <mpi.h>
#endif

//
// Global variables
//

// The rootname and path generated from the arguments.
108
char root[512];
hrchilds's avatar
hrchilds committed
109 110
int rootLen;
char *path;
111
char path_text[256], infoFilename[256];
hrchilds's avatar
hrchilds committed
112 113 114 115

// Flag: set if we're a single domain (and thus handle names differently).
bool singleDomainName = false;

116 117 118
bool verboseMode   = false;
bool createMode = false;

hrchilds's avatar
hrchilds committed
119 120 121 122 123
// Process information. Default values for serial runs.
int numProcesses = 1;
int myRank = 0;

// Number of domains.
124
int ndomains = 1;
hrchilds's avatar
hrchilds committed
125 126 127 128 129 130 131 132

// From avtTypes.h
#define     AVT_SCALAR_VAR      1
#define     AVT_VECTOR_VAR      2 
#define     AVT_UNKNOWN_TYPE    7  
#define     AVT_NODECENT        0
#define     AVT_ZONECENT        1

133 134 135 136
char *dynapartFile = NULL;
char currentPath[512];
bool updateMode = false;

hrchilds's avatar
hrchilds committed
137 138 139 140 141 142 143 144
// ***************************************************************************
//  Struct: MiliInfo
//
//  Purpose:
//    Store information about a Mili dataset. Two different classifications
//    of data are stored: global data only used by the master process, and
//    collected data, which is potentially unique to each domain.
//
hrchilds's avatar
hrchilds committed
145 146 147 148
//  Modifications:
//    Akira Haddox, Fri Jul 25 10:49:57 PDT 2003
//    Added variable dimensionality.
//
hrchilds's avatar
hrchilds committed
149 150 151 152 153 154 155 156 157
// ***************************************************************************

struct MiliInfo
{
  // Used by master process:
    int                             ntimesteps;
    int                             ndomains;
    int                             dimensions;
    int                             numMeshes;
158

hrchilds's avatar
hrchilds committed
159
  // Unique to each domain
160 161
    vector<int>                     numMats;    
    vector<int>                     numVars;
hrchilds's avatar
hrchilds committed
162 163 164 165
    vector<int>                     highestMaterial;
    vector<vector<int> >            varType;
    vector<vector<int> >            varCentering;
    vector<vector<string> >         varNames;
166 167
    vector<vector<string> >         varDescr;
    vector<vector<int> >            varDims;
hrchilds's avatar
hrchilds committed
168 169 170 171 172 173 174
};

//
// Prototypes
//

void DetermineRootAndPath(char *);
175
int  GetNumDomains();
hrchilds's avatar
hrchilds committed
176 177 178 179
void ReadDomain(int, MiliInfo &);
void ReceiveInfo(vector<MiliInfo> &);
void SendInfo(MiliInfo &);
void CompileInfo(const vector<MiliInfo> &, MiliInfo &);
180
void PrintInfo(ostream &o, const MiliInfo &, bool, bool);
hrchilds's avatar
hrchilds committed
181 182
int  VSSearch(const vector<string> &v, const string &s);
void FatalError(const string &);
183 184
void GetGlobalData(MiliInfo &);
void loadMiliFile(char *filename, MiliInfo &);
hrchilds's avatar
hrchilds committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

// ***************************************************************************
//  Function: DetermineRootAndPath
//
//  Purpose:
//    Given an argument, parse out the rootname and the path to the root,
//    storing them in the global variables. Called by the master process.
//
//  Arguments:
//    fname     argument to the program
//
// ***************************************************************************

void DetermineRootAndPath(char *fname)
{
    //
    // Code from GRIZ.
    //
    const char *p_c, *p_src;
    const char *p_root_start, *p_root_end;
    char *p_dest;
 
    /* Scan forward to end of name string. */
    for ( p_c = fname ; *p_c != '\0'; p_c++ );
 
    /* Scan backward to last non-slash character. */
    for ( p_c--; *p_c == '/' && p_c != fname; p_c-- );
    p_root_end = p_c;
 
    /* Scan backward to last slash character preceding last non-slash char. */
    for ( ; *p_c != '/' && p_c != fname; p_c-- );
 
    p_root_start = ( *p_c == '/' ) ? p_c + 1 : p_c;
 
    /* Generate the path argument to mc_open(). */
    if ( p_root_start == fname )
    {
        /* No path preceding root name. Set to . */
        path_text[0] = '.';
        path_text[1] = '\0';
        path = path_text;
    }
    else
    {
        /* Copy path (less last slash). */
 
        path = path_text;
 
        for ( p_src = fname, p_dest = path_text;
              p_src < p_root_start - 1;
              *p_dest++ = *p_src++ );
 
        if ( p_src == fname )
            /* Path must be just "/".  If that's what the app wants... */
            *p_dest++ = *fname;
 
        *p_dest = '\0';
    }
 
    /* Generate root name argument to mc_open(). */
    for ( p_src = p_root_start, p_dest = root;
          p_src <= p_root_end;
          *p_dest++ = *p_src++ );
    *p_dest = '\0';

    rootLen = strlen(root);
251 252

    getcwd(currentPath, sizeof(currentPath));
hrchilds's avatar
hrchilds committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
}


// ***************************************************************************
//  Function: GetNumDomains
//
//  Purpose:
//    Opens the directory specified in the global 'path', and looks for
//    files that match the global 'root'. Given this, it finds how many
//    datasets there are, or if it is a single domain problem. Called by
//    the master process.
//
//  Returns:
//    The number of domains, or 0 on failure.
//
hrchilds's avatar
hrchilds committed
268 269 270 271 272 273
//  Modifications:
//
//    Hank Childs, Mon Dec 20 11:12:24 PST 2004
//    If there is a choice between a multi domain set of files and a single
//    domain file, still continue to choose the multi domain set, but then
//    test to make sure it works.  If it doesn't declare it single domain.
hrchilds's avatar
hrchilds committed
274 275 276 277 278 279 280 281
//
// ***************************************************************************

int GetNumDomains()
{
    int lastdomain = -1;
    dirent *dp;
    DIR *dirp = opendir(path);
282 283 284
    int singleDomain = true;
    int fileLen=0;

hrchilds's avatar
hrchilds committed
285 286 287
    while ((dp = readdir(dirp)) != NULL)
    {
        char const *f = dp->d_name;
288 289
        fileLen=strlen(f);
        if (strstr(f, root) == f && isalpha(f[fileLen-1]))
hrchilds's avatar
hrchilds committed
290 291
        {
            //
292
            // If it starts with our root, look at the next four
hrchilds's avatar
hrchilds committed
293 294 295 296 297
            // characters. If they're numbers, it's a multi domain.
            // If they're not, then it's a single domain.
            // 

            if (isdigit(f[rootLen]) && isdigit(f[rootLen + 1])
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
                                    && isdigit(f[rootLen + 2])
                                    && isdigit(f[rootLen + 3]))
            {
                int thousand = f[rootLen] - '0';
                int hundred = f[rootLen+1] - '0';
                int ten = f[rootLen + 2] - '0';
                int one = f[rootLen + 3] - '0';

                int dom = thousand * 1000 + hundred * 100 + ten * 10 + one;
                if (dom > lastdomain)
                    lastdomain = dom;
                singleDomain = false;
            }
            else
            {
            if (isdigit(f[rootLen]) && isdigit(f[rootLen + 1])
314
                                    && isdigit(f[rootLen + 2]))
hrchilds's avatar
hrchilds committed
315 316 317 318 319 320 321 322
            {
                int hundred = f[rootLen] - '0';
                int ten = f[rootLen + 1] - '0';
                int one = f[rootLen + 2] - '0';

                int dom = hundred * 100 + ten * 10 + one;
                if (dom > lastdomain)
                    lastdomain = dom;
323
                singleDomain = false;
hrchilds's avatar
hrchilds committed
324
            }
325
               }
hrchilds's avatar
hrchilds committed
326 327 328 329 330 331 332
        }
    }
    closedir(dirp);

    // If we find multi domain names, take the multi domain name.
    if (lastdomain != -1)
        singleDomainName = false;
hrchilds's avatar
hrchilds committed
333 334 335 336 337 338 339 340 341 342 343 344

    if (!singleDomainName)
    {
        // Sometimes there will be additional files in the directory that
        // appear to be multiple domains, but are actually all part of the
        // same domain.  An mcopen will test whether or not there are actually
        // multiple domains.
        char rootname[255];
        sprintf(rootname, "%s%.3d", root, 0); 
    
        Famid dbid;
        int rval;
345 346
        char rLetter[2] = "r";
        rval = mc_open (rootname, path, rLetter, &dbid);
hrchilds's avatar
hrchilds committed
347 348 349
        if (rval != OK)
            singleDomainName = true;
    }
hrchilds's avatar
hrchilds committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    
    if (singleDomainName)
        return 1;
    return lastdomain + 1;
}


// ***************************************************************************
//  Function: ReadDomain
//
//  Purpose:
//    Read domain specific information from a domain. Master process also
//    reads in global information.
//
//  Arguments:
//    dom       the domain
//    mi        the MiliInfo structure to fill.
//
//  Notes:
//    Will abort program if failure to open family or read variables.
//    Code based upon VisIt's avtMiliFileFormat.
//
hrchilds's avatar
hrchilds committed
372 373 374 375
//  Modifications:
//    Akira Haddox, Fri Jul 25 10:49:57 PDT 2003
//    Added variable dimensionality.
//
hrchilds's avatar
hrchilds committed
376 377
//    Mark C. Miller, Mon Jul 18 13:41:13 PDT 2005
//    Added logic to look for data in "param arrays"
hrchilds's avatar
hrchilds committed
378 379 380 381 382 383 384 385
// ***************************************************************************

void ReadDomain(int dom, MiliInfo &mi)
{
    //
    // Open the family.
    //
    char rootname[255];
386 387 388 389 390
    if ( ndomains > 999 ) 
         sprintf(rootname, "%s%.4d", root, dom); 
    else
         sprintf(rootname, "%s%.3d", root, dom); 

hrchilds's avatar
hrchilds committed
391 392
    Famid dbid;
    int rval;
393
    char rLetter[2] = "r";
hrchilds's avatar
hrchilds committed
394
    if (singleDomainName)
395
        rval = mc_open (root, path, rLetter, &dbid);
hrchilds's avatar
hrchilds committed
396
    else
397
        rval = mc_open (rootname, path, rLetter, &dbid);
hrchilds's avatar
hrchilds committed
398

hrchilds's avatar
hrchilds committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    if (rval != OK)
    {
        char err[255];
        sprintf(err, "Unable to open family %s for domain %d.",
                singleDomainName ? root : rootname, dom);
        FatalError(err);
    }
    
    //
    // Get the number of meshes.
    //
    int nmeshes;
    mc_query_family(dbid, QTY_MESHES, NULL, NULL, (void *) &nmeshes);

    mi.numMeshes = nmeshes;

    mi.highestMaterial.resize(nmeshes);
    mi.varType.resize(nmeshes);
    mi.varCentering.resize(nmeshes);
    mi.varNames.resize(nmeshes);
419 420
    mi.varDescr.resize(nmeshes);
    mi.varDims.resize(nmeshes);
hrchilds's avatar
hrchilds committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    
    int mesh_id;
    for (mesh_id = 0; mesh_id < nmeshes; ++mesh_id)
    {
        //
        // Read in the mesh connectivity to read in the materials.
        //
        char short_name[1024];
        char long_name[1024];

        const int n_elem_types = 8;
        static int elem_sclasses[n_elem_types] =
        {
            M_TRUSS, M_BEAM, M_TRI, M_QUAD, M_TET, M_PYRAMID, M_WEDGE, M_HEX
        };
        static int conn_count[n_elem_types] =
        {
            2, 3, 3, 4, 4, 5, 6, 8
        };

        vector < vector<int *> > mat_list;
        vector < vector<int> > list_size;
        list_size.resize(n_elem_types);
        mat_list.resize(n_elem_types);

        int i, j, k;
        for (i = 0 ; i < n_elem_types ; i++)
        {
            int args[2];
            args[0] = mesh_id;
            args[1] = elem_sclasses[i];
            int ngroups = 0;
            mc_query_family(dbid, QTY_CLASS_IN_SCLASS, (void*) args, NULL,
                            (void*) &ngroups);
            for (j = 0 ; j < ngroups ; j++)
            {
                int nelems;
                mc_get_class_info(dbid, mesh_id, elem_sclasses[i], j,
                                  short_name, long_name, &nelems);
                  
                int *conn = new int[nelems * conn_count[i]];
                int *mat = new int[nelems];
                int *part = new int[nelems];
                mc_load_conns(dbid, mesh_id, short_name, conn, mat, part);
                
                mat_list[i].push_back(mat);
                list_size[i].push_back(nelems);
                delete [] part;
                delete [] conn;
            }
        }

        //
        // Using mat_list and list_size, find the highest material number
        // for this mesh.
        // 
        int size = 0;
        for (i = 0; i < list_size.size(); ++i)
            for (j = 0; j < list_size[i].size(); ++j)
                size += list_size[i][j];
        
        int elem, gr;
        int highestMat = 0;
        for (elem = 0; elem < mat_list.size(); ++elem)
        {
            for (gr = 0; gr < mat_list[elem].size(); ++gr)
            {
                int *ml = mat_list[elem][gr];
                for (i = 0; i < list_size[elem][gr]; ++i)
                {
                    int mat = ml[i]; 
                    if (highestMat < mat)
                        highestMat = mat;
                }
            }
        }

        mi.highestMaterial[mesh_id] = highestMat;

        for (i = 0; i < mat_list.size(); ++i)
            for (j = 0; j < mat_list[i].size(); ++j)
                delete[] (mat_list[i][j]);

        //
        // End read materials
        //
        // Begin read variables.
        //

        int srec_qty = 0;
        rval = mc_query_family(dbid, QTY_SREC_FMTS, NULL, NULL,
                               (void*) &srec_qty); 

        for (i = 0 ; i < srec_qty ; i++)
        {
            rval = mc_query_family(dbid, SREC_MESH, (void *) &i, NULL,
                                   (void *) &mesh_id);
            if (rval != OK)
            {
                char err[255];
                sprintf(err, "Failed to read variables for domain %d: %s.",
                        dom, singleDomainName ? root : rootname);
                FatalError(err);
            }

            int substates = 0;
            rval = mc_query_family(dbid, QTY_SUBRECS, (void *) &i, NULL,
                                   (void *) &substates);

            for (j = 0 ; j < substates ; j++)
            {
                Subrecord sr;
                rval = mc_get_subrec_def(dbid, i, j, &sr);

            //
            // glob vars are associated with the entire mesh.
            // mat vars deal with materials.
            // These are not variables we need to visualize. Skip them.
            //
            
                if (strcmp(sr.class_name, "glob") == 0)
                    continue;
                if (strcmp(sr.class_name, "mat") == 0)
                    continue;

                for (k = 0 ; k < sr.qty_svars ; k++)
                {
                     State_variable sv;
                     mc_get_svar_def(dbid, sr.svar_names[k], &sv);

                     mi.varNames[mesh_id].push_back(sv.short_name);

553 554 555 556
                     for (int i=0;
                          i<strlen(sv.long_name);
                          i++ )
                          if (sv.long_name[i]==' ' )
557
                              sv.long_name[i]='_';
558 559 560

                     mi.varDescr[mesh_id].push_back(string(sv.long_name));

hrchilds's avatar
hrchilds committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
                     int cent;
                     if (strcmp(sr.class_name, "node") == 0)
                         cent = AVT_NODECENT;
                     else
                         cent = AVT_ZONECENT;
                     mi.varCentering[mesh_id].push_back(cent);
                     
                     int vartype;
                     if (sv.agg_type == SCALAR)
                         vartype = (AVT_SCALAR_VAR);
                     else if (sv.agg_type == VECTOR)
                         vartype = (AVT_VECTOR_VAR);
                     else
                         vartype = (AVT_UNKNOWN_TYPE);
                     mi.varType[mesh_id].push_back(vartype);
hrchilds's avatar
hrchilds committed
576 577

                    if (vartype == AVT_SCALAR_VAR)
578
                        mi.varDims[mesh_id].push_back(1);
hrchilds's avatar
hrchilds committed
579
                    else
580
                        mi.varDims[mesh_id].push_back(sv.vec_size);
hrchilds's avatar
hrchilds committed
581 582 583
                }
            }
        }
hrchilds's avatar
hrchilds committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

        //
        // Mili 1.09 defines some "param arrays" that may be read as mesh
        // variables. However, the interface to access them isn't as complete
        // as the interface for state vars. We don't know which mesh they
        // go with and we don't know their centering. Here, we use apriori
        // knowledge to specify centering and we just associate them
        // with every mesh.
        //
        static vector<int> paramVarTypes;
        static vector<string> paramVarNames;
        if (mesh_id == 0)
        {
            //
            // Ok, deal with known named "param arrays"
            //
            vector<string> knownpas;
            knownpas.push_back("Nodal Mass");
            knownpas.push_back("Nodal Volume");
            for (i = 0; i < knownpas.size(); i++)
            {
                //
                // Alas, Mili doesn't permit us to simply query for existence
                // of a param array. We need to actually attempt to read it and
                // if successful we will have done problem-sized I/O
                //
                void *values;
                if (mc_read_param_array(dbid, (char*) knownpas[i].c_str(), &values) == OK)
                {
                    free(values);
                    string paVarName = "params/" + knownpas[i];
                    paramVarNames.push_back(paVarName);
                    if (strstr(knownpas[i].c_str(), "Nodal") != 0)
                        paramVarTypes.push_back(AVT_NODECENT);
                    else
                        paramVarTypes.push_back(AVT_ZONECENT);
                }
            }
        }

        if (paramVarNames.size() > 0)
        {
            for (i = 0; i < paramVarNames.size(); i++)
            {
                mi.varNames[mesh_id].push_back(paramVarNames[i]);
629
                mi.varDescr[mesh_id].push_back(" ");
hrchilds's avatar
hrchilds committed
630 631
                mi.varCentering[mesh_id].push_back(paramVarTypes[i]);
                mi.varType[mesh_id].push_back(AVT_SCALAR_VAR);
632
                mi.varDims[mesh_id].push_back(1);
hrchilds's avatar
hrchilds committed
633 634
            }
        }
hrchilds's avatar
hrchilds committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    }

    //
    // Master process looks up a few other items.
    //
    if (myRank == 0)
    {
        mi.ndomains = ndomains;
        mc_query_family(dbid, QTY_STATES, NULL, NULL, &(mi.ntimesteps));
        mc_query_family(dbid, QTY_DIMENSIONS, NULL, NULL, &(mi.dimensions));
    }
    mc_close(dbid);
}

// ***************************************************************************
//  Function: ReceiveInfo (parallel only)
//
//  Purpose:
//    Receive compiled information from other processes. Called by master
//    process. See SendInfo for routine.
//
//  Arguments:
//    info      vector of MiliInfo to fill
//
hrchilds's avatar
hrchilds committed
659 660 661 662
//  Modifications:
//    Akira Haddox, Fri Jul 25 10:49:57 PDT 2003
//    Added variable dimensionality.
//
hrchilds's avatar
hrchilds committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
// ***************************************************************************

void ReceiveInfo(vector<MiliInfo> &info)
{
#ifdef PARALLEL
    int p;
    for (p = 1; p < numProcesses; ++p)
    {
        MPI_Status st;
        MiliInfo &mi = info[p];

        // Recv numMeshes
        int nm;
        MPI_Recv(&nm, 1, MPI_INT, p, 0, MPI_COMM_WORLD, &st);
        mi.numMeshes = nm;

        mi.highestMaterial.resize(nm);
        mi.varNames.resize(nm);
681
        mi.varDescr.resize(nm);
hrchilds's avatar
hrchilds committed
682 683
        mi.varType.resize(nm);
        mi.varCentering.resize(nm);
684
        mi.varDims.resize(nm);
hrchilds's avatar
hrchilds committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

        // Recv highest materials
        MPI_Recv(&(mi.highestMaterial[0]), nm, MPI_INT, p, 0, 
                                                        MPI_COMM_WORLD, &st);

        vector<int> numVars(nm);
        // Recv numVars
        MPI_Recv(&(numVars[0]), nm, MPI_INT, p, 0, MPI_COMM_WORLD, &st);

        int i;

        // Recv var types
        for (i = 0; i < nm; ++i)
        {
            mi.varType[i].resize(numVars[i]);
            MPI_Recv(&(mi.varType[i][0]), numVars[i], MPI_INT, p, 0,
                                                        MPI_COMM_WORLD, &st);
        }
        // Recv var centers
        for (i = 0; i < nm; ++i)
        {
            mi.varCentering[i].resize(numVars[i]);
            MPI_Recv(&(mi.varCentering[i][0]), numVars[i], MPI_INT, p, 0,
                                                        MPI_COMM_WORLD, &st);
        }

hrchilds's avatar
hrchilds committed
711 712 713
        // Recv var dimensions
        for (i = 0; i < nm; ++i)
        {
714 715
            mi.varDims[i].resize(numVars[i]);
            MPI_Recv(&(mi.varDims[i][0]), numVars[i], MPI_INT, p, 0,
hrchilds's avatar
hrchilds committed
716 717 718
                                                        MPI_COMM_WORLD, &st);
        }

hrchilds's avatar
hrchilds committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
        int maxLen;
        // Recv max_length
        MPI_Recv(&maxLen, 1, MPI_INT, p, 0, MPI_COMM_WORLD, &st);
        
        // Recv the var names
        char *str = new char[maxLen];
        for (i = 0; i < nm; ++i)
        {
            int j;
            for (j = 0; j < numVars[i]; ++j)
            {
                MPI_Recv(str, maxLen, MPI_CHAR, p, 0, MPI_COMM_WORLD, &st);
                mi.varNames[i].push_back(string(str));
            }
        }
        
        delete []str;
        
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
        // Recv max_length
        MPI_Recv(&maxLen, 1, MPI_INT, p, 0, MPI_COMM_WORLD, &st);

        // Recv the var descriptions (long names)
        char *descr = new char[maxLen];
        for (i = 0; i < nm; ++i)
        {
            int j;
            for (j = 0; j < numVars[i]; ++j)
            {
                MPI_Recv(descr, maxLen, MPI_CHAR, p, 0, MPI_COMM_WORLD, &st);
                mi.varDescr[i].push_back(string(descr));
            }
        }
        
        delete []descr;
hrchilds's avatar
hrchilds committed
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
    }
#endif
}

// ***************************************************************************
//  Function: SendInfo (parallel only)
//
//  Purpose:
//    Send compiled information to the master process.
//
//  Arguments:
//    mi        MillInfo to transfer
//
//  Send structure:
//      maxLen is the maximum length of a varName string.
//  
//      What                    Type        Count
//    ----------------------------------------------------- 
//      number of meshes        int         1
//      highest materials       int[]       number of Meshes
//      number of variables     int[]       number of Meshes
//      for each mesh:
//          variable types      int[]       number of Meshes
//      for each mesh:
//          variable centers    int[]       number of Meshes
//      for each mesh:
hrchilds's avatar
hrchilds committed
779 780
//          variable dimenion   int[]       number of Meshes
//      for each mesh:
hrchilds's avatar
hrchilds committed
781 782
//          variable names      char[]      maxLen
//
hrchilds's avatar
hrchilds committed
783 784 785 786
//  Modifications:
//    Akira Haddox, Fri Jul 25 10:49:57 PDT 2003
//    Added variable dimensionality.
//
hrchilds's avatar
hrchilds committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
// ***************************************************************************

void SendInfo(MiliInfo &mi)
{
#ifdef PARALLEL
    int nm = mi.numMeshes;
    
    // Send numMeshes
    MPI_Send(&nm, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); 

    // Send highest materials
    MPI_Send(&(mi.highestMaterial[0]), nm, MPI_INT, 0, 0, MPI_COMM_WORLD);

    vector<int> numVars(nm);
    int i;
    for (i = 0; i < nm; ++i)
    {
        numVars[i] = mi.varNames[i].size();
    }

    // Send number of variables
    MPI_Send(&(numVars[0]), nm, MPI_INT, 0, 0, MPI_COMM_WORLD);

    // Send the var types
    for (i = 0; i < nm; ++i)
        MPI_Send(&(mi.varType[i][0]), numVars[i], MPI_INT, 0, 0,
                                                        MPI_COMM_WORLD);
    
    // Send the var centers 
    for (i = 0; i < nm; ++i)
        MPI_Send(&(mi.varCentering[i][0]), numVars[i], MPI_INT, 0, 0,
                                                             MPI_COMM_WORLD);
hrchilds's avatar
hrchilds committed
819 820
    // Send the var dimension 
    for (i = 0; i < nm; ++i)
821
        MPI_Send(&(mi.varDims[i][0]), numVars[i], MPI_INT, 0, 0,
hrchilds's avatar
hrchilds committed
822
                                                             MPI_COMM_WORLD);
hrchilds's avatar
hrchilds committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    int maxLen = 0;
    for (i = 0; i < nm; ++i)
    {
        int j;
        for (j = 0; j < numVars[i]; ++j)
            if (mi.varNames[i][j].length() > maxLen)
                maxLen = mi.varNames[i][j].length();
    }
    ++maxLen;
    // Send the max_length
    MPI_Send(&maxLen, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
    
    // Send the var names
    char *str = new char[maxLen];
    for (i = 0; i < nm; ++i)
    {
        int j;
        for (j = 0; j < numVars[i]; ++j)
        {
            strcpy(str, mi.varNames[i][j].c_str());
            MPI_Send(str, maxLen, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
        }
    }

    delete[] str;
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873

    // Send the variable descriptions (long names)
    maxlen=0;
    for (i = 0; i < nm; ++i)
    {
        int j;
        for (j = 0; j < numVars[i]; ++j)
            if (mi.varDescr[i][j].length() > maxLen)
                maxLen = mi.varDescr[i][j].length();
    }
    ++maxLen;

    // Send the max_length
    MPI_Send(&maxLen, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
    char *descr = new char[maxLen];
    for (i = 0; i < nm; ++i)
    {
        int j;
        for (j = 0; j < numVars[i]; ++j)
        {
            strcpy(descr, mi.varDescr[i][j].c_str());
            MPI_Send(descr, maxLen, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
        }
    }

    delete[] descr;
hrchilds's avatar
hrchilds committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
#endif
}


// ***************************************************************************
//  Function: CompileInfo
//
//  Purpose:
//    Combine multi MiliInfo structures, removing redundant information.
//
//  Arguments:
//    info          the vector of MiliInfo structures to combine
//    result        the MiliInfo to fill
//
//  Notes:
//    The global dataset info is always taken from info[0], even though
//    it may be invalid. This ensures that when all the information is
//    finally compiled, the information will come through.
//
hrchilds's avatar
hrchilds committed
893 894 895 896
//  Modifications:
//    Akira Haddox, Fri Jul 25 10:49:57 PDT 2003
//    Added variable dimensionality.
//
hrchilds's avatar
hrchilds committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910
// ***************************************************************************

void CompileInfo(const vector<MiliInfo> &info, MiliInfo &result)
{
    // Always take from the first record the master process info
    result.ntimesteps = info[0].ntimesteps;
    result.ndomains = info[0].ndomains;
    result.dimensions = info[0].dimensions;
    int nm = info[0].numMeshes;
    result.numMeshes = nm;
    
    result.highestMaterial.resize(nm, -1);
    result.varType.resize(nm);
    result.varCentering.resize(nm);
911
    result.varDims.resize(nm);
hrchilds's avatar
hrchilds committed
912
    result.varNames.resize(nm);
913
    result.varDescr.resize(nm);
hrchilds's avatar
hrchilds committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927
   
    int i; 
    for (i = 0; i < info.size(); ++i)
    {
        const MiliInfo &mi = info[i]; 
        int m;
        for (m = 0; m < nm; ++m)
        {
            if (mi.highestMaterial[m] > result.highestMaterial[m])
                result.highestMaterial[m] = mi.highestMaterial[m];
            
            int v;
            for (v = 0; v < mi.varNames[m].size(); ++v)
            {
928 929 930
                const string &vn     = mi.varNames[m][v];
                const string &vdescr = mi.varDescr[m][v];

hrchilds's avatar
hrchilds committed
931 932 933
                if (VSSearch(result.varNames[m], vn) == -1)
                {
                    result.varNames[m].push_back(vn);
934
                    result.varDescr[m].push_back(vdescr);
hrchilds's avatar
hrchilds committed
935 936
                    result.varType[m].push_back(mi.varType[m][v]);
                    result.varCentering[m].push_back(mi.varCentering[m][v]);
937
                    result.varDims[m].push_back(mi.varDims[m][v]);
hrchilds's avatar
hrchilds committed
938 939 940 941 942 943
                } 
            }
        }
    }
}

944 945
#define vp(a) if (verbose) o << a

hrchilds's avatar
hrchilds committed
946 947 948 949 950 951 952 953 954 955 956
// ***************************************************************************
//  Function: PrintInfo
//
//  Purpose:
//    Write a MiliInfo structure to a stream.
//
//  Arguments:
//    o         the stream
//    mi        the MiliInfo structure
//    verbose   if true, makes it human readable (unsuitable for .mili file)
//
hrchilds's avatar
hrchilds committed
957 958 959 960
//  Modifications:
//    Akira Haddox, Fri Jul 25 10:49:57 PDT 2003
//    Added variable dimensionality.
//
hrchilds's avatar
hrchilds committed
961
// ***************************************************************************
962
void PrintInfo(ostream &o, const MiliInfo &mi, bool miliFile, bool verbose)
hrchilds's avatar
hrchilds committed
963
{
964 965 966
    if (!miliFile)
        vp("MiliInfo: \n----------------------\n");
    o << "Path:\t\t\t" << currentPath << endl;
hrchilds's avatar
hrchilds committed
967 968 969 970 971 972
    vp("Domains:\t\t");
    o << mi.ndomains << endl;
    vp("Timesteps:\t\t");
    o << mi.ntimesteps << endl;
    vp("Dimensions:\t\t");
    o << mi.dimensions << endl;
973
    vp("Number_of_Meshes:\t");
hrchilds's avatar
hrchilds committed
974 975 976 977 978 979
    o << mi.numMeshes << endl;
    o << endl;

    int mesh;
    for (mesh = 0; mesh < mi.numMeshes; ++mesh)
    {
980 981
        vp("Mesh: " << mesh+1 << endl);
        vp("Number_of_Materials: ");
hrchilds's avatar
hrchilds committed
982 983
        o << mi.highestMaterial[mesh] + 1 << endl;
        int nVar = mi.varNames[mesh].size();
984
        vp("Number_of_Variables: " );
hrchilds's avatar
hrchilds committed
985
        o << nVar << endl;
986
        vp("*\tType\tCenter\tDims\tName \t\t\tLong Name" << endl);
hrchilds's avatar
hrchilds committed
987
        int var;
988 989 990 991

        for (var = 0; 
             var < mi.varNames[mesh].size(); 
             ++var)
hrchilds's avatar
hrchilds committed
992
        {
993 994
 
           o << '\t' << mi.varType[mesh][var]  << '\t'
hrchilds's avatar
hrchilds committed
995
                      << mi.varCentering[mesh][var] << '\t'
996 997 998
                      << mi.varDims[mesh][var] << '\t' << setw(16) << setiosflags(ios::left)
                      << mi.varNames[mesh][var] << '\t'
                      << mi.varDescr[mesh][var] << endl;
hrchilds's avatar
hrchilds committed
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        }
        o << endl;
    }
}

// ***************************************************************************
//  Function: VSSearch
//
//  Purpose:
//    Search a vector of strings.
//
//  Arguments:
//    v     the vector
//    s     the string to search for
//
//  Returns:
//    The index of s, or -1 if not found.
//
// ***************************************************************************
// 
int VSSearch(const vector<string> &v, const string &s)
{
    int i;
    for (i = 0; i < v.size(); ++i)
        if (v[i] == s)
            return i;
    return -1;
}

// ***************************************************************************
//  Function: FatalError
//
//  Purpose:
//    Prints an error message, and aborts program. The message is compacted
//    into one print in case multiple processes call this.
//
//  Arguments:
//    s         The reason for the error
//
// ***************************************************************************

void FatalError(const string &s)
{
    char error[1024];
    sprintf(error, "** Fatal error: %s Aborting program...\n", s.c_str());
    cerr << error;

#ifdef PARALLEL
    MPI_Abort(MPI_COMM_WORLD, -1);
#endif
    exit(-1);
}

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
// ***************************************************************************
//  Function: GetGlobalData
//
//  Purpose:
//    Reads some global fields from the domain 0 Mili file.
//
//  Arguments: None
//
//  Notes:
//    Will abort program if failure to open family or read variables.
//
//  Modifications:
//
// ***************************************************************************

void GetGlobalData( MiliInfo &mi )
{
    //
    // Open the family.
    //
    int i,j,k;
    int dom = 0;
    char short_name[1024];
    char long_name[1024];

    char rootname[512];
    if ( ndomains > 999 )
         sprintf(rootname, "%s%.4d", root, dom);
    else
         sprintf(rootname, "%s%.3d", root, dom);         
    
    Famid dbid;
    int rval;
1085
    char rLetter[2] = "r";
1086
    if (singleDomainName)
1087
        rval = mc_open (root, path, rLetter, &dbid);
1088
    else
1089
        rval = mc_open (rootname, path, rLetter, &dbid);
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

    mi.ndomains = ndomains;
    mc_query_family(dbid, QTY_STATES, NULL, NULL, &(mi.ntimesteps));
    mc_query_family(dbid, QTY_DIMENSIONS, NULL, NULL, &(mi.dimensions));

    // Get the variable long names if we dont already have them
    int srec_qty=0;
    rval = mc_query_family(dbid, QTY_SREC_FMTS, NULL, NULL,
                           (void*) &srec_qty); 

    for (int i = 0; 
         i < srec_qty;
         i++) {

        int mesh_id=0;
        rval = mc_query_family(dbid, SREC_MESH, (void *) &i, NULL,
                               (void *) &mesh_id);
        
        
        if (mi.varDescr[mesh_id].size()>0 )
            continue;

        int srec_qty = 0;
        int substates = 0;
        rval = mc_query_family(dbid, QTY_SUBRECS, (void *) &i, NULL,
                               (void *) &substates);
        for (int j = 0;
             j < substates;
             j++) {
1119
             Subrecord sr;
1120 1121 1122 1123
             rval = mc_get_subrec_def(dbid, i, j, &sr);
             for (int k = 0; 
                  k < sr.qty_svars;
                  k++) {
1124
                  State_variable sv;
1125 1126 1127 1128 1129 1130 1131
                  mc_get_svar_def(dbid, sr.svar_names[k], &sv);
                  for (int i=0;
                       i<strlen(sv.long_name);
                       i++ )
                       if (sv.long_name[i]==' ' )
                           sv.long_name[i]='_';

1132
                  mi.varDescr[mesh_id].push_back(string(sv.long_name));
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
              }
          }
      }

    mc_close(dbid);
}

// ***************************************************************************
//  Function: readMiliFileLine
//
//  Purpose:
//   
//
//  Arguments: in - input stream
//             commentSymbol - optional comment string
//             keyword - if set, then return line beginning with this string
//             lineN - return line number N
//             eof - return eof state (true | false)
//           
//  Notes:
//
//  Modifications:
//
// ****************************************************************************
char *readMiliFileLine(ifstream &in, const char *commentSymbol, const char *kw,
                       int lineN, bool *lineReturned, bool *eof)
{
  char *oneLine, dummy[512];
  int i=0;
  int maxLen=0;
  int lineNumber=0;

  bool lineFound=false, commentFound=false;

  if (lineN>0)
      in.seekg(0); // Rewind file
  
  *lineReturned=false;
  *eof=false;

  while (!lineFound) {
         in.getline(dummy, 512 );

         if (in.eof()) {
             *eof=true;
             *lineReturned=false;
             return NULL;
         }

         if (strlen(dummy)==0)
             continue;

         string field1;
         std::stringstream ss(dummy);
         field1="";
         ss >> field1;

         // Check for a comment line
         if (commentSymbol)
             if (strlen(commentSymbol)>0) {
                 if (strlen(commentSymbol) <= field1.length())
                     maxLen = strlen(commentSymbol);
                 else
                     maxLen = field1.length();

                 commentFound=true;
                 int charMatch=0;
                 for (int i=0;
1201
                      i<maxLen;
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
                      i++) {
                 if (field1[i]!=commentSymbol[i]) {
                     commentFound=false;
                     break;
                 }
                 else
                     charMatch++;
                 if (  charMatch!=strlen(commentSymbol) )
                       commentFound=false;
                 }
             }

         if (commentFound)
             continue;

         char kwUpper[256];
         if (kw)
             if (strlen(kw)>0) {
                 /* Convert fields to upper case */ 
                 strcpy(kwUpper, kw);
                 for (int i=0; 
                      i<strlen(kw);
                      i++)
                      kwUpper[i] = toupper(kw[i]);
             }
         
         for (int i = 0; 
              i < field1.length(); 
              i++)
              field1[i]=toupper(field1[i]);
         
         if ( !strcmp(field1.c_str(), kwUpper )) {
              lineFound=true;
              break;
         }

         if ( lineN>0 ) {
           if (lineNumber==lineN) {
               if (in.eof())
                   *eof=true;
               lineFound=true;
           }
         }

         if (lineN<=0 && strlen(kw)==0)
             lineFound=true;
  }
  if (lineFound) {
      oneLine = new char[(strlen(dummy)+2)];
      strcpy(oneLine, dummy);
      *lineReturned=true;
      return oneLine;
  }
  else {
      *lineReturned=false;
      return NULL;
  }
}

// ***************************************************************************
//  Function: loadMiliFile
//
//  Purpose:  Read the Mili Metadata file - old and new formats
//   
//
//  Arguments: filename
//             
//
//  Notes:
//
//  Modifications:
//
// ***************************************************************************

void loadMiliFile(char *filename, MiliInfo &mi)
{
   ifstream in;
   bool newFormat = false;
   int i=0, meshid=0, varid=0;
   int nmeshes=1, nmaterials=1;
   int varInt;

   int type, centering, dims;
   string name, descr;
   char nameC[256], descrC[256];

   char path[512], dummy[512], *oneLine;
1289
   bool eof, lineReturned=false;
1290 1291 1292 1293 1294 1295 1296

   in.open(filename, ios::in);
   oneLine = readMiliFileLine(in, "*", "Path:", 0, &lineReturned, &eof);
   
   if (lineReturned) {
       newFormat=true;
       sscanf(oneLine,"%*s %s", path);
1297
       free(oneLine);
1298 1299 1300 1301 1302 1303 1304 1305
   }
   else {
       in.clear();
       in.seekg(0);

   }
   if ( newFormat ) {
        oneLine = readMiliFileLine(in, "*", "Domains:", 0, &lineReturned, &eof);
1306 1307 1308 1309
        if ( lineReturned ) {
             sscanf(oneLine,"%*s %d", &mi.ndomains);    // Num Domains
             free(oneLine);
        }
1310 1311

        oneLine = readMiliFileLine(in, "*", "Timesteps:", 0, &lineReturned, &eof);
1312 1313 1314 1315
        if ( lineReturned ) {
             sscanf(oneLine,"%*s %d", &mi.ntimesteps); // Num Timesteps
             free(oneLine);
        }
1316 1317

        oneLine = readMiliFileLine(in, "*", "Dimensions:", 0, &lineReturned, &eof);
1318 1319 1320 1321
        if ( lineReturned ) {
             sscanf(oneLine,"%*s %d", &mi.dimensions); // Num Dimensions
             free(oneLine);
        }
1322
        oneLine = readMiliFileLine(in, "*", "Number_of_Meshes:", 0, &lineReturned, &eof);
1323 1324 1325 1326
        if ( lineReturned ) {
             sscanf(oneLine,"%*s %d", &mi.numMeshes); // Num Meshes
             free(oneLine);
        }
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
   }
   else {
        in >> mi.ndomains >> mi.ntimesteps >>  mi.dimensions >> mi.numMeshes;
   }

   nmeshes = mi.numMeshes;
   
   mi.numMats.resize(nmeshes);
   mi.numVars.resize(nmeshes);
   mi.highestMaterial.resize(nmeshes);
   mi.varType.resize(nmeshes);
   mi.varCentering.resize(nmeshes);
   mi.varNames.resize(nmeshes);
   mi.varDescr.resize(nmeshes);
   mi.varDims.resize(nmeshes);
   
   for ( meshid=0;
         meshid<mi.numMeshes;
         meshid++ ) {

         if ( newFormat ) {
              oneLine = readMiliFileLine(in, "*", "Mesh:", 0, &lineReturned, &eof);
1349 1350
              if ( lineReturned )
                   free(oneLine);
1351 1352

              oneLine = readMiliFileLine(in, "*", "Number_of_Materials:", 0, &lineReturned, &eof);
1353 1354 1355 1356 1357
              if ( lineReturned ) {
                   sscanf(oneLine,"%*s %d", &mi.numMats[meshid]); // Num Mats
                   mi.highestMaterial[meshid] = mi.numMats[meshid]-1;
                   free(oneLine);
              }
1358 1359

              oneLine = readMiliFileLine(in, "*", "Number_of_Variables:", 0, &lineReturned, &eof);
1360 1361 1362 1363
              if ( lineReturned ) {
                   sscanf(oneLine,"%*s %d", &mi.numVars[meshid]); // Num Vars
                   free(oneLine);
              }
1364 1365 1366 1367 1368 1369

              for ( varid=0; 
                    varid<mi.numVars[meshid];
                    varid++ ) {
                    oneLine = readMiliFileLine(in, "*", "", 0, &lineReturned, &eof);

1370 1371 1372
                    // Replace spaces in var names with special character so we can parse as a
                    // single name.
                    if ( strlen(oneLine)>10 )
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
                         for ( int i=10;
                               i<strlen(oneLine)-1;
                               i++ ) if ( oneLine[i]==' ' && oneLine[i-1]!=' ' && oneLine[i+1]!=' ' )
                                          oneLine[i]='~';

                    if (lineReturned) {
                        descrC[0]='\0';
                        sscanf(oneLine,"%d %d %d %s %s", &type, &centering, &dims, nameC, descrC); 
                        free(oneLine);
                        
                        mi.varType[meshid].push_back(type);
                        mi.varCentering[meshid].push_back(centering);
                        mi.varDims[meshid].push_back(dims);

                        for ( int i=0;
                              i<strlen(nameC);
                              i++ ) if ( nameC[i]=='~' )
                                         nameC[i]=' ';
                        mi.varNames[meshid].push_back(string(nameC)); 

                        for ( int i=0;
                              i<strlen(descrC);
                              i++ ) if ( descrC[i]=='~' )
                                         descrC[i]=' ';
                        mi.varDescr[meshid].push_back(string(descrC));
                    }
              }
         }
         else {
1402
              in >> mi.numMats[meshid] >> mi.numVars[meshid];  // Num Mats + Num Var    
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
              for ( varid=0; 
                    varid<mi.numVars[meshid];
                    varid++ ) {
                    in >> type >> centering >> dims >> name;

                    mi.varType[meshid].push_back(type);
                    mi.varCentering[meshid].push_back(centering);
                    mi.varDims[meshid].push_back(dims);
                    mi.varNames[meshid].push_back(name);
              }
         }
   }

   // Get the Partfile name if it exists
   if (!dynapartFile) {
       oneLine = readMiliFileLine(in, "*", "", 0, &lineReturned, &eof);
       if (lineReturned) {
1420
           dynapartFile = new char[strlen(oneLine)+2];
1421
           strcpy(dynapartFile, oneLine);
1422
           free(oneLine);
1423 1424 1425 1426 1427 1428
       }
   }

   in.close();
}

hrchilds's avatar
hrchilds committed
1429 1430 1431 1432 1433 1434
// ***************************************************************************
//  Main
//
//  Arguments:
//      argv[1]     The root name of the dataset.
//
hrchilds's avatar
hrchilds committed
1435 1436 1437 1438
//  Modifications:
//    Akira Haddox, Tue Jul 22 08:12:57 PDT 2003
//    Added help on bad number of arguments.  
//
hrchilds's avatar
hrchilds committed
1439 1440 1441
//    Akira Haddox, Fri Jul 25 11:21:38 PDT 2003
//    Added check to find rootname, ignoring hyphen-ed arguments.
//
hrchilds's avatar
hrchilds committed
1442 1443 1444
//    Akira Haddox, Mon Aug 18 15:19:21 PDT 2003
//    Added -dynapart option.
//
1445 1446 1447
//    Eric Brugger, Fri Oct  9 16:32:26 PDT 2015
//    Added code to ignore -forceversion.
//
hrchilds's avatar
hrchilds committed
1448 1449 1450 1451
// ***************************************************************************

int main(int argc, char* argv[])
{
1452

hrchilds's avatar
hrchilds committed
1453 1454 1455 1456 1457 1458 1459
#ifdef PARALLEL
    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
    MPI_Comm_size(MPI_COMM_WORLD, &numProcesses);
#endif 

hrchilds's avatar
hrchilds committed
1460 1461
    char * argument = NULL;
    int argi;
1462

1463
    printf("\nRunning Makemili Version %s. Created on: %s\n", VERSION_STRING, DATE_STRING);
1464 1465 1466 1467

    for (argi = 1; 
         argi < argc; 
         ++argi)
hrchilds's avatar
hrchilds committed
1468
    {
1469 1470 1471 1472
        if (!strcmp(argv[argi], "-c") || !strcmp(argv[argi], "-create"))
        {
            createMode = true;
        }
1473
        else if (!strcmp(argv[argi], "-v") || !strcmp(argv[argi], "-verbose"))
1474 1475 1476
        {
            verboseMode = true;
        }
1477 1478 1479 1480 1481
        else if (!strcmp(argv[argi], "-forceversion"))
        {
            ++argi;
        }
        else if (!strcmp(argv[argi], "-dynapart"))
hrchilds's avatar
hrchilds committed
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
        {
            // Check the next argument for bad usage.
            if (argi + 1 >= argc || argv[argi + 1] == NULL
                                 || argv[argi + 1][0] == '-')
            {
                argument = NULL;
                break;
            }
            dynapartFile = argv[++argi];
        }
        else if (argv[argi][0] != '-' && !argument)
hrchilds's avatar
hrchilds committed
1493 1494 1495
        {
            argument = argv[argi];
        }
hrchilds's avatar
hrchilds committed
1496
    }
hrchilds's avatar
hrchilds committed
1497 1498

    if (argument == NULL)
hrchilds's avatar
hrchilds committed
1499 1500 1501 1502 1503
    {
        if (myRank != 0)
            exit(-1);
        
        cout <<
1504

hrchilds's avatar
hrchilds committed
1505
"makemili help:\n"
1506

hrchilds's avatar
hrchilds committed
1507
"  Req. Argument:   the root name of a single or multi domained Mili dataset.\n"
hrchilds's avatar
hrchilds committed
1508 1509
"                   The path to the dataset may be included in the name.\n"
"                   The output .mili file will be written in the same\n"
hrchilds's avatar
hrchilds committed
1510
"                   directory as the dataset.\n\n"
1511 1512 1513
"\n"
"  Opt. Argument:   -dynapart <DynaPart partition filename>\n" 
"                   -c Create new .mili file - do not update if file exists." << endl;
hrchilds's avatar
hrchilds committed
1514 1515 1516 1517
 
        exit(-1);
    }

hrchilds's avatar
hrchilds committed
1518
    DetermineRootAndPath(argument);
hrchilds's avatar
hrchilds committed
1519 1520 1521 1522 1523 1524 1525
    
    //
    // Master process needs to determine how many domains there are.
    //
    if (myRank == 0)
    {
        ndomains = GetNumDomains();
1526
        cout << "\nGeneral: \n----------------------\n";
1527
        cout << "Root: " << root << " \tPath: " << currentPath << endl;
hrchilds's avatar
hrchilds committed
1528 1529
        if (dynapartFile)
            cout << "DynaPart file option: " << dynapartFile << endl;
hrchilds's avatar
hrchilds committed
1530 1531 1532 1533 1534 1535 1536 1537 1538
        if (ndomains <= 0)
        {
            FatalError("Unable to find matching files.");
        }
        else
        {
            cout << "Domains found: " << ndomains;
            if (singleDomainName)
            {
hrchilds's avatar
hrchilds committed
1539
                cout << " (single family: " << root << ")";
hrchilds's avatar
hrchilds committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
            }
            cout << endl << endl;
        }
    }
    
#ifdef PARALLEL
    //
    // Master process needs to tell children how many domains there are.
    //
    MPI_Bcast((void *)&ndomains, 1, MPI_INT, 0, MPI_COMM_WORLD);
#endif

    //
    // Now, find how many domains I am responsible for.
    //
    int startDomain;
    int endDomain;

    //
    // Special cases: If processes >= ndomains.
    // 
    if (numProcesses >= ndomains)
    {
#ifdef PARALLEL
        if (myRank == 0 && numProcesses > ndomains)
        {
            cout << "** More processes than domains. Restricting to "
                 << ndomains <<
                 (ndomains == 1 ? " process." : " processes.") << endl << endl;
        }
#endif
        if (myRank >= ndomains)
        {
#ifdef PARALLEL
            MPI_Finalize();
#endif
            return 0;
        }
        
        startDomain = myRank;
1580
        endDomain   = myRank;
hrchilds's avatar
hrchilds committed
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
        
        //
        // At this point, the number of processes may have changed.
        //
        numProcesses = ndomains;
    }
    else 
    {
        startDomain = (ndomains) * myRank / numProcesses;
        endDomain = (ndomains) * (myRank + 1) / numProcesses - 1; 
    }

    //
    // Make sure we always take care of the last domain.
    //
    if (myRank + 1 == numProcesses)
    {
        endDomain = ndomains - 1;
    }
    
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    // Check if a .mili file exists to update
    struct stat stFileInfo;
    int status=0;
    strcpy( infoFilename, root );
    strcat( infoFilename, ".mili" );
    status = stat(infoFilename, &stFileInfo);
    if(status == 0) 
       updateMode = true;
    else
       updateMode = false;
hrchilds's avatar
hrchilds committed
1611
    
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    if ( updateMode && !createMode ) 
    {
         ofstream out;
         char tempFilename[512];
         char oneLine[512];
         int  status=0;
         MiliInfo compiledInfo;

         loadMiliFile( infoFilename, compiledInfo );
         GetGlobalData( compiledInfo );

         strcpy( tempFilename, infoFilename );
         strcat( tempFilename, ".old" );
         status = rename( infoFilename, tempFilename );
         
         out.open( infoFilename, ios::out );
         PrintInfo(out, compiledInfo, false, true); 

1630
         if (dynapartFile)
1631 1632 1633 1634
             out << dynapartFile << endl;

         out.close();

1635
         PrintInfo(cout, compiledInfo, false, true);     
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
         if (dynapartFile)
             cout << "DynaPart file: " << dynapartFile << endl;
         cout << "File " << infoFilename << " successfully written." << endl; 

#ifdef PARALLEL
         MPI_Finalize();
#endif
         exit(1);
    }

hrchilds's avatar
hrchilds committed
1646
    int i;
1647 1648 1649 1650
    vector<MiliInfo> info(endDomain - startDomain + 1);
    for (i = startDomain; 
         i <= endDomain; 
         ++i)
hrchilds's avatar
hrchilds committed
1651
    {
1652
         ReadDomain(i, info[i - startDomain]);
hrchilds's avatar
hrchilds committed
1653 1654 1655 1656 1657
    }
    MiliInfo compiledInfo;
    CompileInfo(info, compiledInfo);
    
#ifdef PARALLEL
1658
    if (myRank == 0) 
hrchilds's avatar
hrchilds committed
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    {
        vector<MiliInfo> gatheredInfo(numProcesses);
        gatheredInfo[0] = compiledInfo;
        // Receive domain info from all other processes
        ReceiveInfo(gatheredInfo);
        CompileInfo(gatheredInfo, compiledInfo);
    }
    else
    {
        SendInfo(compiledInfo);
    } 
#endif

    if (myRank == 0)
    {
1674
        PrintInfo(cout, compiledInfo, false, true);
hrchilds's avatar
hrchilds committed
1675 1676
        if (dynapartFile)
            cout << "DynaPart file: " << dynapartFile << endl;
hrchilds's avatar
hrchilds committed
1677 1678 1679 1680 1681 1682 1683 1684 1685

        char outfname[255];
        sprintf(outfname, "%s/%s.mili", path, root);
        ofstream out;
        out.open(outfname);
        if (out.fail())
            cerr << "** Error! Could not write to file: " << outfname << endl; 
        else
        {
1686 1687
             PrintInfo(out, compiledInfo, true, true);

hrchilds's avatar
hrchilds committed
1688 1689 1690
            // Write out the dynapart file if we have one
            if (dynapartFile)
                out << dynapartFile << endl;
hrchilds's avatar
hrchilds committed
1691 1692 1693 1694 1695 1696 1697 1698
            cout << "File " << outfname << " successfully written." << endl; 
        }
        out.close();
    }

#ifdef PARALLEL
    MPI_Finalize();
#endif
1699
    exit(1);
hrchilds's avatar
hrchilds committed
1700
}
1701