FieldIO.cpp 58.8 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
////////////////////////////////////////////////////////////////////////////////
//
//  File: FieldIO.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: I/O routines relating to Fields
//
////////////////////////////////////////////////////////////////////////////////

36
#include <boost/format.hpp>
37
38
39
40
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/asio/ip/host_name.hpp>

41
#include <LibUtilities/BasicUtils/FieldIO.h>
42
#include <LibUtilities/BasicUtils/FileSystem.h>
43
44
#include <LibUtilities/BasicConst/GitRevision.h>

45
#include "zlib.h"
46
#include <set>
47

48
49
50
51
#ifdef NEKTAR_USE_MPI
#include <mpi.h>
#endif

52
53
// Buffer size for zlib compression/decompression
#define CHUNK 16384
54

55
56
57
58
59
60
#ifndef NEKTAR_VERSION
#define NEKTAR_VERSION "Unknown"
#endif

namespace ptime = boost::posix_time;
namespace ip = boost::asio::ip;
61
namespace berrc = boost::system::errc;
62

63
64
65
66
namespace Nektar
{
    namespace LibUtilities
    {
67
68
69
70
71
72
73
74
75
        /**
         * This function allows for data to be written to an FLD file when a
         * session and/or communicator is not instantiated. Typically used in
         * utilities which do not take XML input and operate in serial only.
         */
        void Write(     const std::string &outFile,
                        std::vector<FieldDefinitionsSharedPtr> &fielddefs,
                        std::vector<std::vector<NekDouble> >   &fielddata,
                        const FieldMetaDataMap &fieldinfomap)
76
        {
77
78
#ifdef NEKTAR_USE_MPI
            int size;
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
            int init;
            MPI_Initialized(&init);

            // If MPI has been initialised we can check the number of processes
            // and, if > 1, tell the user he should not be running this
            // function in parallel. If it is not initialised, we do not
            // initialise it here, and assume the user knows what they are
            // doing.
            if (init)
            {
                MPI_Comm_size( MPI_COMM_WORLD, &size );
                ASSERTL0(size == 1,
                     "This static function is not available in parallel. Please"
                     "instantiate a FieldIO object for parallel use.");
            }
94
#endif
95
96
97
            CommSharedPtr c = GetCommFactory().CreateInstance("Serial", 0, 0);
            FieldIO f(c);
            f.Write(outFile, fielddefs, fielddata, fieldinfomap);
98
99
100
        }


101
102
103
104
105
106
107
108
109
110
111
112
113
114
        /**
         * This function allows for data to be imported from an FLD file when
         * a session and/or communicator is not instantiated. Typically used in
         * utilities which only operate in serial.
         */
        LIB_UTILITIES_EXPORT void Import(
                        const std::string& infilename,
                        std::vector<FieldDefinitionsSharedPtr> &fielddefs,
                        std::vector<std::vector<NekDouble> > &fielddata,
                        FieldMetaDataMap &fieldinfomap,
                        const Array<OneD, int> ElementiDs)
        {
#ifdef NEKTAR_USE_MPI
            int size;
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
            int init;
            MPI_Initialized(&init);

            // If MPI has been initialised we can check the number of processes
            // and, if > 1, tell the user he should not be running this
            // function in parallel. If it is not initialised, we do not
            // initialise it here, and assume the user knows what they are
            // doing.
            if (init)
            {
                MPI_Comm_size( MPI_COMM_WORLD, &size );
                ASSERTL0(size == 1,
                     "This static function is not available in parallel. Please"
                     "instantiate a FieldIO object for parallel use.");
            }
130
131
132
133
#endif
            CommSharedPtr c = GetCommFactory().CreateInstance("Serial", 0, 0);
            FieldIO f(c);
            f.Import(infilename, fielddefs, fielddata, fieldinfomap, ElementiDs);
134
135
        }

136
137

        /**
138
139
         *
         */
140
141
142
        FieldIO::FieldIO(
                LibUtilities::CommSharedPtr pComm)
            : m_comm(pComm)
143
144
145
146
147
148
149
        {
        }


        /**
         *
         */
150
        void FieldIO::Write(const std::string &outFile,
151
                   std::vector<FieldDefinitionsSharedPtr> &fielddefs,
Chris Cantwell's avatar
Chris Cantwell committed
152
                   std::vector<std::vector<NekDouble> > &fielddata,
153
                   const FieldMetaDataMap &fieldmetadatamap)
154
        {
155
            // Check everything seems sensible
156
157
            ASSERTL1(fielddefs.size() == fielddata.size(),
                      "Length of fielddefs and fielddata incompatible");
158
159
160
161
            for (int f = 0; f < fielddefs.size(); ++f)
            {
                ASSERTL1(fielddata[f].size() > 0,
                        "Fielddata vector must contain at least one value.");
162

163
164
165
166
167
168
169
170
171
172
173
174
                ASSERTL1(fielddata[f].size() ==
                             fielddefs[f]->m_fields.size() *
                             CheckFieldDefinition(fielddefs[f]),
                         "Invalid size of fielddata vector.");
            }

            // Prepare to write out data. In parallel, we must create directory
            // and determine the full pathname to the file to write out.
            // Any existing file/directory which is in the way is removed.
            std::string filename = SetUpOutput(outFile, fielddefs, fieldmetadatamap);

            // Create the file (partition)
175
176
177
178
179
180
181
182
            TiXmlDocument doc;
            TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "utf-8", "");
            doc.LinkEndChild(decl);

            TiXmlElement * root = new TiXmlElement("NEKTAR");
            doc.LinkEndChild(root);

            AddInfoTag(root,fieldmetadatamap);
183
184
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
251
252
253
254
255
256
257
258
259
260
261

            for (int f = 0; f < fielddefs.size(); ++f)
            {
                //---------------------------------------------
                // Write ELEMENTS
                TiXmlElement * elemTag = new TiXmlElement("ELEMENTS");
                root->LinkEndChild(elemTag);

                // Write FIELDS
                std::string fieldsString;
                {
                    std::stringstream fieldsStringStream;
                    bool first = true;
                    for (std::vector<int>::size_type i = 0; i
                    < fielddefs[f]->m_fields.size(); i++)
                    {
                        if (!first)
                            fieldsStringStream << ",";
                        fieldsStringStream << fielddefs[f]->m_fields[i];
                        first = false;
                    }
                    fieldsString = fieldsStringStream.str();
                }
                elemTag->SetAttribute("FIELDS", fieldsString);

                // Write SHAPE
                std::string shapeString;
                {
                    std::stringstream shapeStringStream;
                    shapeStringStream << ShapeTypeMap[fielddefs[f]->m_shapeType];
                    if(fielddefs[f]->m_numHomogeneousDir == 1)
                    {
                        shapeStringStream << "-HomogenousExp1D";
                    }
                    else if (fielddefs[f]->m_numHomogeneousDir == 2)
                    {
                        shapeStringStream << "-HomogenousExp2D";
                    }

                    shapeString = shapeStringStream.str();
                }
                elemTag->SetAttribute("SHAPE", shapeString);

                // Write BASIS
                std::string basisString;
                {
                    std::stringstream basisStringStream;
                    bool first = true;
                    for (std::vector<BasisType>::size_type i = 0; i < fielddefs[f]->m_basis.size(); i++)
                    {
                        if (!first)
                            basisStringStream << ",";
                        basisStringStream
                        << BasisTypeMap[fielddefs[f]->m_basis[i]];
                        first = false;
                    }
                    basisString = basisStringStream.str();
                }
                elemTag->SetAttribute("BASIS", basisString);

                // Write homogeneuous length details
                if(fielddefs[f]->m_numHomogeneousDir)
                {
                    std::string homoLenString;
                    {
                        std::stringstream homoLenStringStream;
                        bool first = true;
                        for (int i = 0; i < fielddefs[f]->m_numHomogeneousDir; ++i)
                        {
                            if (!first)
                                homoLenStringStream << ",";
                            homoLenStringStream
                            << fielddefs[f]->m_homogeneousLengths[i];
                            first = false;
                        }
                        homoLenString = homoLenStringStream.str();
                    }
                    elemTag->SetAttribute("HOMOGENEOUSLENGTHS", homoLenString);
                }
Chris Cantwell's avatar
Chris Cantwell committed
262

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
                // Write homogeneuous planes/lines details
                if(fielddefs[f]->m_numHomogeneousDir)
                {
                    if(fielddefs[f]->m_homogeneousYIDs.size() > 0)
                    {
                        std::string homoYIDsString;
                        {
                            std::stringstream homoYIDsStringStream;
                            bool first = true;
                            for(int i = 0; i < fielddefs[f]->m_homogeneousYIDs.size(); i++)
                            {
                                if (!first)
                                    homoYIDsStringStream << ",";
                                homoYIDsStringStream << fielddefs[f]->m_homogeneousYIDs[i];
                                first = false;
                            }
                            homoYIDsString = homoYIDsStringStream.str();
                        }
                        elemTag->SetAttribute("HOMOGENEOUSYIDS", homoYIDsString);
                    }
Chris Cantwell's avatar
Chris Cantwell committed
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
                    if(fielddefs[f]->m_homogeneousZIDs.size() > 0)
                    {
                        std::string homoZIDsString;
                        {
                            std::stringstream homoZIDsStringStream;
                            bool first = true;
                            for(int i = 0; i < fielddefs[f]->m_homogeneousZIDs.size(); i++)
                            {
                                if (!first)
                                    homoZIDsStringStream << ",";
                                homoZIDsStringStream << fielddefs[f]->m_homogeneousZIDs[i];
                                first = false;
                            }
                            homoZIDsString = homoZIDsStringStream.str();
                        }
                        elemTag->SetAttribute("HOMOGENEOUSZIDS", homoZIDsString);
                    }
                }
Chris Cantwell's avatar
Chris Cantwell committed
302

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
                // Write NUMMODESPERDIR
                std::string numModesString;
                {
                    std::stringstream numModesStringStream;

                    if (fielddefs[f]->m_uniOrder)
                    {
                        numModesStringStream << "UNIORDER:";
                        // Just dump single definition
                        bool first = true;
                        for (std::vector<int>::size_type i = 0; i
                                 < fielddefs[f]->m_basis.size(); i++)
                        {
                            if (!first)
                                numModesStringStream << ",";
                            numModesStringStream << fielddefs[f]->m_numModes[i];
                            first = false;
                        }
                    }
                    else
                    {
                        numModesStringStream << "MIXORDER:";
                        bool first = true;
                        for (std::vector<int>::size_type i = 0; i
                                 < fielddefs[f]->m_numModes.size(); i++)
                        {
                            if (!first)
                                numModesStringStream << ",";
                            numModesStringStream << fielddefs[f]->m_numModes[i];
                            first = false;
                        }
                    }
Chris Cantwell's avatar
Chris Cantwell committed
335

336
337
338
339
340
341
342
343
344
345
                    numModesString = numModesStringStream.str();
                }
                elemTag->SetAttribute("NUMMODESPERDIR", numModesString);

                // Write ID
                // Should ideally look at ways of compressing this stream
                // if just sequential;
                std::string idString;
                {
                    std::stringstream idStringStream;
Chris Cantwell's avatar
Chris Cantwell committed
346
                    GenerateSeqString(fielddefs[f]->m_elementIDs,idString);
347
348
                }
                elemTag->SetAttribute("ID", idString);
349
350
                elemTag->SetAttribute("COMPRESSED",
                              LibUtilities::CompressData::GetCompressString());
351
352
353
354

                // Add this information for future compatibility
                // issues, for exmaple in case we end up using a 128
                // bit machine.
355
356
                elemTag->SetAttribute("BITSIZE",
                              LibUtilities::CompressData::GetBitSizeStr());
357
                std::string base64string;
Chris Cantwell's avatar
Chris Cantwell committed
358
359
                ASSERTL0(Z_OK == CompressData::ZlibEncodeToBase64Str(
                                                fielddata[f], base64string),
360
                         "Failed to compress field data.");
Chris Cantwell's avatar
Chris Cantwell committed
361

362
363
364
                elemTag->LinkEndChild(new TiXmlText(base64string));

            }
365
            doc.SaveFile(filename);
366
367
368
369
370
371
        }


        /**
         *
         */
372
        void FieldIO::Import(const std::string& infilename,
373
374
                    std::vector<FieldDefinitionsSharedPtr> &fielddefs,
                    std::vector<std::vector<NekDouble> > &fielddata,
375
376
                    FieldMetaDataMap &fieldmetadatamap,
                    const Array<OneD, int> ElementIDs)
377
378
        {

379
            std::string infile = infilename;
380

Chris Cantwell's avatar
Chris Cantwell committed
381
382
            fs::path pinfilename(infilename);

383
            if(fs::is_directory(pinfilename)) // check to see that infile is a directory
384
            {
385
                fs::path infofile("Info.xml");
Chris Cantwell's avatar
Chris Cantwell committed
386
                fs::path fullpath = pinfilename / infofile;
387
                infile = PortablePath(fullpath);
388

Chris Cantwell's avatar
Chris Cantwell committed
389
                std::vector<std::string> filenames;
390
                std::vector<std::vector<unsigned int> > elementIDs_OnPartitions;
Chris Cantwell's avatar
Chris Cantwell committed
391
392


393
394
                ImportMultiFldFileIDs(infile,filenames, elementIDs_OnPartitions,
                                      fieldmetadatamap);
Chris Cantwell's avatar
Chris Cantwell committed
395

396
397
                // Load metadata
                ImportFieldMetaData(infile,fieldmetadatamap);
398

399
400
401
402
                if(ElementIDs == NullInt1DArray) //load all fields
                {
                    for(int i = 0; i < filenames.size(); ++i)
                    {
403
                        fs::path pfilename(filenames[i]);
Chris Cantwell's avatar
Chris Cantwell committed
404
405
                        fullpath = pinfilename / pfilename;
                        string fname = PortablePath(fullpath);
406

407
                        TiXmlDocument doc1(fname);
408
                        bool loadOkay1 = doc1.LoadFile();
Chris Cantwell's avatar
Chris Cantwell committed
409

410
                        std::stringstream errstr;
411
                        errstr << "Unable to load file: " << fname << std::endl;
412
                        errstr << "Reason: " << doc1.ErrorDesc() << std::endl;
413
                        errstr << "Position: Line " << doc1.ErrorRow() << ", Column " << doc1.ErrorCol() << std::endl;
414
                        ASSERTL0(loadOkay1, errstr.str());
Chris Cantwell's avatar
Chris Cantwell committed
415

416
                        ImportFieldDefs(doc1, fielddefs, false);
417
                        if(fielddata != NullVectorNekDoubleVector)
418
419
420
                        {
                            ImportFieldData(doc1, fielddefs, fielddata);
                        }
421
                    }
Chris Cantwell's avatar
Chris Cantwell committed
422

423
424
425
426
                }
                else // only load relevant partitions
                {
                    int i,j;
427
428
                    map<int,vector<int> > FileIDs;
                    map<int,vector<int> >::iterator it;
429
                    set<int> LoadFile;
430

431
432
433
434
                    for(i = 0; i < elementIDs_OnPartitions.size(); ++i)
                    {
                        for(j = 0; j < elementIDs_OnPartitions[i].size(); ++j)
                        {
435
                            FileIDs[elementIDs_OnPartitions[i][j]].push_back(i);
436
437
                        }
                    }
Chris Cantwell's avatar
Chris Cantwell committed
438

439
440
                    for(i = 0; i < ElementIDs.num_elements(); ++i)
                    {
441
442
                        it = FileIDs.find(ElementIDs[i]);
                        if (it != FileIDs.end())
443
                        {
444
445
446
447
                            for (j = 0; j < it->second.size(); ++j)
                            {
                                LoadFile.insert(it->second[j]);
                            }
448
                        }
449
                    }
Chris Cantwell's avatar
Chris Cantwell committed
450
451

                    set<int>::iterator iter;
452
453
                    for(iter = LoadFile.begin(); iter != LoadFile.end(); ++iter)
                    {
454
                        fs::path pfilename(filenames[*iter]);
Chris Cantwell's avatar
Chris Cantwell committed
455
456
                        fullpath = pinfilename / pfilename;
                        string fname = PortablePath(fullpath);
457
                        TiXmlDocument doc1(fname);
458
                        bool loadOkay1 = doc1.LoadFile();
Chris Cantwell's avatar
Chris Cantwell committed
459

460
                        std::stringstream errstr;
461
                        errstr << "Unable to load file: " << fname << std::endl;
462
                        errstr << "Reason: " << doc1.ErrorDesc() << std::endl;
463
                        errstr << "Position: Line " << doc1.ErrorRow() << ", Column " << doc1.ErrorCol() << std::endl;
464
                        ASSERTL0(loadOkay1, errstr.str());
Chris Cantwell's avatar
Chris Cantwell committed
465

466
                        ImportFieldDefs(doc1, fielddefs, false);
467
                        if(fielddata != NullVectorNekDoubleVector)
468
469
470
                        {
                            ImportFieldData(doc1, fielddefs, fielddata);
                        }
471
472
473
                    }
                }
            }
Chris Cantwell's avatar
Chris Cantwell committed
474
            else // serial format case
475
            {
Chris Cantwell's avatar
Chris Cantwell committed
476

477
478
                TiXmlDocument doc(infile);
                bool loadOkay = doc.LoadFile();
Chris Cantwell's avatar
Chris Cantwell committed
479

480
481
482
                std::stringstream errstr;
                errstr << "Unable to load file: " << infile << std::endl;
                errstr << "Reason: " << doc.ErrorDesc() << std::endl;
Chris Cantwell's avatar
Chris Cantwell committed
483
                errstr << "Position: Line " << doc.ErrorRow() << ", Column " <<
484
485
                    doc.ErrorCol() << std::endl;
                ASSERTL0(loadOkay, errstr.str());
Chris Cantwell's avatar
Chris Cantwell committed
486

487
                ImportFieldMetaData(doc,fieldmetadatamap);
488
                ImportFieldDefs(doc, fielddefs, false);
489
                if(fielddata != NullVectorNekDoubleVector)
490
491
492
                {
                    ImportFieldData(doc, fielddefs, fielddata);
                }
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

        /**
         *
         */
        void FieldIO::WriteMultiFldFileIDs(const std::string &outFile,
                                  const std::vector<std::string> fileNames,
                                  std::vector<std::vector<unsigned int> > &elementList,
                                  const FieldMetaDataMap &fieldmetadatamap)
        {
            TiXmlDocument doc;
            TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "utf-8", "");
            doc.LinkEndChild(decl);

            ASSERTL0(fileNames.size() == elementList.size(),"Outfile names and list of elements ids does not match");

            TiXmlElement * root = new TiXmlElement("NEKTAR");
            doc.LinkEndChild(root);

            AddInfoTag(root,fieldmetadatamap);

            for (int t = 0; t < fileNames.size(); ++t)
            {
518
519
520
521
                if(elementList[t].size())
                {
                    TiXmlElement * elemIDs = new TiXmlElement("Partition");
                    root->LinkEndChild(elemIDs);
Chris Cantwell's avatar
Chris Cantwell committed
522

523
                    elemIDs->SetAttribute("FileName",fileNames[t]);
Chris Cantwell's avatar
Chris Cantwell committed
524

525
                    string IDstring;
Chris Cantwell's avatar
Chris Cantwell committed
526

527
                    GenerateSeqString(elementList[t],IDstring);
528

529
530
                    elemIDs->LinkEndChild(new TiXmlText(IDstring));
                }
531
532
533
534
535
536
            }

            doc.SaveFile(outFile);
        }


Chris Cantwell's avatar
Chris Cantwell committed
537
        /**
538
539
         *
         */
540
         void FieldIO::ImportMultiFldFileIDs(const std::string &inFile,
541
                                    std::vector<std::string> &fileNames,
542
543
                                    std::vector<std::vector<unsigned int> > &elementList,
                                    FieldMetaDataMap &fieldmetadatamap)
Chris Cantwell's avatar
Chris Cantwell committed
544
         {
545
546
             TiXmlDocument doc(inFile);
             bool loadOkay = doc.LoadFile();
Chris Cantwell's avatar
Chris Cantwell committed
547
548


549
550
551
552
553
             std::stringstream errstr;
             errstr << "Unable to load file: " << inFile<< std::endl;
             errstr << "Reason: " << doc.ErrorDesc() << std::endl;
             errstr << "Position: Line " << doc.ErrorRow() << ", Column " << doc.ErrorCol() << std::endl;
             ASSERTL0(loadOkay, errstr.str());
Chris Cantwell's avatar
Chris Cantwell committed
554

555
             // Handle on XML document
556
             TiXmlHandle docHandle(&doc);
Chris Cantwell's avatar
Chris Cantwell committed
557

558
559
560
             // Retrieve main NEKTAR tag - XML specification states one
             // top-level element tag per file.
             TiXmlElement* master = doc.FirstChildElement("NEKTAR");
561
             ASSERTL0(master, "Unable to find NEKTAR tag in file.");
562
563
564
565
566
567
568

             // Partition element tag name
             std::string strPartition = "Partition";

             // First attempt to get the first Partition element
             TiXmlElement* fldfileIDs = master->FirstChildElement(strPartition.c_str());
             if (!fldfileIDs)
569
             {
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
                 // If this files try previous name
                 strPartition = "MultipleFldFiles";
                 fldfileIDs = master->FirstChildElement("MultipleFldFiles");
             }
             ASSERTL0(fldfileIDs,
                      "Unable to find 'Partition' or 'MultipleFldFiles' tag "
                      "within nektar tag.");

             while (fldfileIDs)
             {
                // Read file name of partition file
                const char *attr = fldfileIDs->Attribute("FileName");
                ASSERTL0(attr, "'FileName' not provided as an attribute of '"
                                + strPartition + "' tag.");
                fileNames.push_back(std::string(attr));

                const char* elementIDs = fldfileIDs->GetText();
                ASSERTL0(elementIDs, "Element IDs not specified.");

                std::string elementIDsStr(elementIDs);

                std::vector<unsigned int> idvec;
                ParseUtils::GenerateSeqVector(elementIDsStr.c_str(),idvec);

                elementList.push_back(idvec);

                fldfileIDs = fldfileIDs->NextSiblingElement(strPartition.c_str());
597
598
             }
         }
599

600
        void FieldIO::ImportFieldMetaData(std::string filename,
601
602
603
604
                                 FieldMetaDataMap &fieldmetadatamap)
        {
            TiXmlDocument doc(filename);
            bool loadOkay = doc.LoadFile();
Chris Cantwell's avatar
Chris Cantwell committed
605

606
607
608
609
610
            std::stringstream errstr;
            errstr << "Unable to load file: " << filename << std::endl;
            errstr << "Reason: " << doc.ErrorDesc() << std::endl;
            errstr << "Position: Line " << doc.ErrorRow() << ", Column " << doc.ErrorCol() << std::endl;
            ASSERTL0(loadOkay, errstr.str());
Chris Cantwell's avatar
Chris Cantwell committed
611

612
613
            ImportFieldMetaData(doc,fieldmetadatamap);
        }
Chris Cantwell's avatar
Chris Cantwell committed
614

615

616
        void FieldIO::ImportFieldMetaData(TiXmlDocument &doc,
617
618
                                FieldMetaDataMap &fieldmetadatamap)
        {
Chris Cantwell's avatar
Chris Cantwell committed
619

620
            TiXmlHandle docHandle(&doc);
621
622
            TiXmlElement* master = 0;    // Master tag within which all data is contained.
            TiXmlElement* metadata = 0;
Chris Cantwell's avatar
Chris Cantwell committed
623

624
625
626
627
            master = doc.FirstChildElement("NEKTAR");
            ASSERTL0(master, "Unable to find NEKTAR tag in file.");
            std::string strLoop = "NEKTAR";

628
629
630
631
            // Retain original metadata structure for backwards compatibility
            // TODO: Remove old metadata format
            metadata = master->FirstChildElement("FIELDMETADATA");
            if(metadata)
632
633
            {
                TiXmlElement *param = metadata->FirstChildElement("P");
634

635
636
637
638
639
                while (param)
                {
                    TiXmlAttribute *paramAttr = param->FirstAttribute();
                    std::string attrName(paramAttr->Name());
                    std::string paramString;
640

641
642
643
644
645
646
647
648
649
650
651
                    if(attrName == "PARAM")
                    {
                        paramString.insert(0,paramAttr->Value());
                    }
                    else
                    {
                        ASSERTL0(false,"PARAM not provided as an attribute in FIELDMETADATA section");
                    }

                    // Now read body of param
                    std::string paramBodyStr;
652

653
                    TiXmlNode *paramBody = param->FirstChild();
654

655
                    paramBodyStr += paramBody->ToText()->Value();
656
657
658
659
660
661
662
663
664
665
666

                    fieldmetadatamap[paramString] = paramBodyStr;
                    param = param->NextSiblingElement("P");
                }
            }

            // New metadata format
            metadata = master->FirstChildElement("Metadata");
            if(metadata)
            {
                TiXmlElement *param = metadata->FirstChildElement();
Chris Cantwell's avatar
Chris Cantwell committed
667

668
669
670
671
                while (param)
                {
                    std::string paramString = param->Value();
                    if (paramString != "Provenance")
672
                    {
673
674
675
                        // Now read body of param
                        TiXmlNode *paramBody = param->FirstChild();
                        std::string paramBodyStr = paramBody->ToText()->Value();
676

677
678
679
                        fieldmetadatamap[paramString] = paramBodyStr;
                    }
                    param = param->NextSiblingElement();
680
681
                }
            }
682

683
        }
Chris Cantwell's avatar
Chris Cantwell committed
684

685
686
687
688

        /**
         * The bool decides if the FieldDefs are in <EXPANSIONS> or in <NEKTAR>.
         */
689
        void FieldIO::ImportFieldDefs(TiXmlDocument &doc, std::vector<FieldDefinitionsSharedPtr> &fielddefs,
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
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
                             bool expChild)
        {
            TiXmlHandle docHandle(&doc);
            TiXmlElement* master = NULL;    // Master tag within which all data is contained.

            master = doc.FirstChildElement("NEKTAR");
            ASSERTL0(master, "Unable to find NEKTAR tag in file.");
            std::string strLoop = "NEKTAR";
            TiXmlElement* loopXml = master;

            TiXmlElement *expansionTypes;
            if(expChild)
            {
                expansionTypes = master->FirstChildElement("EXPANSIONS");
                ASSERTL0(expansionTypes, "Unable to find EXPANSIONS tag in file.");
                loopXml = expansionTypes;
                strLoop = "EXPANSIONS";
            }

            // Loop through all nektar tags, finding all of the element tags.
            while (loopXml)
            {
                TiXmlElement* element = loopXml->FirstChildElement("ELEMENTS");
                ASSERTL0(element, "Unable to find ELEMENTS tag within nektar tag.");

                while (element)
                {
                    // Extract the attributes.
                    std::string idString;
                    std::string shapeString;
                    std::string basisString;
                    std::string homoLengthsString;
                    std::string homoZIDsString;
                    std::string homoYIDsString;
                    std::string numModesString;
                    std::string numPointsString;
                    std::string fieldsString;
                    std::string pointsString;
                    bool pointDef = false;
                    bool numPointDef = false;
                    TiXmlAttribute *attr = element->FirstAttribute();
                    while (attr)
                    {
                        std::string attrName(attr->Name());
                        if (attrName == "FIELDS")
                        {
                            fieldsString.insert(0, attr->Value());
                        }
                        else if (attrName == "SHAPE")
                        {
                            shapeString.insert(0, attr->Value());
                        }
                        else if (attrName == "BASIS")
                        {
                            basisString.insert(0, attr->Value());
                        }
                        else if (attrName == "HOMOGENEOUSLENGTHS")
                        {
                            homoLengthsString.insert(0,attr->Value());
                        }
                        else if (attrName == "HOMOGENEOUSZIDS")
                        {
                            homoZIDsString.insert(0,attr->Value());
                        }
                        else if (attrName == "HOMOGENEOUSYIDS")
                        {
                            homoYIDsString.insert(0,attr->Value());
                        }
                        else if (attrName == "NUMMODESPERDIR")
                        {
                            numModesString.insert(0, attr->Value());
                        }
                        else if (attrName == "ID")
                        {
                            idString.insert(0, attr->Value());
                        }
                        else if (attrName == "POINTSTYPE")
                        {
                            pointsString.insert(0, attr->Value());
                            pointDef = true;
                        }
                        else if (attrName == "NUMPOINTSPERDIR")
                        {
                            numPointsString.insert(0, attr->Value());
                            numPointDef = true;
                        }
776
777
778
                        else if (attrName == "COMPRESSED")
                        {
                            if(!boost::iequals(attr->Value(),
Chris Cantwell's avatar
Chris Cantwell committed
779
                                            CompressData::GetCompressString()))
780
                            {
Chris Cantwell's avatar
Chris Cantwell committed
781
782
                                WARNINGL0(false, "Compressed formats do not "
                                          "match. Expected: "
783
784
                                          + CompressData::GetCompressString()
                                          + " but got "+ string(attr->Value()));
785
786
                            }
                        }
787
                        else if (attrName =="BITSIZE")
788
                        {
789
790
791
792
                            // This information is for future
                            // compatibility issues, for exmaple in
                            // case we end up using a 128 bit machine.
                            // Currently just do nothing
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
819
820
821
822
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
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
                        else
                        {
                            std::string errstr("Unknown attribute: ");
                            errstr += attrName;
                            ASSERTL1(false, errstr.c_str());
                        }

                        // Get the next attribute.
                        attr = attr->Next();
                    }

                    // Check to see if homogeneous expansion and if so
                    // strip down the shapeString definition
                    int numHomoDir = 0;
                    size_t loc;
                    //---> This finds the first location of  'n'!
                    if((loc = shapeString.find_first_of("-"))!=string::npos)
                    {
                        if(shapeString.find("Exp1D")!=string::npos)
                        {
                            numHomoDir = 1;
                        }
                        else // HomogeneousExp1D
                        {
                            numHomoDir = 2;
                        }

                        shapeString.erase(loc,shapeString.length());
                    }

                    // Reconstruct the fielddefs.
                    std::vector<unsigned int> elementIds;
                    {
                        bool valid = ParseUtils::GenerateSeqVector(idString.c_str(), elementIds);
                        ASSERTL0(valid, "Unable to correctly parse the element ids.");
                    }

                    // Get the geometrical shape
                    ShapeType shape;
                    bool valid = false;
                    for (unsigned int j = 0; j < SIZE_ShapeType; j++)
                    {
                        if (ShapeTypeMap[j] == shapeString)
                        {
                            shape = (ShapeType) j;
                            valid = true;
                            break;
                        }
                    }

                    ASSERTL0(valid, std::string("Unable to correctly parse the shape type: ").append(shapeString).c_str());

                    // Get the basis
                    std::vector<std::string> basisStrings;
                    std::vector<BasisType> basis;
                    valid = ParseUtils::GenerateOrderedStringVector(basisString.c_str(), basisStrings);
                    ASSERTL0(valid, "Unable to correctly parse the basis types.");
                    for (std::vector<std::string>::size_type i = 0; i < basisStrings.size(); i++)
                    {
                        valid = false;
                        for (unsigned int j = 0; j < SIZE_BasisType; j++)
                        {
                            if (BasisTypeMap[j] == basisStrings[i])
                            {
                                basis.push_back((BasisType) j);
                                valid = true;
                                break;
                            }
                        }
                        ASSERTL0(valid, std::string("Unable to correctly parse the basis type: ").append(basisStrings[i]).c_str());
                    }

                    // Get homoLengths
                    std::vector<NekDouble> homoLengths;
                    if(numHomoDir)
                    {
                        valid = ParseUtils::GenerateUnOrderedVector(homoLengthsString.c_str(), homoLengths);
                        ASSERTL0(valid, "Unable to correctly parse the number of homogeneous lengths.");
                    }
Spencer Sherwin's avatar
Spencer Sherwin committed
873
                    
Chris Cantwell's avatar
Chris Cantwell committed
874
875
876
                    // Get Homogeneous points IDs
                    std::vector<unsigned int> homoZIDs;
                    std::vector<unsigned int> homoYIDs;
Spencer Sherwin's avatar
Spencer Sherwin committed
877
                    
Chris Cantwell's avatar
Chris Cantwell committed
878
                    if(numHomoDir == 1)
879
880
881
882
                    {
                        valid = ParseUtils::GenerateSeqVector(homoZIDsString.c_str(), homoZIDs);
                        ASSERTL0(valid, "Unable to correctly parse homogeneous planes IDs.");
                    }
Spencer Sherwin's avatar
Spencer Sherwin committed
883
                    
Chris Cantwell's avatar
Chris Cantwell committed
884
885
886
                    if(numHomoDir == 2)
                    {
                        valid = ParseUtils::GenerateSeqVector(homoZIDsString.c_str(), homoZIDs);
887
                        ASSERTL0(valid, "Unable to correctly parse homogeneous lines IDs in z-direction.");
Chris Cantwell's avatar
Chris Cantwell committed
888
                        valid = ParseUtils::GenerateSeqVector(homoYIDsString.c_str(), homoYIDs);
889
                        ASSERTL0(valid, "Unable to correctly parse homogeneous lines IDs in y-direction.");
Chris Cantwell's avatar
Chris Cantwell committed
890
                    }
Spencer Sherwin's avatar
Spencer Sherwin committed
891
892
                    
                    
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
                    // Get points type
                    std::vector<PointsType> points;

                    if(pointDef)
                    {
                        std::vector<std::string> pointsStrings;
                        valid = ParseUtils::GenerateOrderedStringVector(pointsString.c_str(), pointsStrings);
                        ASSERTL0(valid, "Unable to correctly parse the points types.");
                        for (std::vector<std::string>::size_type i = 0; i < pointsStrings.size(); i++)
                        {
                            valid = false;
                            for (unsigned int j = 0; j < SIZE_PointsType; j++)
                            {
                                if (kPointsTypeStr[j] == pointsStrings[i])
                                {
                                    points.push_back((PointsType) j);
                                    valid = true;
                                    break;
                                }
                            }

                            ASSERTL0(valid, std::string("Unable to correctly parse the points type: ").append(pointsStrings[i]).c_str());
                        }
                    }

                    // Get numModes
                    std::vector<unsigned int> numModes;
                    bool UniOrder = false;

                    if(strstr(numModesString.c_str(),"UNIORDER:"))
                    {
                        UniOrder  = true;
                    }

                    valid = ParseUtils::GenerateOrderedVector(numModesString.c_str()+9, numModes);
                    ASSERTL0(valid, "Unable to correctly parse the number of modes.");

                    // Get numPoints
                    std::vector<unsigned int> numPoints;
                    if(numPointDef)
                    {
                        valid = ParseUtils::GenerateOrderedVector(numPointsString.c_str(), numPoints);
                        ASSERTL0(valid, "Unable to correctly parse the number of points.");
                    }

                    // Get fields names
                    std::vector<std::string> Fields;
                    valid = ParseUtils::GenerateOrderedStringVector(fieldsString.c_str(), Fields);
                    ASSERTL0(valid, "Unable to correctly parse the number of fields.");

                    FieldDefinitionsSharedPtr fielddef  = MemoryManager<FieldDefinitions>::AllocateSharedPtr(shape, elementIds, basis, UniOrder, numModes, Fields, numHomoDir, homoLengths, homoZIDs, homoYIDs, points, pointDef, numPoints, numPointDef);
Chris Cantwell's avatar
Chris Cantwell committed
944

945
946
947
948
949
950
951
952
953
954
955
956
                    fielddefs.push_back(fielddef);

                    element = element->NextSiblingElement("ELEMENTS");
                }
                loopXml = loopXml->NextSiblingElement(strLoop);
            }
        }


        /**
         *
         */
957
        void FieldIO::ImportFieldData(TiXmlDocument &doc, const std::vector<FieldDefinitionsSharedPtr> &fielddefs, std::vector<std::vector<NekDouble> > &fielddata)
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
        {
            int cntdumps = 0;

            TiXmlHandle docHandle(&doc);
            TiXmlElement* master = NULL;    // Master tag within which all data is contained.

            master = doc.FirstChildElement("NEKTAR");
            ASSERTL0(master, "Unable to find NEKTAR tag in file.");

            // Loop through all nektar tags, finding all of the element tags.
            while (master)
            {
                TiXmlElement* element = master->FirstChildElement("ELEMENTS");
                ASSERTL0(element, "Unable to find ELEMENTS tag within nektar tag.");
                while (element)
                {
                    // Extract the body, which the "data".
                    TiXmlNode* elementChild = element->FirstChild();
                    ASSERTL0(elementChild, "Unable to extract the data from the element tag.");
                    std::string elementStr;
                    while(elementChild)
                    {
Dave Moxey's avatar
Dave Moxey committed
980
                        if (elementChild->Type() == TiXmlNode::TINYXML_TEXT)
981
982
983
984
985
986
                        {
                            elementStr += elementChild->ToText()->ValueStr();
                        }
                        elementChild = elementChild->NextSibling();
                    }

987
                    std::vector<NekDouble> elementFieldData;
988
                    // Convert from base64 to binary.
989

990
991
992
                    const char *CompressStr = element->Attribute("COMPRESSED");
                    if(CompressStr)
                    {
Chris Cantwell's avatar
Chris Cantwell committed
993
994
                        if(!boost::iequals(CompressStr,
                                           CompressData::GetCompressString()))
995
                        {
Chris Cantwell's avatar
Chris Cantwell committed
996
997
                            WARNINGL0(false, "Compressed formats do not match. "
                                      "Expected: "
998
999
                                      + CompressData::GetCompressString()
                                      + " but got "+ string(CompressStr));
1000
1001
1002
                        }
                    }

1003
                    ASSERTL0(Z_OK == CompressData::ZlibDecodeFromBase64Str(
Chris Cantwell's avatar
Chris Cantwell committed
1004
                                                        elementStr,
1005
1006
1007
                                                        elementFieldData),
                             "Failed to decompress field data.");

1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022

                    fielddata.push_back(elementFieldData);

                    int datasize = CheckFieldDefinition(fielddefs[cntdumps]);
                    ASSERTL0(fielddata[cntdumps].size() == datasize*fielddefs[cntdumps]->m_fields.size(),"Input data is not the same length as header infoarmation");

                    cntdumps++;

                    element = element->NextSiblingElement("ELEMENTS");
                }
                master = master->NextSiblingElement("NEKTAR");
            }
        }


1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
        /**
         * \brief add information about provenance and fieldmetadata
         */
        void FieldIO::AddInfoTag(TiXmlElement * root,
                             const FieldMetaDataMap &fieldmetadatamap)
        {
            FieldMetaDataMap ProvenanceMap;

            // Nektar++ release version from VERSION file
            ProvenanceMap["NektarVersion"] = string(NEKTAR_VERSION);

            // Date/time stamp
            ptime::time_facet *facet = new ptime::time_facet("%d-%b-%Y %H:%M:%S");
            std::stringstream wss;
            wss.imbue(locale(wss.getloc(), facet));
            wss << ptime::second_clock::local_time();
            ProvenanceMap["Timestamp"] = wss.str();

            // Hostname
            boost::system::error_code ec;
            ProvenanceMap["Hostname"] = ip::host_name(ec);

            // Git information
            // If built from a distributed package, do not include this
Dave Moxey's avatar
Dave Moxey committed
1047
            if (NekConstants::kGitSha1 != "GITDIR-NOTFOUND")
1048
            {
Dave Moxey's avatar
Dave Moxey committed
1049
1050
                ProvenanceMap["GitSHA1"]   = NekConstants::kGitSha1;
                ProvenanceMap["GitBranch"] = NekConstants::kGitBranch;
1051
            }
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
1085
1086
1087
1088
1089
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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143

            TiXmlElement * infoTag = new TiXmlElement("Metadata");
            root->LinkEndChild(infoTag);

            TiXmlElement * v;
            FieldMetaDataMap::const_iterator infoit;

            TiXmlElement * provTag = new TiXmlElement("Provenance");
            infoTag->LinkEndChild(provTag);
            for (infoit = ProvenanceMap.begin(); infoit != ProvenanceMap.end(); ++infoit)
            {
                v = new TiXmlElement( (infoit->first).c_str() );
                v->LinkEndChild(new TiXmlText((infoit->second).c_str()));
                provTag->LinkEndChild(v);
            }

            //---------------------------------------------
            // write field info section
            if(fieldmetadatamap != NullFieldMetaDataMap)
            {
                for(infoit = fieldmetadatamap.begin(); infoit != fieldmetadatamap.end(); ++infoit)
                {
                    v = new TiXmlElement( (infoit->first).c_str() );
                    v->LinkEndChild(new TiXmlText((infoit->second).c_str()));
                    infoTag->LinkEndChild(v);
                }
            }
        }


        /**
         *
         */
        void FieldIO::GenerateSeqString(const std::vector<unsigned int> &elmtids,
                                      std::string &idString)
        {
            std::stringstream idStringStream;
            bool setdash = true;
            unsigned int endval;

            idStringStream << elmtids[0];
            for (int i = 1; i < elmtids.size(); ++i)
            {
                if(elmtids[i] == elmtids[i-1]+1)
                {
                    if(setdash)
                    {
                        idStringStream << "-";
                        setdash = false;
                    }

                    if(i == elmtids.size()-1) // last element
                    {
                        idStringStream << elmtids[i];
                    }
                    else
                    {
                        endval = elmtids[i];
                    }
                }
                else
                {
                    if(setdash == false) // finish off previous dash sequence
                    {
                        idStringStream << endval;
                        setdash = true;
                    }


                    idStringStream << "," << elmtids[i];
                }
            }
            idString = idStringStream.str();
        }


        /**
         *
         */
        std::string FieldIO::SetUpOutput(const std::string outname,
                const std::vector<FieldDefinitionsSharedPtr>& fielddefs,
                const FieldMetaDataMap &fieldmetadatamap)
        {
            ASSERTL0(!outname.empty(), "Empty path given to SetUpOutput()");

            int nprocs = m_comm->GetSize();
            int rank   = m_comm->GetRank();

            // Directory name if in parallel, regular filename if in serial
            fs::path specPath (outname);

            // Remove any existing file which is in the way
1144
            if(m_comm->RemoveExistingFiles())
1145
            {
1146
1147
                try
                {
1148
1149
1150
1151
1152
1153
                    if (rank == 0)
                    {
                        fs::remove_all(specPath);
                    }

                    m_comm->Block();
1154
1155
1156
1157
1158
1159
                }
                catch (fs::filesystem_error& e)
                {
                    ASSERTL0(e.code().value() == berrc::no_such_file_or_directory,
                             "Filesystem error: " + string(e.what()));
                }
1160
1161
1162
1163
1164
            }

            // serial processing just add ending.
            if(nprocs == 1)
            {
Gianmarco Mengaldo's avatar
Gianmarco Mengaldo committed
1165
                cout << "Writing: " << specPath << endl;
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
                return LibUtilities::PortablePath(specPath);
            }

            // Compute number of elements on this process and share with other
            // processes. Also construct list of elements on this process from
            // available vector of field definitions.
            std::vector<unsigned int> elmtnums(nprocs,0);
            std::vector<unsigned int> idlist;
            int i;
            for (i = 0; i < fielddefs.size(); ++i)
            {
                elmtnums[rank] += fielddefs[i]->m_elementIDs.size();
                idlist.insert(idlist.end(), fielddefs[i]->m_elementIDs.begin(),
                                            fielddefs[i]->m_elementIDs.end());
            }
            m_comm->AllReduce(elmtnums,LibUtilities::ReduceMax);

1183
            // Create the destination directory
1184
1185
            try
            {
1186
1187
1188
1189
1190
1191
                if (rank == 0)
                {
                    fs::create_directory(specPath);
                }

                m_comm->Block();
1192
1193
1194
1195
1196
            }
            catch (fs::filesystem_error& e)
            {
                ASSERTL0(false, "Filesystem error: " + string(e.what()));
            }
1197

1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
            // Collate per-process element lists on root process to generate
            // the info file.
            if (rank == 0)
            {
                std::vector<std::vector<unsigned int> > ElementIDs(nprocs);

                // Populate the list of element ID lists from all processes
                ElementIDs[0] = idlist;
                for (i = 1; i < nprocs; ++i)
                {
                    std::vector<unsigned int> tmp(elmtnums[i]);
                    m_comm->Recv(i, tmp);
                    ElementIDs[i] = tmp;
                }

                // Set up output names
                std::vector<std::string> filenames;
                for(int i = 0; i < nprocs; ++i)
                {
                    boost::format pad("P%1$07d.fld");
                    pad % i;
                    filenames.push_back(pad.str());
                }

                // Write the Info.xml file
Chris Cantwell's avatar
Chris Cantwell committed
1223
1224
                string infofile = LibUtilities::PortablePath(
                                            specPath / fs::path("Info.xml"));
1225
1226

                cout << "Writing: " << specPath << endl;
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
                WriteMultiFldFileIDs(infofile, filenames, ElementIDs,
                                     fieldmetadatamap);
            }
            else
            {
                // Send this process's ID list to the root process
                m_comm->Send(0, idlist);
            }

            // Pad rank to 8char filenames, e.g. P0000000.fld
            boost::format pad("P%1$07d.fld");
            pad % m_comm->GetRank();

            // Generate full path name
            fs::path poutfile(pad.str());
            fs::path fulloutname = specPath / poutfile;

            // Return the full path to the partition for this process
            return LibUtilities::PortablePath(fulloutname);
        }

1248
1249
1250
        /**
         *
         */
1251
        int FieldIO::CheckFieldDefinition(const FieldDefinitionsSharedPtr &fielddefs)
1252
1253
        {
            int i;
1254
1255
1256
1257
1258
1259

            if(fielddefs->m_elementIDs.size() == 0) // empty partition
            {
                return 0;
            }
            //ASSERTL0(fielddefs->m_elementIDs.size() > 0, "Fielddefs vector must contain at least one element of data .");
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271

            unsigned int numbasis = 0;

            // Determine nummodes vector lists are correct length
            switch(fielddefs->m_shapeType)
            {
            case eSegment:
                numbasis = 1;
                if(fielddefs->m_numHomogeneousDir)
                {
                    numbasis += fielddefs->m_numHomogeneousDir;
                }
Chris Cantwell's avatar
Chris Cantwell committed
1272

1273
                break;
Chris Cantwell's avatar
Chris Cantwell committed
1274
            case eTriangle:
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
            case eQuadrilateral:
                if(fielddefs->m_numHomogeneousDir)
                {
                    numbasis = 3;
                }
                else
                {
                    numbasis = 2;
                }
                break;
            case eTetrahedron:
            case ePyramid:
            case ePrism:
            case eHexahedron:
                numbasis = 3;
                break;
            default:
                ASSERTL0(false, "Unsupported shape type.");
                break;
            }
Chris Cantwell's avatar
Chris Cantwell committed
1295

1296
            unsigned int datasize = 0;
Chris Cantwell's avatar
Chris Cantwell committed
1297

1298
1299
1300
1301
1302
1303
1304
1305
1306
            ASSERTL0(fielddefs->m_basis.size() == numbasis, "Length of basis vector is incorrect");

            if(fielddefs->m_uniOrder == true)
            {
                unsigned int cnt = 0;
                // calculate datasize
                switch(fielddefs->m_shapeType)
                {
                case eSegment:
1307
1308
                {
                    int l = fielddefs->m_numModes[cnt++];
1309
1310
                    if(fielddefs->m_numHomogeneousDir == 1)
                    {
1311
                        datasize += l*fielddefs->m_numModes[cnt++];
1312
1313
1314
                    }
                    else if(fielddefs->m_numHomogeneousDir == 2)
                    {
1315
1316
                        int m = fielddefs->m_numModes[cnt++];
                        datasize += l*m*fielddefs->m_numModes[cnt++];
1317
1318
1319
                    }
                    else
                    {
1320
                        datasize += l;
1321
                    }
1322
1323
                }
                break;
1324
1325
1326
1327
                case eTriangle:
                {
                    int l = fielddefs->m_numModes[cnt++];
                    int m = fielddefs->m_numModes[cnt++];
Chris Cantwell's avatar
Chris Cantwell committed
1328

1329
1330
                    if(fielddefs->m_numHomogeneousDir == 1)
                    {
1331
1332
                        datasize += StdTriData::getNumberOfCoefficients(l,m)*
                                    fielddefs->m_homogeneousZIDs.size();
1333
1334
1335
1336
1337
1338
1339
1340
1341
                    }
                    else
                    {
                        datasize += StdTriData::getNumberOfCoefficients(l,m);
                    }
                }
                break;
                case eQuadrilateral:
                    {
1342
1343
                        int l = fielddefs->m_numModes[cnt++];
                        int m = fielddefs->m_numModes[cnt++];
1344
1345
                        if(fielddefs->m_numHomogeneousDir == 1)
                        {
1346
                            datasize += l*m*fielddefs->m_homogeneousZIDs.size();
1347
1348
1349
                        }
                        else
                        {
1350
1351
                            datasize += l*m;
                        }
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
                    }
                    break;
                case eTetrahedron:
                    {
                        int l = fielddefs->m_numModes[cnt++];
                        int m = fielddefs->m_numModes[cnt++];
                        int n = fielddefs->m_numModes[cnt++];
                        datasize += StdTetData::getNumberOfCoefficients(l,m,n);
                    }
                    break;
                case ePyramid:
                    {
                        int l = fielddefs->m_numModes[cnt++];
                        int m = fielddefs->m_numModes[cnt++];
                        int n = fielddefs->m_numModes[cnt++];
                        datasize += StdPyrData::getNumberOfCoefficients(l,m,n);
                    }
                    break;
                case  ePrism:
                    {
                        int l = fielddefs->m_numModes[cnt++];
                        int m = fielddefs->m_numModes[cnt++];
                        int n = fielddefs->m_numModes[cnt++];
                        datasize += StdPrismData::getNumberOfCoefficients(l,m,n);
                    }
                    break;
                case eHexahedron:
1379
1380
1381
1382
1383
1384
                    {
                        int l = fielddefs->m_numModes[cnt++];
                        int m = fielddefs->m_numModes[cnt++];
                        int n = fielddefs->m_numModes[cnt++];
                        datasize += l*m*n;
                    }
1385
1386
1387
1388
1389
                    break;
                default:
                    ASSERTL0(false, "Unsupported shape type.");
                    break;
                }
Chris Cantwell's avatar
Chris Cantwell committed
1390

1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
                datasize *= fielddefs->m_elementIDs.size();
            }
            else
            {
                unsigned int cnt = 0;
                // calculate data length
                for(i = 0; i < fielddefs->m_elementIDs.size(); ++i)
                {
                    switch(fielddefs->m_shapeType)
                    {
                    case eSegment:
Chris Cantwell's avatar
Chris Cantwell committed
1402
                        {
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
                            int l = fielddefs->m_numModes[cnt++];
                            if(fielddefs->m_numHomogeneousDir == 1)
                            {
                                datasize += l*fielddefs->m_numModes[cnt++];
                            }
                            else if(fielddefs->m_numHomogeneousDir == 2)
                            {
                                int m = fielddefs->m_numModes[cnt++];
                                datasize += l*m*fielddefs->m_numModes[cnt++];
                            }
                            else
                            {
                                datasize += l;
                            }
Chris Cantwell's avatar
Chris Cantwell committed
1417
                        }
1418
1419
1420
1421
                        break;
                    case eTriangle:
                        {
                            int l = fielddefs->m_numModes[cnt++];