SessionReader.cpp 80.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
///////////////////////////////////////////////////////////////////////////////
//
// File SessionReader.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Session reader
//
///////////////////////////////////////////////////////////////////////////////

#ifndef TIXML_USE_STL
#define TIXML_USE_STL
#endif

40 41
#include <LibUtilities/BasicUtils/SessionReader.h>

42
#include <iostream>
43
#include <fstream>
44 45 46
#include <string>
using namespace std;

47 48 49
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
50 51 52
#include <boost/algorithm/string.hpp>
#include <tinyxml/tinyxml.h>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
53 54
#include <LibUtilities/BasicUtils/Equation.h>
#include <LibUtilities/Memory/NekMemoryManager.hpp>
55
#include <LibUtilities/BasicUtils/MeshPartition.h>
56
#include <LibUtilities/BasicUtils/ParseUtils.hpp>
57
#include <LibUtilities/BasicUtils/FileSystem.h>
58

59
#include <boost/program_options.hpp>
60
#include <boost/format.hpp>
61

62
namespace po = boost::program_options;
63
namespace io = boost::iostreams;
64

65 66 67 68
namespace Nektar
{
    namespace LibUtilities
    {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        /**
         * @class SessionReader
         *
         * This class provides an interface to Nektar++-specific content in a
         * supplied XML document. It also initialises a Nektar++ session
         * including setting up communication for parallel execution and where
         * necessary partitioning the supplied mesh for running across multiple
         * processes.
         *
         * A session should be initialised at the beginning of a user's
         * application by passing the command-line arguments. This not only
         * allows the SessionReader to extract the name of the XML document to
         * load containing Nektar++ session information, but also supplies the
         * MPI arguments necessary for setting up parallel communication. The
         * SessionReader should be initialised using the #CreateInstance
         * function:
         * @code
         * LibUtilities::SessionReaderSharedPtr vSession
         *          = LibUtilities::SessionReader::CreateInstance(argc, argv);
         * @endcode
         * The instance \c vSession can now be passed to other key Nektar++
         * components during their construction.
         * @note At the end of the user application, it is important to call the
         * #Finalise routine in order to finalise any MPI communication and
         * correctly free resources.
         *
         * The SessionReader class provides streamlined, validated access to
         * session parameters, solver information and functions defined within a
         * Nektar++ XML document. The available routines and their usage is
         * documented below.
         *
         * In the case of solver information properties, the classes to which
         * these parameters are pertinent may register with the SessionReader
         * class the set of valid values for a given property. Such values may
         * also be associated with an enumeration value for more transparent use
         * of the property values in code.
         */

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        /**
         * This map of maps stores the list of valid string values for a number
         * of solver information parameters. The top level map connects
         * different parameter names to their list of possible values. The list
         * of possible values is also a map, mapping a valid string to a
         * corresponding enum value.
         *
         * This list is populated through the #RegisterEnumValue static member
         * function which is called statically from various classes to register
         * the valid values for solver info parameters associated with them. The
         * map is therefore fully populated before the SessionReader class is
         * instantiated and a file is read in and parsed.
         */
        EnumMapList SessionReader::m_enums;


        /**
         * List of default values for solver information parameters to be used
         * in the case of them not being provided.
         *
         * This list is populated through the #RegisterDefaultSolverInfo static
         * member variable which is called statically from various classes to
         * register the default value for a given parameter.
         */
        SolverInfoMap SessionReader::m_solverInfoDefaults;


134 135 136 137 138 139 140 141 142 143 144
        /**
         * List of values for GlobalSysSoln parameters to be used to override
         * details given in SolverInfo
         *
         * This list is populated by ReadGlobalSysSoln if the
         * GLOBALSYSSOLNINFO section is defined in the input file.
         * This List allows for details to define for the Global Sys
         * solver for each variable. 
         */
        GloSysSolnInfoList SessionReader::m_gloSysSolnList;

145 146 147 148 149 150 151 152 153 154 155
        /**
         * Lists the possible command-line argument which can be specified for
         * this executable.
         *
         * This list is populated through the #RegisterCmdLineArgument static
         * member function which is called statically from various classes to
         * register command-line arguments they need.
         */
        CmdLineArgMap SessionReader::m_cmdLineArguments;


156 157 158 159 160 161 162 163
        /**
         * This constructor parses the command-line arguments given to the user
         * application to set up any MPI communication, read supplied XML
         * session files, and partition meshes where necessary.
         *
         * @param   argc        Number of command-line arguments
         * @param   argv        Array of command-line arguments
         */
164 165
        SessionReader::SessionReader(int argc, char *argv[])
        {
Chris Cantwell's avatar
Chris Cantwell committed
166
            m_xmlDoc    = 0;
167
            m_filenames = ParseCommandLineArguments(argc, argv);
168

169
            ASSERTL0(m_filenames.size() > 0, "No session file(s) given.");
170

171
            m_filename    = m_filenames[0];
172
            m_sessionName = m_filename.substr(0, m_filename.find_last_of('.'));
173 174 175 176 177 178
            if (m_filename.size() > 3 &&
                m_filename.substr(m_filename.size() - 3, 3) == ".gz")
            {
                m_sessionName =
                    m_sessionName.substr(0, m_sessionName.find_last_of('.'));
            }
179

180
            // Create communicator
181
            CreateComm(argc, argv);
182 183 184 185 186 187 188 189

            // If running in parallel change the default global sys solution
            // type.
            if (m_comm->GetSize() > 1)
            {
                m_solverInfoDefaults["GLOBALSYSSOLN"] = 
                    "IterativeStaticCond";
            }
190 191 192
        }


193 194 195
        /**
         *
         */
196 197 198 199 200
        SessionReader::SessionReader(
            int                             argc, 
            char                           *argv[], 
            const std::vector<std::string> &pFilenames, 
            const CommSharedPtr            &pComm)
201 202 203
        {
            ASSERTL0(pFilenames.size() > 0, "No filenames specified.");

204
            ParseCommandLineArguments(argc, argv);
Chris Cantwell's avatar
Chris Cantwell committed
205
            m_xmlDoc      = 0;
206
            m_filenames   = pFilenames;
207

208
            m_filename    = pFilenames[0];
209
            m_sessionName = m_filename.substr(0, m_filename.find_last_of('.'));
210 211 212 213 214 215
            if (m_filename.size() > 3 &&
                m_filename.substr(m_filename.size() - 3, 3) == ".gz")
            {
                m_sessionName =
                    m_sessionName.substr(0, m_sessionName.find_last_of('.'));
            }
216

217
            // Create communicator
218 219
            if (!pComm.get())
            {
220
                CreateComm(argc, argv);
221 222 223 224
            }
            else
            {
                m_comm = pComm;
225 226 227 228 229 230

                if (m_comm->GetSize() > 1)
                {
                    m_solverInfoDefaults["GLOBALSYSSOLN"] = 
                        "IterativeStaticCond";
                }
231
            }
232 233 234 235 236 237 238 239

            // If running in parallel change the default global sys solution
            // type.
            if (m_comm->GetSize() > 1)
            {
                m_solverInfoDefaults["GLOBALSYSSOLN"] = 
                    "IterativeStaticCond";
            }
240 241 242
        }


243 244 245
        /**
         *
         */
246 247
        SessionReader::~SessionReader()
        {
248
            delete m_xmlDoc;
249 250
        }

251 252 253 254 255 256 257

        /**
         * Performs the main initialisation of the object. The XML file provided
         * on the command-line is loaded and any mesh partitioning is done. The
         * resulting process-specific XML file (containing the process's
         * geometry partition) is then reloaded and parsed.
         */
258 259
        void SessionReader::InitSession()
        {
260 261 262
            // Split up the communicator
            PartitionComm();

263 264 265
            // Partition mesh
            PartitionMesh();

266 267
            // Parse the XML data in #m_xmlDoc
            ParseDocument();
268 269 270 271

            // Override SOLVERINFO and parameters with any specified on the
            // command line.
            CmdLineOverride();
272 273
        }

274

275
        /**
276 277
         * @brief Parses the command-line arguments for known options and
         * filenames.
278
         */
279 280
        std::vector<std::string> SessionReader::ParseCommandLineArguments(
            int argc, char *argv[])
281 282 283 284
        {
            // List the publically visible options (listed using --help)
            po::options_description desc("Allowed options");
            desc.add_options()
285 286 287 288 289 290
                ("verbose,v",    "be verbose")
                ("help,h",       "print this help message")
                ("solverinfo,I", po::value<vector<std::string> >(), 
                                 "override a SOLVERINFO property")
                ("parameter,P",  po::value<vector<std::string> >(),
                                 "override a parameter")
291
                ("shared-filesystem,s", "Using shared filesystem.")
292 293 294 295 296 297
                ("npx",          po::value<int>(),
                                 "number of procs in X-dir")
                ("npy",          po::value<int>(),
                                 "number of procs in Y-dir")
                ("npz",          po::value<int>(),
                                 "number of procs in Z-dir")
298
                ("part-info",    "Output partition information")
299
            ;
300
            
301
            CmdLineArgMap::const_iterator cmdIt;
302 303
            for (cmdIt  = m_cmdLineArguments.begin(); 
                 cmdIt != m_cmdLineArguments.end(); ++cmdIt)
304 305 306 307 308 309
            {
                std::string names = cmdIt->first;
                if (cmdIt->second.shortName != "")
                {
                    names += "," + cmdIt->second.shortName;
                }
310 311 312 313 314 315 316 317 318 319 320 321 322
                if (cmdIt->second.isFlag)
                {
                    desc.add_options()
                        (names.c_str(), cmdIt->second.description.c_str())
                    ;
                }
                else
                {
                    desc.add_options()
                        (names.c_str(), po::value<std::string>(),
                         cmdIt->second.description.c_str())
                    ;
                }
323
            }
324 325 326 327 328

            // List hidden options (e.g. session file arguments are not actually
            // specified using the input-file option by the user).
            po::options_description hidden("Hidden options");
            hidden.add_options()
329 330
                    ("input-file", po::value< vector<string> >(), 
                                   "input filename")
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            ;

            // Combine all options for the parser
            po::options_description all("All options");
            all.add(desc).add(hidden);

            // Session file is a positional option
            po::positional_options_description p;
            p.add("input-file", -1);

            // Parse the command-line options
            po::parsed_options parsed = po::command_line_parser(argc, argv).
                                                options(all).
                                                positional(p).
                                                allow_unregistered().
                                                run();

            // Extract known options to map and update
            po::store(parsed, m_cmdLineOptions);
            po::notify(m_cmdLineOptions);

            // Help message
            if (m_cmdLineOptions.count("help"))
            {
                cout << desc << endl;
                exit(0);
            }

            // Enable verbose mode
            if (m_cmdLineOptions.count("verbose"))
            {
                m_verbose = true;
            }
            else
            {
                m_verbose = false;
            }
368
            
369 370 371 372 373 374
            // Print a warning for unknown options
            std::vector< po::basic_option<char> >::iterator x;
            for (x = parsed.options.begin(); x != parsed.options.end(); ++x)
            {
                if (x->unregistered)
                {
375 376
                    cout << "Warning: Unknown option: " << x->string_key 
                         << endl;
377 378 379 380 381 382
                }
            }

            // Return the vector of filename(s) given as positional options
            if (m_cmdLineOptions.count("input-file"))
            {
383 384
                return m_cmdLineOptions["input-file"].as<
                    std::vector<std::string> >();
385 386 387 388 389 390 391 392
            }
            else
            {
                return std::vector<std::string>();
            }
        }


393 394 395
        /**
         *
         */
396 397
        TiXmlDocument& SessionReader::GetDocument()
        {
398
            ASSERTL1(m_xmlDoc, "XML Document not defined.");
399 400 401
            return *m_xmlDoc;
        }

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

        /**
         * The single parameter specifies a path to the requested element in a
         * similar format to the filesystem path. Given the following XML:
         * @code
         * <NEKTAR>
         *   <CONDITIONS>
         *     <PARAMETERS>
         *     ...
         *     </PARAMETERS>
         *   </CONDITIONS>
         * </NEKTAR>
         * @endcode
         * the PARAMETERS element would be retrieved by requesting the path:
         * @code
         * Nektar/Conditions/Parameters
         * @endcode
         * @note Paths are case-insensitive.
         *
         * @param   pPath       Path to requested element.
422 423
         *
         * @return Direct pointer to requested XML Element.
424
         */
425 426 427
        TiXmlElement* SessionReader::GetElement(const string& pPath)
        {
            std::string vPath = boost::to_upper_copy(pPath);
428 429 430
            std::vector<std::string> st;
            boost::split(st, vPath, boost::is_any_of("\\/ "));
            ASSERTL0(st.size() > 0, "No path given in XML element request.");
431

432
            TiXmlElement* vReturn = m_xmlDoc->FirstChildElement(st[0].c_str());
433
            ASSERTL0(vReturn, std::string("Cannot find element '")
434 435
                              + st[0] + std::string("'."));
            for (int i = 1; i < st.size(); ++i)
436
            {
437
                vReturn = vReturn->FirstChildElement(st[i].c_str());
438
                ASSERTL0(vReturn, std::string("Cannot find element '")
439
                                  + st[i] + std::string("'."));
440 441 442 443
            }
            return vReturn;
        }

444 445 446 447 448

        /**
         *
         */
        bool SessionReader::DefinesElement(const std::string &pPath) const
449 450
        {
            std::string vPath = boost::to_upper_copy(pPath);
451 452 453
            std::vector<std::string> st;
            boost::split(st, vPath, boost::is_any_of("\\/ "));
            ASSERTL0(st.size() > 0, "No path given in XML element request.");
454

455
            TiXmlElement* vReturn = m_xmlDoc->FirstChildElement(st[0].c_str());
456
            ASSERTL0(vReturn, std::string("Cannot find element '")
457 458
                              + st[0] + std::string("'."));
            for (int i = 1; i < st.size(); ++i)
459
            {
460
                vReturn = vReturn->FirstChildElement(st[i].c_str());
461 462 463 464 465
                if (!vReturn) return false;
            }
            return true;
        }

466 467 468 469

        /**
         *
         */
470
        const std::string& SessionReader::GetFilename() const
471 472 473 474
        {
            return m_filename;
        }

475 476 477 478

        /**
         *
         */
479 480 481 482 483
        const std::string& SessionReader::GetSessionName() const
        {
            return m_sessionName;
        }

484

485 486 487 488 489 490
        /**
         * Output is of the form [sessionName]_P[idx] where idx is the rank
         * of the process.
         */
        const std::string SessionReader::GetSessionNameRank() const
        {
491
            std::string  dirname = m_sessionName + "_xml"; 
492 493
            fs::path     pdirname(dirname);
            
494
            std::string vFilename = "P" + boost::lexical_cast<std::string>(m_comm->GetRowComm()->GetRank());
495
            fs::path    pFilename(vFilename);            
496

497
            fs::path fullpath = pdirname / pFilename;
498

499 500
            return PortablePath(fullpath);
        }
501

502 503 504
        /**
         *
         */
505 506 507 508 509
        CommSharedPtr& SessionReader::GetComm()
        {
            return m_comm;
        }

510 511 512 513 514 515 516

        /**
         * This routine finalises any parallel communication.
         *
         * @note This routine should be called at the very end of a users
         * application.
         */
517 518 519 520 521
        void SessionReader::Finalise()
        {
            m_comm->Finalise();
        }

522

523 524 525 526 527 528
        /**
         *
         */
        bool SessionReader::DefinesParameter(const std::string& pName) const
        {
            std::string vName = boost::to_upper_copy(pName);
529 530
            ParameterMap::const_iterator paramIter = m_parameters.find(vName);
            return (paramIter != m_parameters.end());
531 532
        }

533 534 535 536 537 538 539 540 541

        /**
         * If the parameter is not defined, termination occurs. Therefore, the
         * parameters existence should be tested for using #DefinesParameter
         * before calling this function.
         *
         * @param   pName       The name of a floating-point parameter.
         * @returns The value of the floating-point parameter.
         */
542 543
        const NekDouble& SessionReader::GetParameter(
            const std::string& pName) const
544 545
        {
            std::string vName = boost::to_upper_copy(pName);
546
            ParameterMap::const_iterator paramIter = m_parameters.find(vName);
547

548 549
            ASSERTL0(paramIter != m_parameters.end(),
                     "Unable to find requested parameter: " + pName);
550

551
            return paramIter->second;
552 553
        }

554 555 556 557

        /**
         *
         */
558 559
        void SessionReader::LoadParameter(
            const std::string &pName, int &pVar) const
560 561
        {
            std::string vName = boost::to_upper_copy(pName);
562 563 564 565
            ParameterMap::const_iterator paramIter = m_parameters.find(vName);
            ASSERTL0(paramIter != m_parameters.end(), "Required parameter '" + 
                     pName + "' not specified in session.");
            pVar = (int)floor(paramIter->second);
566 567
        }

568 569 570 571

        /**
         *
         */
572 573
        void SessionReader::LoadParameter(
            const std::string &pName, int &pVar, const int &pDefault) const
574 575
        {
            std::string vName = boost::to_upper_copy(pName);
576 577
            ParameterMap::const_iterator paramIter = m_parameters.find(vName);
            if(paramIter != m_parameters.end())
578
            {
579
                pVar = (int)floor(paramIter->second);
580 581 582 583 584 585 586
            }
            else
            {
                pVar  = pDefault;
            }
        }

587 588 589 590

        /**
         *
         */
591 592
        void SessionReader::LoadParameter(
            const std::string &pName, NekDouble& pVar) const
593 594
        {
            std::string vName = boost::to_upper_copy(pName);
595 596 597 598
            ParameterMap::const_iterator paramIter = m_parameters.find(vName);
            ASSERTL0(paramIter != m_parameters.end(), "Required parameter '" + 
                     pName + "' not specified in session.");
            pVar = paramIter->second;
599 600
        }

601 602 603 604

        /**
         *
         */
605 606 607 608
        void SessionReader::LoadParameter(
            const std::string &pName, 
                  NekDouble   &pVar, 
            const NekDouble   &pDefault) const
609 610
        {
            std::string vName = boost::to_upper_copy(pName);
611 612
            ParameterMap::const_iterator paramIter = m_parameters.find(vName);
            if(paramIter != m_parameters.end())
613
            {
614
                pVar = paramIter->second;
615 616 617
            }
            else
            {
618
                pVar = pDefault;
619 620 621
            }
        }

622

Spencer Sherwin's avatar
Spencer Sherwin committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636

        /**
         *
         */
        void SessionReader::SetParameter(const std::string &pName, int &pVar) 
        {
            std::string vName = boost::to_upper_copy(pName);
            m_parameters[vName] = pVar;
        }


        /**
         *
         */
637 638
        void SessionReader::SetParameter(
            const std::string &pName, NekDouble& pVar) 
Spencer Sherwin's avatar
Spencer Sherwin committed
639 640 641 642 643 644 645
        {
            std::string vName = boost::to_upper_copy(pName);
            m_parameters[vName] = pVar;
        }



646 647 648 649
        /**
         *
         */
        bool SessionReader::DefinesSolverInfo(const std::string &pName) const
650 651
        {
            std::string vName = boost::to_upper_copy(pName);
652 653
            SolverInfoMap::const_iterator infoIter = m_solverInfo.find(vName);
            return (infoIter != m_solverInfo.end());
654 655
        }

656 657 658 659

        /**
         *
         */
660 661
        const std::string& SessionReader::GetSolverInfo(
            const std::string &pProperty) const
662 663
        {
            std::string vProperty = boost::to_upper_copy(pProperty);
664
            SolverInfoMap::const_iterator iter = m_solverInfo.find(vProperty);
665

666 667
            ASSERTL1(iter != m_solverInfo.end(),
                     "Unable to find requested property: " + pProperty);
668

669
            return iter->second;
670 671 672 673 674 675
        }


        /**
         *
         */
676 677 678 679
        void SessionReader::LoadSolverInfo(
            const std::string &pName, 
                  std::string &pVar, 
            const std::string &pDefault) const
680 681
        {
            std::string vName = boost::to_upper_copy(pName);
682 683
            SolverInfoMap::const_iterator infoIter = m_solverInfo.find(vName);
            if(infoIter != m_solverInfo.end())
684
            {
685
                pVar = infoIter->second;
686 687 688
            }
            else
            {
689
                pVar = pDefault;
690 691 692
            }
        }

693 694 695 696

        /**
         *
         */
697 698 699 700 701
        void SessionReader::MatchSolverInfo(
            const std::string &pName,
            const std::string &pTrueVal,
                  bool        &pVar,
            const bool        &pDefault) const
702 703
        {
            std::string vName = boost::to_upper_copy(pName);
704 705
            SolverInfoMap::const_iterator infoIter = m_solverInfo.find(vName);
            if(infoIter != m_solverInfo.end())
706
            {
707
                pVar = boost::iequals(infoIter->second, pTrueVal);
708 709 710
            }
            else
            {
711
                pVar = pDefault;
712 713 714
            }
        }

715 716 717 718

        /**
         *
         */
719 720 721
        bool SessionReader::MatchSolverInfo(
            const std::string &pName,
            const std::string &pTrueVal) const
722 723 724 725
        {
            if (DefinesSolverInfo(pName))
            {
                std::string vName = boost::to_upper_copy(pName);
726 727
                SolverInfoMap::const_iterator iter = m_solverInfo.find(vName);
                if(iter != m_solverInfo.end())
728 729 730 731 732 733 734 735
                {
                    return true;
                }
            }
            return false;
        }


736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 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 779
        /**
         *
         */
        bool SessionReader::DefinesGlobalSysSolnInfo(const std::string &pVariable, 
                                                     const std::string &pProperty) const
        {

            GloSysSolnInfoList::const_iterator iter = m_gloSysSolnList.find(pVariable);
            if(iter == m_gloSysSolnList.end())
            {
                return false;
            }

            std::string vProperty = boost::to_upper_copy(pProperty);
            
            GloSysInfoMap::const_iterator iter1 = iter->second.find(vProperty);
            if(iter1 == iter->second.end())
            {
                return false;
            }
            
            return true;
        }

        
        /**
         *
         */
        const std::string &SessionReader::GetGlobalSysSolnInfo(const std::string &pVariable, const std::string &pProperty) const
        {
            GloSysSolnInfoList::const_iterator iter; 

            ASSERTL0( (iter = m_gloSysSolnList.find(pVariable)) != m_gloSysSolnList.end(),
                      "Failed to find variable in GlobalSysSolnInfoList");

            std::string vProperty = boost::to_upper_copy(pProperty);
            GloSysInfoMap::const_iterator iter1; 

            ASSERTL0( (iter1 = iter->second.find(vProperty)) != iter->second.end(),
                      "Failed to find property: " + vProperty + " in GlobalSysSolnInfoList");
            
            return iter1->second;
        }
        
780 781 782 783
        /**
         *
         */
        bool SessionReader::DefinesGeometricInfo(const std::string &pName) const
784 785
        {
            std::string vName = boost::to_upper_copy(pName);
786 787
            GeometricInfoMap::const_iterator iter = m_geometricInfo.find(vName);
            return (iter != m_geometricInfo.end());
788 789
        }

790 791 792 793

        /**
         *
         */
794 795 796 797
        void SessionReader::LoadGeometricInfo(
            const std::string &pName,
                  std::string &pVar,
            const std::string &pDefault) const
798 799
        {
            std::string vName = boost::to_upper_copy(pName);
800 801
            GeometricInfoMap::const_iterator iter = m_geometricInfo.find(vName);
            if(iter != m_geometricInfo.end())
802
            {
803
                pVar = iter->second;
804 805 806
            }
            else
            {
807
                pVar = pDefault;
808 809 810
            }
        }

811 812 813 814

        /**
         *
         */
815 816 817 818
        void SessionReader::LoadGeometricInfo(
            const std::string &pName,
                  bool        &pVar,
            const bool        &pDefault) const
819 820
        {
            std::string vName = boost::to_upper_copy(pName);
821 822
            GeometricInfoMap::const_iterator iter = m_geometricInfo.find(vName);
            if(iter != m_geometricInfo.end())
823
            {
824
                if (iter->second == "TRUE")
825 826 827 828 829 830 831 832 833 834
                {
                    pVar = true;
                }
                else
                {
                    pVar = false;
                }
            }
            else
            {
835
                pVar = pDefault;
836 837 838
            }
        }

839

840 841 842
        /**
         *
         */
843 844 845 846
        void SessionReader::LoadGeometricInfo(
            const std::string &pName,
                  NekDouble   &pVar,
            const NekDouble   &pDefault) const
847 848
        {
            std::string vName = boost::to_upper_copy(pName);
849 850
            GeometricInfoMap::const_iterator iter = m_geometricInfo.find(vName);
            if(iter != m_geometricInfo.end())
851
            {
852
                pVar = std::atoi(iter->second.c_str());
853 854 855
            }
            else
            {
856
                pVar = pDefault;
857 858 859 860
            }
        }


861 862 863
        /**
         *
         */
864 865 866 867 868
        void SessionReader::MatchGeometricInfo(
            const std::string &pName,
            const std::string &pTrueVal,
                  bool        &pVar,
            const bool        &pDefault) const
869 870
        {
            std::string vName = boost::to_upper_copy(pName);
871 872
            GeometricInfoMap::const_iterator iter = m_geometricInfo.find(vName);
            if(iter != m_geometricInfo.end())
873
            {
874
                pVar = boost::iequals(iter->second, pTrueVal);
875 876 877 878 879 880 881 882
            }
            else
            {
                pVar  = pDefault;
            }
        }


883 884 885
        /**
         *
         */
886 887
        const std::string& SessionReader::GetVariable(
            const unsigned int &idx) const
888 889 890 891 892
        {
            ASSERTL0(idx < m_variables.size(), "Variable index out of range.");
            return m_variables[idx];
        }

893

894 895 896 897 898 899 900 901 902 903 904 905

        /**
         *
         */
        void SessionReader::SetVariable(const unsigned int &idx, 
                                        std::string newname) 
        {
            ASSERTL0(idx < m_variables.size(), "Variable index out of range.");
            m_variables[idx] = newname;
        }


906 907 908
        /**
         *
         */
909 910 911 912 913
        std::vector<std::string> SessionReader::GetVariables() const
        {
            return m_variables;
        }

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

        /**
         *
         */
        bool SessionReader::DefinesFunction(const std::string &pName) const
        {
            FunctionMap::const_iterator it1;
            std::string vName = boost::to_upper_copy(pName);

            if ((it1 = m_functions.find(vName)) != m_functions.end())
            {
                return true;
            }
            return false;
        }


        /**
         *
         */
934 935 936
        bool SessionReader::DefinesFunction(
            const std::string &pName,
            const std::string &pVariable) const
937 938
        {
            FunctionMap::const_iterator it1;
939
            FunctionVariableMap::const_iterator it2;
940 941
            std::string vName = boost::to_upper_copy(pName);

942 943
            // Check function exists
            if ((it1 = m_functions.find(vName))     != m_functions.end())
944
            {
945 946 947 948
                bool varExists =
                    (it2 = it1->second.find(pVariable)) != it1->second.end() ||
                    (it2 = it1->second.find("*")) != it1->second.end();
                return varExists;
949 950 951 952 953 954 955 956
            }
            return false;
        }


        /**
         *
         */
957 958 959
        EquationSharedPtr SessionReader::GetFunction(
            const std::string &pName,
            const std::string &pVariable) const
960 961
        {
            FunctionMap::const_iterator it1;
962
            FunctionVariableMap::const_iterator it2, it3;
963 964 965 966 967
            std::string vName = boost::to_upper_copy(pName);

            ASSERTL0((it1 = m_functions.find(vName)) != m_functions.end(),
                     std::string("No such function '") + pName
                     + std::string("' has been defined in the session file."));
968 969 970 971 972 973 974 975 976

            // Check for specific and wildcard definitions
            bool specific = (it2 = it1->second.find(pVariable)) !=
                            it1->second.end();
            bool wildcard = (it3 = it1->second.find("*")) !=
                            it1->second.end();

            // Check function is defined somewhere
            ASSERTL0(specific || wildcard,
977 978 979
                     std::string("No such variable '") + pVariable
                     + std::string("' defined for function '") + pName
                     + std::string("' in session file."));
980 981 982 983 984 985 986

            // If not specific, must be wildcard
            if (!specific)
            {
                it2 = it3;
            }

987
            ASSERTL0((it2->second.m_type == eFunctionTypeExpression),
988
                    std::string("Function is defined by a file."));
989
            return it2->second.m_expression;
990 991
        }

992 993 994 995

        /**
         *
         */
996 997 998
        EquationSharedPtr SessionReader::GetFunction(
            const std::string  &pName,
            const unsigned int &pVar) const
999 1000 1001 1002 1003
        {
            ASSERTL0(pVar < m_variables.size(), "Variable index out of range.");
            return GetFunction(pName, m_variables[pVar]);
        }

1004 1005 1006 1007

        /**
         *
         */
1008 1009 1010
        enum FunctionType SessionReader::GetFunctionType(
            const std::string &pName,
            const std::string &pVariable) const
1011 1012
        {
            FunctionMap::const_iterator it1;
1013
            FunctionVariableMap::const_iterator it2, it3;
1014 1015 1016 1017 1018 1019
            std::string vName = boost::to_upper_copy(pName);

            it1 = m_functions.find(vName);
            ASSERTL0 (it1 != m_functions.end(),
                      std::string("Function '") + pName
                      + std::string("' not found."));
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

            // Check for specific and wildcard definitions
            bool specific = (it2 = it1->second.find(pVariable)) !=
                            it1->second.end();
            bool wildcard = (it3 = it1->second.find("*")) !=
                            it1->second.end();

            // Check function is defined somewhere
            ASSERTL0(specific || wildcard,
                     std::string("No such variable '") + pVariable
                     + std::string("' defined for function '") + pName
                     + std::string("' in session file."));

            // If not specific, must be wildcard
            if (!specific)
            {
                it2 = it3;
            }

1039
            return it2->second.m_type;
1040 1041
        }

1042 1043 1044 1045

        /**
         *
         */
1046 1047 1048
        enum FunctionType SessionReader::GetFunctionType(
            const std::string  &pName,
            const unsigned int &pVar) const
1049 1050 1051 1052 1053 1054 1055 1056 1057
        {
            ASSERTL0(pVar < m_variables.size(), "Variable index out of range.");
            return GetFunctionType(pName, m_variables[pVar]);
        }


        /**
         *
         */
1058 1059 1060
        std::string SessionReader::GetFunctionFilename(
            const std::string &pName, 
            const std::string &pVariable) const
1061 1062
        {
            FunctionMap::const_iterator it1;
1063
            FunctionVariableMap::const_iterator it2, it3;
1064 1065 1066 1067 1068 1069
            std::string vName = boost::to_upper_copy(pName);

            it1 = m_functions.find(vName);
            ASSERTL0 (it1 != m_functions.end(),
                      std::string("Function '") + pName
                      + std::string("' not found."));
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

            // Check for specific and wildcard definitions
            bool specific = (it2 = it1->second.find(pVariable)) !=
                            it1->second.end();
            bool wildcard = (it3 = it1->second.find("*")) !=
                            it1->second.end();

            // Check function is defined somewhere
            ASSERTL0(specific || wildcard,
                     std::string("No such variable '") + pVariable
                     + std::string("' defined for function '") + pName
                     + std::string("' in session file."));

            // If not specific, must be wildcard
            if (!specific)
            {
                it2 = it3;
            }

1089 1090 1091 1092 1093 1094 1095
            return it2->second.m_filename;
        }


        /**
         *
         */
1096 1097 1098
        std::string SessionReader::GetFunctionFilename(
            const std::string  &pName, 
            const unsigned int &pVar) const
1099 1100 1101
        {
            ASSERTL0(pVar < m_variables.size(), "Variable index out of range.");
            return GetFunctionFilename(pName, m_variables[pVar]);
1102 1103 1104
        }


1105 1106 1107 1108 1109 1110 1111 1112 1113
        /**
         *
         */
        AnalyticExpressionEvaluator& SessionReader::GetExpressionEvaluator()
        {
            return m_exprEvaluator;
        }


1114 1115 1116 1117
        /**
         *
         */
        bool SessionReader::DefinesTag(const std::string &pName) const
1118 1119
        {
            std::string vName = boost::to_upper_copy(pName);
1120
            TagMap::const_iterator vTagIterator = m_tags.find(vName);
1121 1122 1123
            return (vTagIterator != m_tags.end());
        }

1124 1125 1126 1127

        /**
         *
         */
1128 1129 1130
        void SessionReader::SetTag(
            const std::string &pName, 
            const std::string &pValue)
1131 1132 1133 1134 1135
        {
            std::string vName = boost::to_upper_copy(pName);
            m_tags[vName] = pValue;
        }

1136 1137 1138 1139 1140

        /**
         *
         */
        const std::string &SessionReader::GetTag(const std::string& pName) const
1141 1142
        {
            std::string vName = boost::to_upper_copy(pName);
1143
            TagMap::const_iterator vTagIterator = m_tags.find(vName);
1144 1145 1146 1147 1148
            ASSERTL0(vTagIterator != m_tags.end(),
                     "Requested tag does not exist.");
            return vTagIterator->second;
        }

1149

1150 1151 1152 1153 1154 1155 1156 1157 1158
        /**
         *
         */
        const FilterMap &SessionReader::GetFilters() const
        {
            return m_filters;
        }


1159 1160 1161
        /**
         *
         */
1162 1163
        bool SessionReader::DefinesCmdLineArgument(
            const std::string& pName) const
1164 1165 1166 1167 1168 1169 1170 1171
        {
            return (m_cmdLineOptions.find(pName) != m_cmdLineOptions.end());
        }


        /**
         *
         */
1172 1173
        template <typename T>
        T SessionReader::GetCmdLineArgument(
1174
            const std::string& pName) const
1175
        {
1176
            return m_cmdLineOptions.find(pName)->second.as<T>();
1177 1178 1179
        }


1180 1181 1182 1183 1184 1185
        /**
         *
         */
        void SessionReader::SubstituteExpressions(std::string& pExpr)
        {
            ExpressionMap::iterator exprIter;
1186 1187
            for (exprIter  = m_expressions.begin(); 
                 exprIter != m_expressions.end(); ++exprIter)
1188 1189 1190 1191 1192
            {
                boost::replace_all(pExpr, exprIter->first, exprIter->second);
            }
        }

1193 1194 1195 1196
        CompositeOrdering SessionReader::GetCompositeOrdering() const
        {
            return m_compOrder;
        }
1197

1198 1199 1200 1201 1202
        BndRegionOrdering SessionReader::GetBndRegionOrdering() const
        {
            return m_bndRegOrder;
        }

1203 1204 1205 1206 1207 1208 1209
        /**
         *
         */
        void SessionReader::LoadDoc(
            const std::string &pFilename,
            TiXmlDocument* pDoc) const
        {
1210 1211
            if (pFilename.size() > 3 &&
                pFilename.substr(pFilename.size() - 3, 3) == ".gz")
1212
            {
1213 1214 1215
                ifstream file(pFilename.c_str(),
                              ios_base::in | ios_base::binary);
                ASSERTL0(file.good(), "Unable to open file: " + pFilename);
1216
                stringstream ss;
1217 1218
                io::filtering_streambuf<io::input> in;
                in.push(io::gzip_decompressor());
1219
                in.push(file);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
                try
                {
                    io::copy(in, ss);
                    ss >> (*pDoc);
                }
                catch (io::gzip_error& e)
                {
                    ASSERTL0(false,
                             "Error: File '" + pFilename + "' is corrupt.");
                }
1230 1231 1232
            }
            else
            {
1233 1234 1235
                ifstream file(pFilename.c_str());
                ASSERTL0(file.good(), "Unable to open file: " + pFilename);
                file >> (*pDoc);
1236 1237 1238
            }
        }

1239 1240 1241
        /**
         *
         */
1242 1243
        TiXmlDocument *SessionReader::MergeDoc(
            const std::vector<std::string> &pFilenames) const
1244
        {
1245 1246
            ASSERTL0(pFilenames.size() > 0, "No filenames for merging.");

1247
            // Read the first document
1248 1249 1250
            TiXmlDocument *vMainDoc = new TiXmlDocument;
            LoadDoc(pFilenames[0], vMainDoc);

1251
            TiXmlHandle vMainHandle(vMainDoc);
1252 1253
            TiXmlElement* vMainNektar = 
                vMainHandle.FirstChildElement("NEKTAR").Element();
1254 1255 1256 1257

            // Read all subsequent XML documents.
            // For each element within the NEKTAR tag, use it to replace the
            // version already present in the loaded XML data.
1258
            for (int i = 1; i < pFilenames.size(); ++i)
1259
            {
1260 1261
                if((pFilenames[i].compare(pFilenames[i].size()-3,3,"xml") == 0)
                   ||(pFilenames[i].compare(pFilenames[i].size()-6,6,"xml.gz") == 0))
1262
                {
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
                    TiXmlDocument* vTempDoc = new TiXmlDocument;
                    LoadDoc(pFilenames[i], vTempDoc);
                    
                    TiXmlHandle docHandle(vTempDoc);
                    TiXmlElement* vTempNektar;
                    vTempNektar = docHandle.FirstChildElement("NEKTAR").Element();
                    ASSERTL0(vTempNektar, "Unable to find NEKTAR tag in file.");
                    TiXmlElement* p = vTempNektar->FirstChildElement();
                    
                    while (p)
1273
                    {
1274 1275 1276 1277 1278 1279 1280 1281 1282
                        TiXmlElement *vMainEntry = 
                            vMainNektar->FirstChildElement(p->Value());
                        TiXmlElement *q = new TiXmlElement(*p);
                        if (vMainEntry)
                        {
                            vMainNektar->RemoveChild(vMainEntry);
                        }
                        vMainNektar->LinkEndChild(q);
                        p = p->NextSiblingElement();
1283
                    }
1284 1285
                    
                    delete vTempDoc;
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
                }
            }
            return vMainDoc;
        }


        /**
         *
         */
        void SessionReader::ParseDocument()
        {
            // Check we actually have a document loaded.
            ASSERTL0(m_xmlDoc, "No XML document loaded.");

            // Look for all data in CONDITIONS block.
1301 1302
            TiXmlHandle docHandle(m_xmlDoc);
            TiXmlElement* e;
1303 1304
            e = docHandle.FirstChildElement("NEKTAR").
                FirstChildElement("CONDITIONS").Element();
1305

1306
            // Read the various sections of the CONDITIONS block
Chris Cantwell's avatar
Chris Cantwell committed
1307 1308
            ReadParameters        (e);
            ReadSolverInfo        (e);
1309
            ReadGlobalSysSolnInfo (e);
Chris Cantwell's avatar
Chris Cantwell committed
1310 1311 1312
            ReadExpressions       (e);
            ReadVariables         (e);
            ReadFunctions         (e);
1313

1314 1315
            e = docHandle.FirstChildElement("NEKTAR").
                FirstChildElement("GEOMETRY").Element();
1316 1317

            ReadGeometricInfo(e);
1318

1319 1320
            e = docHandle.FirstChildElement("NEKTAR").
                FirstChildElement("FILTERS").Element();
1321 1322

            ReadFilters(e);
1323 1324 1325
        }


1326 1327 1328
        /**
         *
         */
1329 1330
        void SessionReader::CreateComm(
            int               &argc, 
1331
            char*              argv[])
1332 1333 1334 1335 1336 1337 1338 1339
        {
            if (argc == 0)
            {
                m_comm = GetCommFactory().CreateInstance("Serial", 0, 0);
            }
            else
            {
                string vCommModule("Serial");
1340
                if (GetCommFactory().ModuleExists("ParallelMPI"))
1341 1342 1343 1344 1345 1346 1347 1348
                {
                    vCommModule = "ParallelMPI";
                }

                m_comm = GetCommFactory().CreateInstance(vCommModule,argc,argv);
            }
        }

1349 1350 1351 1352

        /**
         *
         */
1353 1354 1355
        void SessionReader::PartitionMesh()
        {
            ASSERTL0(m_comm.get(), "Communication not initialised.");
1356 1357 1358 1359 1360 1361

            // Get row of comm, or the whole comm if not split
            CommSharedPtr vCommMesh = m_comm->GetRowComm();

            // Partition mesh into length of row comms
            if (vCommMesh->GetSize() > 1)
1362
            {
1363 1364 1365