XdmfHDF5Writer.cpp 61.3 KB
Newer Older
Kenneth Leiter's avatar
Kenneth Leiter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfHDF5Writer.cpp                                                  */
/*                                                                           */
/*  Author:                                                                  */
/*     Kenneth Leiter                                                        */
/*     kenneth.leiter@arl.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2011 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/
23

24
#include <hdf5.h>
25
#include <sstream>
26
#include <cstdio>
27
#include <cmath>
28
#include <set>
29
#include <list>
30
#include "XdmfItem.hpp"
31
#include "XdmfArray.hpp"
32
#include "XdmfArrayType.hpp"
33
#include "XdmfError.hpp"
34
#include "XdmfHDF5Controller.hpp"
35
#include "XdmfHDF5Writer.hpp"
36

37 38
namespace {

39
  const static unsigned int DEFAULT_CHUNK_SIZE = 1000;
40 41 42

}

43 44 45
/**
 * PIMPL
 */
46
class XdmfHDF5Writer::XdmfHDF5WriterImpl  {
47 48 49 50

public:

  XdmfHDF5WriterImpl():
51
    mHDF5Handle(-1),
52
    mChunkSize(DEFAULT_CHUNK_SIZE),
53
    mOpenFile(""),
54
    mDepth(0)
55 56 57 58 59 60 61 62 63 64 65 66
  {
  };

  ~XdmfHDF5WriterImpl()
  {
    closeFile();
  };

  void
  closeFile()
  {
    if(mHDF5Handle >= 0) {
67
      /*herr_t status =*/H5Fclose(mHDF5Handle);
68 69
      mHDF5Handle = -1;
    }
70
    mOpenFile = "";
71 72
  };  

73 74
  int
  openFile(const std::string & filePath,
75 76
           const int fapl,
           const int mDataSetId)
77 78 79 80 81 82 83 84 85 86 87
  {
    if(mHDF5Handle >= 0) {
      // Perhaps we should throw a warning.
      closeFile();
    }
    // Save old error handler and turn off error handling for now
    H5E_auto_t old_func;
    void * old_client_data;
    H5Eget_auto(0, &old_func, &old_client_data);
    H5Eset_auto2(0, NULL, NULL);
  
88
    int toReturn = 0;
89

90 91
    mOpenFile.assign(filePath);

92

93 94 95 96
    if(H5Fis_hdf5(filePath.c_str()) > 0) {
      mHDF5Handle = H5Fopen(filePath.c_str(), 
                            H5F_ACC_RDWR, 
                            fapl);
97 98 99 100 101 102 103 104 105
      if(mDataSetId == 0) {
        hsize_t numObjects;
        /*herr_t status = */H5Gget_num_objs(mHDF5Handle,
                                            &numObjects);
        toReturn = numObjects;
      }
      else {
        toReturn = mDataSetId;
      }
106 107
    }
    else {
108
      // This is where it currently fails
109 110 111 112 113 114 115 116 117
      mHDF5Handle = H5Fcreate(filePath.c_str(),
                              H5F_ACC_TRUNC,
                              H5P_DEFAULT,
                              fapl);
    }

    // Restore previous error handler
    H5Eset_auto2(0, old_func, old_client_data);

118 119
    return toReturn;

120 121 122
  }

  hid_t mHDF5Handle;
123
  unsigned int mChunkSize;
124
  std::string mOpenFile;
125 126
  int mDepth;
  std::set<const XdmfItem *> mWrittenItems;
127
};
128

129
shared_ptr<XdmfHDF5Writer>
130 131
XdmfHDF5Writer::New(const std::string & filePath,
                    const bool clobberFile)
132
{
133 134 135
  if(clobberFile) {
    std::remove(filePath.c_str());
  }
136
  shared_ptr<XdmfHDF5Writer> p(new XdmfHDF5Writer(filePath));
137
  return p;
138 139
}

140
XdmfHDF5Writer::XdmfHDF5Writer(const std::string & filePath) :
141
  XdmfHeavyDataWriter(filePath, 1, 800),
142
  mImpl(new XdmfHDF5WriterImpl())
143 144 145 146 147
{
}

XdmfHDF5Writer::~XdmfHDF5Writer()
{
148
  delete mImpl;
149 150
}

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 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 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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 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 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 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 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 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 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
void
XdmfHDF5Writer::controllerSplitting(XdmfArray & array,
                                    const int & fapl,
                                    int & controllerIndexOffset,
                                    shared_ptr<XdmfHeavyDataController> heavyDataController,
                                    const std::string & checkFileName,
                                    const std::string & checkFileExt,
                                    const std::string & dataSetPath,
                                    const std::vector<unsigned int> & dimensions,
                                    const std::vector<unsigned int> & dataspaceDimensions,
                                    const std::vector<unsigned int> & start,
                                    const std::vector<unsigned int> & stride,
                                    std::list<std::string> & filesWritten,
                                    std::list<void *> & arraysWritten,
                                    std::list<std::vector<unsigned int> > & startsWritten,
                                    std::list<std::vector<unsigned int> > & stridesWritten,
                                    std::list<std::vector<unsigned int> > & dimensionsWritten,
                                    std::list<std::vector<unsigned int> > & dataSizesWritten,
                                    std::list<unsigned int> & arrayOffsetsWritten)
{
  // This is the file splitting algorithm
  if (getFileSizeLimit() > 0) {
    // Only if the file limit is positive, disabled if 0 or negative
    unsigned int previousDataSize = 0;

    std::vector<unsigned int> previousDimensions;
    std::vector<unsigned int> previousDataSizes;
    unsigned int amountAlreadyWritten = 0;
    // Even though theoretically this could be an infinite loop
    // if all possible files with the specified name are produced
    // the chances of that happening are small.
    // It can handle up to 65535 different files.
    // This value may vary depending on the compiler and platform.
    // The variable UINT_MAX holds the value in question.
    // If all files are take up it will loop until a file opens up
    // since adding past the max causes overflow.

    unsigned int containedInController = 1;
    for (unsigned int j = 0; j < dataspaceDimensions.size(); ++j) {
      containedInController *= dataspaceDimensions[j];
    }
    int hyperslabSize = 0;
    while (amountAlreadyWritten < containedInController) {

      std::vector<unsigned int> partialStarts;
      std::vector<unsigned int> partialStrides;
      std::vector<unsigned int> partialDimensions;
      std::vector<unsigned int> partialDataSizes;

      std::stringstream testFile;
      if (getFileIndex() == 0) {
      // If sequentially named files need to be created or referenced
        testFile << checkFileName << "." << checkFileExt;
      }
      else {
        testFile << checkFileName << getFileIndex() << "." << checkFileExt;
      }
      FILE *checkFile = NULL;
      unsigned int fileSize = 0;
      // If the file doesn't exist the size is 0 because there's no data
      // Get the file stream
      checkFile = fopen(testFile.str().c_str(), "a");
      if (checkFile != NULL) {
        // Set the file pointer to end of file
        fseek(checkFile, 0, SEEK_END);
        // Get the file size, in bytes
        fileSize = ftell(checkFile);

        // If overwrite subtract previous data size.
        if (mMode == Overwrite || mMode == Hyperslab) {
          // Find previous data size
          int checkfilesize = getDataSetSize(testFile.str(), dataSetPath, fapl);
          if (checkfilesize < 0) {
            checkfilesize = 0;
          }
          unsigned int checksize = (unsigned int)checkfilesize;
          if (mMode == Overwrite) {
            if (checksize > fileSize) {
              fileSize = 0;
            }
            else {
              fileSize = fileSize - checksize;
              // Remove previous set's size, since it's overwritten
            }
            if (fileSize == 0) {
              fileSize += getFileOverhead();
            }
          }
          else if (mMode == Hyperslab) {
            hyperslabSize = checksize;
          }
        }
        if (fileSize == 0) {
          fileSize += getFileOverhead();
        }
        fclose(checkFile);
      }
      else if (previousDataSize == 0) {
        fileSize += getFileOverhead();
      }

      //Start of splitting section

      // If needed split the written array
      // into smaller arrays based on dimension blocks
      // Working with strings has a more
      // resource intensive version of this algorithm
      // Size needed is equal to the dataspaceDimensions if in hyperslab mode
      // otherwise is equal to the size of the written array
      unsigned int remainingSize = 0;
      unsigned int dataItemSize = 1;
      if (array.getArrayType() == XdmfArrayType::String()) {
        unsigned int remainingValues = 0;
        unsigned int sizeArrayIndex = 0;
        if (mMode == Hyperslab) {
          remainingValues += 1;
          sizeArrayIndex += 1;
          for (unsigned int j = 0; j < dataspaceDimensions[j]; ++j) {
            remainingValues *= dataspaceDimensions[j];
            sizeArrayIndex *= dimensions[j];
          }
        }
        else {
          remainingValues += array.getSize();
          sizeArrayIndex = amountAlreadyWritten;
        }
        remainingValues -= amountAlreadyWritten;
        // Reduce by number of values already written
        if (remainingValues == 0) {
          // End if no remaining values
          break;
        }
        // If remaining size is less than available space, just write all of what's left
        // Calculate remaining size
        for (unsigned int j = sizeArrayIndex; j < array.getSize(); ++j) {
          remainingSize +=
            (unsigned int)((double)(array.getValue<std::string>(j).size()) *
                           8.0 * mCompressionRatio);
        }
        if (mMode == Hyperslab) {
          // Size is estimated based on averages
          remainingSize = (remainingSize /
                           (array.getSize() - sizeArrayIndex)) *
                           remainingValues;
        }
      }
      else {
        unsigned int remainingValues = 0;
        if (mMode == Hyperslab) {
          remainingValues += 1;
          for (unsigned int j = 0; j < dataspaceDimensions.size(); ++j) {
            remainingValues *= dataspaceDimensions[j];
          }
        }
        else {
          remainingValues += 1;
          for (unsigned int j = 0; j < dimensions.size(); ++j) {
            remainingValues *= dimensions[j];
          }
        }
        if ((int)remainingValues - (int) amountAlreadyWritten < 0) {
          remainingValues = 0;
        }
        else {
          remainingValues -= amountAlreadyWritten;
        }
        // Reduce by number of values already written
        if (remainingValues == 0) {//end if no remaining values
          break;
        }
        dataItemSize =
          (unsigned int)((double) (array.getArrayType()->getElementSize()) *
                         mCompressionRatio);
        // If remaining size is less than available space, just write all of what's left
        remainingSize = remainingValues * dataItemSize;
      }
      if (remainingSize + previousDataSize + fileSize
          < (unsigned int)getFileSizeLimit()*(1024*1024)) {
        // If the array hasn't been split
        if (amountAlreadyWritten == 0) {
          // Just pass all data to the partial vectors
          for (unsigned int j = 0; j < dimensions.size(); ++j) {
            // Done using a loop so that data is copied, not referenced
            partialStarts.push_back(start[j]);
            partialStrides.push_back(stride[j]);
            partialDimensions.push_back(dimensions[j]);
            partialDataSizes.push_back(dataspaceDimensions[j]);
          }
        }
        else {
          // If the array has been split
          int dimensionIndex = previousDimensions.size() - 1;
          // Loop previous dimensions in
          int j = 0;
          for (j = 0; j < dimensionIndex; ++j) {
            partialStarts.push_back(start[j]);
            partialStrides.push_back(stride[j]);
            partialDimensions.push_back(dimensions[j]);
            partialDataSizes.push_back(dataspaceDimensions[j]);
          }
          if (mMode == Hyperslab) {
            int newStart = (start[j] +
                            stride[j] * previousDimensions[j])
                           - previousDataSizes[j];
            while (newStart < 0) {
              newStart += stride[j];
            }
            partialStarts.push_back(newStart);
            // Stride should not change in this algorithm
            partialStrides.push_back(stride[j]);
            // Total up number of blocks for
            // the higher dimesions and subtract the amount already written
            unsigned int dimensiontotal = dimensions[j];
            unsigned int dataspacetotal = dataspaceDimensions[j];
            for (unsigned int k = j + 1; k < dimensions.size(); ++k) {
              dimensiontotal *= dimensions[k];
              dataspacetotal *= dataspaceDimensions[k];
            }
            if (previousDimensions.size() > 0) {
              partialDimensions.push_back(dimensiontotal-previousDimensions[j]);
            }
            else {
              partialDimensions.push_back(dimensiontotal);
            }
            if (previousDataSizes.size() > 0) {
              partialDataSizes.push_back(dataspacetotal-previousDataSizes[j]);
            }
            else {
              partialDataSizes.push_back(dataspacetotal);
            }
          }
          else {
            // Start and stride are not used outside of hyperslab
            partialStarts.push_back(start[j]);
            partialStrides.push_back(stride[j]);
            // Total up number of blocks for
            // the higher dimesions and subtract the amount already written
            // since it isn't hyperslab dimensions
            // and dataspacedimensions should be the same
            unsigned int dimensiontotal = dimensions[j];
            for (unsigned int k = j + 1; k < dimensions.size(); ++k) {
              dimensiontotal *= dimensions[k];
            }
            if (previousDimensions.size() > 0) {
              partialDimensions.push_back(dimensiontotal-previousDimensions[j]);
            }
            else {
              partialDimensions.push_back(dimensiontotal);
            }
            if (previousDataSizes.size() > 0) {
              partialDataSizes.push_back(dimensiontotal-previousDataSizes[j]);
            }
            else {
              partialDataSizes.push_back(dimensiontotal);
            }
          }
        }
      }
      else {
        // Otherwise, take remaining size
        // and start removing dimensions until the dimension block is less
        // then take a fraction of the dimension
        // Calculate the number of values of the data type you're using will fit
        unsigned int usableSpace = (getFileSizeLimit()*(1024*1024) -
                                    fileSize) / dataItemSize;
        if ((unsigned int)getFileSizeLimit()*(1024*1024) < previousDataSize + fileSize) {
          usableSpace = 0;
        }
        usableSpace += hyperslabSize-previousDataSize;
        // If the array hasn't been split
        if (amountAlreadyWritten == 0) {
          // See if it will fit in the next file
          // If it will just go to the next file
          // Otherwise split it.
          if (remainingSize + getFileOverhead() >
              (unsigned int)getFileSizeLimit()*(1024*1024)
              && usableSpace > 0) {
            if (getAllowSetSplitting()) {
              // Figure out the size of the largest block that will fit.
              unsigned int blockSizeSubtotal = 1;
              unsigned int dimensionIndex = 0;
              if (array.getArrayType() == XdmfArrayType::String()) {
                unsigned int dimensionSizeTotal = 1;
                unsigned int previousBlockSize = 0;
                // Find the dimension that was split
                while (dimensionIndex < dataspaceDimensions.size()
                       && blockSizeSubtotal <= usableSpace) {
                  // This is totally different for strings
                  dimensionSizeTotal *= dimensions[dimensionIndex];
                  previousBlockSize = blockSizeSubtotal;
                  blockSizeSubtotal = 0;
                  for (unsigned int k = 0; k < dimensionSizeTotal; ++k) {
                    if (amountAlreadyWritten + k > array.getSize()) {
                      XdmfError::message(XdmfError::FATAL,
                                         "Error: Invalid Dimension in HDF5 Write.\n");
                    }
                    blockSizeSubtotal +=
                      array.getValue<std::string>(amountAlreadyWritten + k).size();
                  }
                  dimensionIndex++;
                }
                // It should end on the "blockSizeSubtotal <= usableSpace" statement
                // the other half is for backup
                // move back one dimension so we're working
                // on the dimension that was split, not the one after it
                dimensionIndex--;
                blockSizeSubtotal = previousBlockSize;
              }
              else {
                // Find the dimension that was split
                while (dimensionIndex < dataspaceDimensions.size()
                       && blockSizeSubtotal <= usableSpace) {
                  blockSizeSubtotal *= dataspaceDimensions[dimensionIndex];
                  dimensionIndex++;
                }
                // It should end on the "blockSizeSubtotal <= arrayStartIndex" statement
                // the other half is for backup
                // Move back one dimension so we're working on the dimension that was split
                // not the one after it
                dimensionIndex--;
                blockSizeSubtotal /= dataspaceDimensions[dimensionIndex];
              }
              // Determine how many of those blocks will fit
              unsigned int numBlocks = usableSpace / blockSizeSubtotal;
              // This should be less than the current value for the dimension
              // Add dimensions as required.
              unsigned int j = 0;
              for (j = 0; j < dimensionIndex; ++j) {
                partialStarts.push_back(start[j]);
                partialStrides.push_back(stride[j]);
                partialDimensions.push_back(dimensions[j]);
                partialDataSizes.push_back(dataspaceDimensions[j]);
              }
              if (start[j] > numBlocks) {
                partialStarts.push_back(numBlocks-1);
              }
              else {
                partialStarts.push_back(start[j]);
              }
              partialStrides.push_back(stride[j]);
              partialDataSizes.push_back(numBlocks);
              if (dimensions[j] == dataspaceDimensions[j]) {
                // This is for non-hyperslab and specific cases of hyperslab
                partialDimensions.push_back(numBlocks);
              }
              else {
                // For hyperslab in general
                // Determine how many values from the array will fit
                // into the blocks being used with the dimensions specified
                unsigned int displacement = numBlocks / stride[j];
                if (((int)displacement * (int)stride[j])
                      + (start[j] % stride[j])
                    < numBlocks) {
                  displacement++;
                }
                displacement -= start[j]/stride[j];
                if (start[j] > numBlocks) {
                  displacement = 0;
                }
                if (dimensions[j] <= displacement) {
                  // If there are less values than there are space for
                  // just write all of them.
                  partialDimensions.push_back(dimensions[j]);
                }
                else {
                  // Otherwise write what space allows for
                  partialDimensions.push_back(displacement);
                }
              }
            }
            else {
              // Just pass all data to the partial vectors
              for (unsigned int j = 0; j < dimensions.size(); ++j) {
                // Done using a loop so that data is copied, not referenced
                partialStarts.push_back(start[j]);
                partialStrides.push_back(stride[j]);
                partialDimensions.push_back(dimensions[j]);
                partialDataSizes.push_back(dataspaceDimensions[j]);
              }
            }
          }
        }
        else {
          // If the array has been split
          // This case should not come up often
          // as it requires truly gigantic data sets
          // See if the remaining data will fit in the next file
          // If yes, skip to it
          // If no, split
          if (remainingSize + getFileOverhead() >
              (unsigned int)getFileSizeLimit()*(1024*1024)
              && usableSpace > 0) {
            // Figure out the size of the largest block that will fit.
            unsigned int blockSizeSubtotal = 1;
            unsigned int dimensionIndex = 0;
            if (array.getArrayType() == XdmfArrayType::String()) {
              unsigned int dimensionSizeTotal = 1;
              unsigned int previousBlockSize = 0;
              // Find the dimension that was split
              while (dimensionIndex < dataspaceDimensions.size()
                     && blockSizeSubtotal <= usableSpace) {
                // This is totally different for strings
                dimensionSizeTotal *= dimensions[dimensionIndex];
                previousBlockSize = blockSizeSubtotal;
                blockSizeSubtotal = 0;
                for (unsigned int k = 0; k < dimensionSizeTotal; ++k) {
                  if (amountAlreadyWritten + k > array.getSize()) {
                    XdmfError::message(XdmfError::FATAL,
                                       "Error: Invalid Dimension in HDF5 Write.\n");
                  }
                  blockSizeSubtotal +=
                    array.getValue<std::string>(amountAlreadyWritten + k).size();
                }
                dimensionIndex++;
              }
              // It should end on the "blockSizeSubtotal <= usableSpace" statement
              // the other half is for backup
              // move back one dimension so we're working
              // on the dimension that was split, not the one after it
              dimensionIndex--;
              blockSizeSubtotal = previousBlockSize;
            }
            else {
              // Find the dimension that was split
              while (dimensionIndex < dataspaceDimensions.size()
                     && blockSizeSubtotal <= usableSpace) {
                blockSizeSubtotal *= dataspaceDimensions[dimensionIndex];
                dimensionIndex++;
              }
              // It should end on the "blockSizeSubtotal <= arrayStartIndex" statement
              // the other half is for backup
              // Move back one dimension so we're working on the dimension that was split
              // not the one after it
              dimensionIndex--;
              blockSizeSubtotal /= dataspaceDimensions[dimensionIndex];
            }
            unsigned int j = 0;
            for (; j < dimensionIndex; ++j) {
              partialStarts.push_back(start[j]);
              partialStrides.push_back(stride[j]);
              partialDimensions.push_back(dimensions[j]);
              partialDataSizes.push_back(dataspaceDimensions[j]);
            }
            // Continue if the block is smaller than the available size
            if (blockSizeSubtotal <=usableSpace) {
             // Find number of blocks that will fit
              // This should be less than the current value for the dimension
              unsigned int numBlocks = usableSpace / blockSizeSubtotal;
              // Add dimensions to the partial vectors
              if (mMode == Hyperslab) {
                int newStart = (start[j] +
                                stride[j] * previousDimensions[j]) -
                               previousDataSizes[j];
                while (newStart < 0) {
                  newStart += stride[j];
                }
                partialStarts.push_back(newStart);
                // Stride should not change in this algorithm
                partialStrides.push_back(stride[j]);
                partialDataSizes.push_back(numBlocks);
                // Determine how many values from the array will fit
                // into the blocks being used
                // with the dimensions specified
                unsigned int displacement = (numBlocks - newStart)
                                            / stride[j];
                if (((int)displacement * (int)stride[j]) + (newStart % stride[j])
                    < numBlocks) {
                  displacement++;
                }
                displacement -= newStart/stride[j];
                if (newStart > (int)numBlocks) {
                  displacement = 0;
                }
                if ((dimensions[j] - previousDimensions[j]) <= displacement) {
                  // If there are less values than there are space for
                  // just write all of them.
                  partialDimensions.push_back(dimensions[j] - previousDimensions[j]);
                }
                else {
                  // Otherwise write what space allows for
                  partialDimensions.push_back(displacement);
                }
              }
              else {
                // Start and stride are only specified in hyperslab
                partialStarts.push_back(start[j]);
                partialStrides.push_back(stride[j]);
                partialDataSizes.push_back(numBlocks);
                partialDimensions.push_back(numBlocks);
              }
              // Place dimensions into previous dimensions
              // for later iterations
            }
            else {
              // If this is larger than usable space, try the next file
              // If moving to next file
              // just do nothing and pass out of the if statement
              // but also check if specified file size is too small
              if ((unsigned int)getFileSizeLimit()*(1024*1024)
                  < blockSizeSubtotal) {
                // This shouldn't ever trigger,
                // but it's good to cover ourselves
                // Throw an error if the block size won't work
                XdmfError::message(XdmfError::FATAL,
                                   "Error: Dimension Block size"
                                   " / Maximum File size mismatch.\n");
              }
            }
          }
        }
        // Move to next file
        setFileIndex(getFileIndex()+1);
      }

      if (partialDimensions.size() > 0) {
        // Building the array to be written
        int containedInDimensions = 1;
        // Count moved
        for (unsigned int j = 0 ; j < partialDimensions.size(); ++j) {
          containedInDimensions *= partialDimensions[j];
        }
        // Starting index
        int containedInPriorDimensions = controllerIndexOffset;
        int startOffset = 1;
        for (unsigned int j = 0; j < previousDimensions.size(); ++j) {
          startOffset *= previousDimensions[j];
        }
        if (previousDimensions.size() == 0) {
          startOffset = 0;
        }
        containedInPriorDimensions += startOffset;
        int dimensionTotal = 1;
        for (unsigned int j = 0; j < dimensions.size(); ++j) {
          dimensionTotal *= dimensions[j];
        }
        if (containedInDimensions > 0) {
          void * partialArray = NULL;
          if (array.getArrayType() == XdmfArrayType::Int8()) {
            partialArray =
              &(((char *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::Int16()) {
            partialArray =
              &(((short *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::Int32()) {
            partialArray =
              &(((int *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::Int64()) {
            partialArray =
              &(((long *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::Float32()) {
            partialArray =
              &(((float *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::Float64()) {
            partialArray =
              &(((double *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::UInt8()) {
            partialArray =
              &(((unsigned char *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::UInt16()) {
            partialArray =
              &(((unsigned short *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::UInt32()) {
            partialArray =
              &(((unsigned int *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          else if (array.getArrayType() == XdmfArrayType::String()) {
            partialArray =
              &(((std::string *)array.getValuesInternal())[containedInPriorDimensions]);
          }
          arraysWritten.push_back(partialArray);
          filesWritten.push_back(testFile.str());
          startsWritten.push_back(partialStarts);
          stridesWritten.push_back(partialStrides);
          dimensionsWritten.push_back(partialDimensions);
          dataSizesWritten.push_back(partialDataSizes);
          arrayOffsetsWritten.push_back(containedInPriorDimensions);
        }
        if (mMode == Hyperslab) {
          containedInPriorDimensions -= controllerIndexOffset;
        }
        if (containedInDimensions + containedInPriorDimensions == dimensionTotal) {
          controllerIndexOffset += dimensionTotal;
        }
        // For hyperslab the space is controlled by the dataspace dimensions
        // So use that since the dimensions should be equal
        // to the dataspace dimensions in all other variations
        // Total up written data space
        unsigned int writtenDataSpace = 1;
        for (unsigned int j = 0; j < partialDataSizes.size(); ++j) {
          writtenDataSpace *= partialDataSizes[j];
        }
        amountAlreadyWritten += writtenDataSpace;
        // Generate previous dimensions
        if (previousDataSizes.size() == 0) {
          previousDataSizes = partialDataSizes;
          previousDimensions = partialDimensions;
        }
        else {
          // Determine if the sizes match
          // If they do, add the top values together
          // Otherwise, compress the higher dimensions and then add them
          if (previousDimensions.size() == partialDimensions.size()) {
            previousDimensions[previousDimensions.size()-1] +=
              partialDimensions[previousDimensions.size()-1];
          }
          else if (previousDimensions.size() < partialDimensions.size()) {
            unsigned int overflowDimensions = 1;
            for (unsigned int j = previousDimensions.size() - 1;
                 j < partialDimensions.size();
                 ++j) {
              overflowDimensions *= partialDimensions[j];
            }
            previousDimensions[previousDimensions.size()-1] += overflowDimensions;
          }
          else if (previousDimensions.size() > partialDimensions.size()) {
            unsigned int overflowDimensions = 1;
            for (unsigned int j = partialDimensions.size() - 1;
                 j < previousDimensions.size();
                 ++j) {
              overflowDimensions *= previousDimensions[j];
            }
            previousDimensions.resize(partialDimensions.size());
            previousDimensions[partialDimensions.size()-1] = overflowDimensions;
            previousDimensions[previousDimensions.size()-1] +=
              partialDimensions[previousDimensions.size()-1];
          }
          if (previousDataSizes.size() == partialDataSizes.size()) {
            previousDataSizes[previousDataSizes.size()-1] +=
              partialDataSizes[previousDataSizes.size()-1];
          }
          else if (previousDataSizes.size() < partialDataSizes.size()) {
            unsigned int overflowDataSizes = 1;
            for (unsigned int j = previousDataSizes.size() - 1;
                 j < partialDataSizes.size();
                 ++j) {
              overflowDataSizes *= partialDataSizes[j];
            }
            previousDataSizes[previousDataSizes.size()-1] += overflowDataSizes;
          }
          else if (previousDataSizes.size() > partialDataSizes.size()) {
            unsigned int overflowDataSizes = 1;
            for (unsigned int j = partialDataSizes.size() - 1;
                 j < previousDataSizes.size();
                 ++j) {
              overflowDataSizes *= previousDataSizes[j];
            }
            previousDataSizes.resize(partialDataSizes.size());
            previousDataSizes[partialDataSizes.size()-1] = overflowDataSizes;
            previousDataSizes[previousDataSizes.size()-1] +=
              partialDataSizes[previousDataSizes.size()-1];
          }
        }
      }
    }

    if (mMode == Append) {
      // If the written filename is different write add the previous controller
      if (*(filesWritten.rbegin()) != heavyDataController->getFilePath()) {
        // Should also be different from previous controller
        if (filesWritten.size() > 1) {
          if (*(filesWritten.rbegin()) != *((filesWritten.rbegin())++)) {
            array.insert(heavyDataController);
          }
        }
        else {
          array.insert(heavyDataController);
        }
      }
    }
  }
  else {
    // Otherwise work with the full array
    void * partialArray = NULL;
    // Need to copy by duplicating the contents of the array
    unsigned int j = controllerIndexOffset;
    std::string writtenFileName = "";
    if (mMode == Default) {
      std::stringstream testFile;
      if (getFileIndex() == 0) {
        // If sequentially named files need to be created or referenced
        testFile << checkFileName << "." << checkFileExt;
      }
      else {
        testFile << checkFileName << getFileIndex() << "." << checkFileExt;
      }
      writtenFileName = testFile.str();
    }
    else {
      writtenFileName = heavyDataController->getFilePath();
    }

    if (array.getArrayType() == XdmfArrayType::Int8()){
      partialArray =
        &(((char *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::Int16()){
      partialArray =
        &(((short *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::Int32()){
      partialArray =
        &(((int *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::Int64()){
      partialArray =
        &(((long *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::Float32()){
      partialArray =
        &(((float *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::Float64()){
      partialArray =
        &(((double *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::UInt8()){
      partialArray =
        &(((unsigned char *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::UInt16()){
      partialArray =
        &(((unsigned short *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::UInt32()) {
      partialArray =
        &(((unsigned int *)array.getValuesInternal())[controllerIndexOffset]);
    }
    else if (array.getArrayType() == XdmfArrayType::String()) {
      partialArray =
        &(((std::string *)array.getValuesInternal())[controllerIndexOffset]);
    }
    arrayOffsetsWritten.push_back(controllerIndexOffset);
    // Set the offset to the point after the end of the current subset
    controllerIndexOffset = j;

    arraysWritten.push_back(partialArray);
    filesWritten.push_back(writtenFileName);
    // Also need to push the starts and strides loaded from the HeavyDataController
    startsWritten.push_back(start);
    stridesWritten.push_back(stride);
    dimensionsWritten.push_back(dimensions);
    dataSizesWritten.push_back(dataspaceDimensions);
  }
}

904 905
shared_ptr<XdmfHeavyDataController>
XdmfHDF5Writer::createController(const std::string & hdf5FilePath,
906
                                     const std::string & dataSetPath,
907
                                     const shared_ptr<const XdmfArrayType> type,
908 909
                                     const std::vector<unsigned int> & start,
                                     const std::vector<unsigned int> & stride,
910 911
                                     const std::vector<unsigned int> & dimensions,
                                     const std::vector<unsigned int> & dataspaceDimensions)
912
{
913 914 915 916 917 918 919
  return XdmfHDF5Controller::New(hdf5FilePath,
                                 dataSetPath,
                                 type,
                                 start,
                                 stride,
                                 dimensions,
                                 dataspaceDimensions);
920 921
}

922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
shared_ptr<XdmfHeavyDataController>
XdmfHDF5Writer::createController(const shared_ptr<XdmfHeavyDataController> & refController)
{
  if (shared_ptr<XdmfHDF5Controller> controller = shared_dynamic_cast<XdmfHDF5Controller>(refController)) {
    return createController(controller->getFilePath(),
                            controller->getDataSetPath(),
                            controller->getType(),
                            controller->getStart(),
                            controller->getStride(),
                            controller->getDimensions(),
                            controller->getDataspaceDimensions());
  }
  else {
    XdmfError::message(XdmfError::FATAL, "Error: Invalid Controller Conversion");
    return shared_ptr<XdmfHeavyDataController>();
  }
}

940 941
unsigned int
XdmfHDF5Writer::getChunkSize() const
942
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
943
  return mImpl->mChunkSize;
944 945 946
}

int
947
XdmfHDF5Writer::getDataSetSize(const std::string & fileName, const std::string & dataSetName, const int fapl)
948
{
949 950 951 952 953 954 955
  hid_t handle = -1;
  H5E_auto_t old_func;
  void * old_client_data;
  H5Eget_auto(0, &old_func, &old_client_data);
  H5Eset_auto2(0, NULL, NULL);
  if (fileName !=  mImpl->mOpenFile) {
    // Save old error handler and turn off error handling for now
956

957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    if(H5Fis_hdf5(fileName.c_str()) > 0) {
      handle = H5Fopen(fileName.c_str(),
                       H5F_ACC_RDWR,
                       fapl);
    }
    else {
      // This is where it currently fails
      handle = H5Fcreate(fileName.c_str(),
                         H5F_ACC_TRUNC,
                         H5P_DEFAULT,
                         fapl);
    }
  }
  else {
    handle = mImpl->mHDF5Handle;
  }
973

974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
  // Restore previous error handler
  H5Eset_auto2(0, old_func, old_client_data);

  hid_t checkset = H5Dopen(handle,
                           dataSetName.c_str(),
                           H5P_DEFAULT);
  hid_t checkspace = H5S_ALL;
  checkspace = H5Dget_space(checkset);
  hssize_t checksize = H5Sget_simple_extent_npoints(checkspace);
  herr_t status = H5Dclose(checkset);
  if(checkspace != H5S_ALL) {
    status = H5Sclose(checkspace);
  }
  if (handle != mImpl->mHDF5Handle) {
    H5Fclose(handle);
  }
  return checksize;
991 992
}

993 994 995
void 
XdmfHDF5Writer::closeFile()
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
996
  mImpl->closeFile();
997 998 999 1000 1001
}

void 
XdmfHDF5Writer::openFile()
{
1002 1003 1004 1005 1006 1007
  this->openFile(H5P_DEFAULT);
}

void
XdmfHDF5Writer::openFile(const int fapl)
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1008 1009 1010
  mDataSetId = mImpl->openFile(mFilePath,
                               fapl,
                               mDataSetId);
1011 1012
}

1013 1014 1015
void
XdmfHDF5Writer::setChunkSize(const unsigned int chunkSize)
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1016
  mImpl->mChunkSize = chunkSize;
1017 1018
}

1019 1020
void
XdmfHDF5Writer::visit(XdmfArray & array,
1021
                      const shared_ptr<XdmfBaseVisitor> visitor)
1022
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1023 1024 1025 1026 1027 1028 1029 1030 1031
  mImpl->mDepth++;
  std::set<const XdmfItem *>::iterator checkWritten = mImpl->mWrittenItems.find(&array);
  if (checkWritten == mImpl->mWrittenItems.end() || array.getItemTag() == "DataItem") {
    // If it has children send the writer to them too.
    array.traverse(visitor);
    if (array.isInitialized()) {
      // Only do this if the object has not already been written
      this->write(array, H5P_DEFAULT);
      mImpl->mWrittenItems.insert(&array);
1032
    }
1033
  }
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1034 1035 1036 1037
  // If the object has already been written, just end, it already has the data
  mImpl->mDepth--;
  if(mImpl->mDepth <= 0) {
    mImpl->mWrittenItems.clear();
1038 1039 1040
  }
}

1041

1042 1043 1044 1045
void
XdmfHDF5Writer::visit(XdmfItem & item,
                      const shared_ptr<XdmfBaseVisitor> visitor)
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1046 1047 1048 1049 1050 1051 1052 1053
  mImpl->mDepth++;
  // This is similar to the algorithm for writing XPaths
  // shouldn't be a problem if XPaths are turned off because all this does is avoid writing an object twice
  // if it was written once then all instances of the object should have the controller
  std::set<const XdmfItem *>::iterator checkWritten = mImpl->mWrittenItems.find(&item);
  if (checkWritten == mImpl->mWrittenItems.end()) {
    mImpl->mWrittenItems.insert(&item);
    item.traverse(visitor);
1054
  }
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1055 1056 1057
  mImpl->mDepth--;
  if(mImpl->mDepth <= 0) {
    mImpl->mWrittenItems.clear();
1058
  }
1059 1060
}

1061

1062 1063 1064
void
XdmfHDF5Writer::write(XdmfArray & array,
                      const int fapl)
1065
{
1066
  hid_t datatype = -1;
Kenneth Leiter's avatar
Kenneth Leiter committed
1067
  bool closeDatatype = false;
1068

1069
  // Determining data type
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
  if(array.isInitialized()) {
    if(array.getArrayType() == XdmfArrayType::Int8()) {
      datatype = H5T_NATIVE_CHAR;
    }
    else if(array.getArrayType() == XdmfArrayType::Int16()) {
      datatype = H5T_NATIVE_SHORT;
    }
    else if(array.getArrayType() == XdmfArrayType::Int32()) {
      datatype = H5T_NATIVE_INT;
    }
    else if(array.getArrayType() == XdmfArrayType::Int64()) {
      datatype = H5T_NATIVE_LONG;
    }
    else if(array.getArrayType() == XdmfArrayType::Float32()) {
      datatype = H5T_NATIVE_FLOAT;
    }
    else if(array.getArrayType() == XdmfArrayType::Float64()) {
      datatype = H5T_NATIVE_DOUBLE;
    }
    else if(array.getArrayType() == XdmfArrayType::UInt8()) {
      datatype = H5T_NATIVE_UCHAR;
    }
    else if(array.getArrayType() == XdmfArrayType::UInt16()) {
      datatype = H5T_NATIVE_USHORT;
    }
    else if(array.getArrayType() == XdmfArrayType::UInt32()) {
      datatype = H5T_NATIVE_UINT;
    }
1098 1099
    else if(array.getArrayType() == XdmfArrayType::String()) {
      // Strings are a special case as they have mutable size
Kenneth Leiter's avatar
Kenneth Leiter committed
1100 1101 1102 1103
      datatype = H5Tcopy(H5T_C_S1);
      H5Tset_size(datatype, H5T_VARIABLE);
      closeDatatype = true;
    }
1104
    else {
1105 1106 1107
      XdmfError::message(XdmfError::FATAL,
                         "Array of unsupported type in "
                         "XdmfHDF5Writer::write");
1108 1109 1110
    }
  }

1111 1112
  herr_t status;

1113 1114
  if(datatype != -1) {
    std::string hdf5FilePath = mFilePath;
1115

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    size_t extIndex;
    std::string checkFileName;
    std::string checkFileExt;
    extIndex = hdf5FilePath.find_last_of(".");
    if (extIndex == std::string::npos) {
      checkFileName = hdf5FilePath;
      checkFileExt = "";
    }
    else {
      checkFileName = hdf5FilePath.substr(0, extIndex);
      checkFileExt = hdf5FilePath.substr(extIndex+1);
    }

1129 1130
    std::stringstream dataSetPath;

1131 1132
    std::vector<shared_ptr<XdmfHeavyDataController> > previousControllers;

1133
    // Hold the controllers in order to base the new controllers on them
1134
    for(unsigned int i = 0; i < array.getNumberHeavyDataControllers(); ++i) {
1135
      previousControllers.push_back(array.getHeavyDataController(i));
1136
    }
1137

1138 1139
    // Remove controllers from the array
    // they will be replaced by the controllers created by this function.
1140
    while(array.getNumberHeavyDataControllers() != 0) {
1141
      array.removeHeavyDataController(array.getNumberHeavyDataControllers() -1);
1142 1143 1144
    }


1145 1146

    if (previousControllers.size() == 0) {
1147
      // Create a temporary controller if the array doesn't have one
1148 1149 1150 1151 1152 1153 1154 1155 1156
      shared_ptr<XdmfHeavyDataController> tempDataController =
        this->createController(hdf5FilePath,
                               "Data",
                               array.getArrayType(),
                               std::vector<unsigned int>(1, 0),
                               std::vector<unsigned int>(1, 1),
                               std::vector<unsigned int>(1, array.getSize()),
                               std::vector<unsigned int>(1, array.getSize()));
      previousControllers.push_back(tempDataController);
1157
    }
1158

1159
    int controllerIndexOffset = 0;
1160

1161 1162
    // It is assumed that the array will have at least one controller
    // if it didn't have one a temporary one was generated
1163
    for(unsigned int i = 0; i < previousControllers.size(); ++i)
1164
    {
1165 1166
      if (mMode == Append) {
        // Append only cares about the last controller, so add the rest back in
1167
	for (; i < previousControllers.size() - 1; ++i) {
1168 1169 1170 1171
          array.insert(previousControllers[i]);
	}
      }

1172
      std::list<std::string> filesWritten;
1173
      std::list<void *> arraysWritten;
1174 1175 1176 1177
      std::list<std::vector<unsigned int> > startsWritten;
      std::list<std::vector<unsigned int> > stridesWritten;
      std::list<std::vector<unsigned int> > dimensionsWritten;
      std::list<std::vector<unsigned int> > dataSizesWritten;
1178
      std::list<unsigned int> arrayOffsetsWritten;
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

      // Open a hdf5 dataset and write to it on disk.
      hsize_t size = array.getSize();

      // Save old error handler and turn off error handling for now
      H5E_auto_t old_func;
      void * old_client_data;
      H5Eget_auto(0, &old_func, &old_client_data);
      H5Eset_auto2(0, NULL, NULL);

1189 1190
      // If this is in hyperslab mode, this loop will need to execute multiple times
      // Otherwise the boolean is used simply to start it and one pass is made
1191
      bool startedloop = false;
1192 1193 1194 1195 1196 1197
      unsigned int origFileIndex = getFileIndex();
      while ((mMode == Hyperslab
              && i < previousControllers.size())
             || !startedloop) {
        // Hyperslab mode wants to assign all data using the current location
        // without writing until all data sets are determined
1198 1199 1200

        startedloop = true;

1201 1202
        shared_ptr<XdmfHDF5Controller> heavyDataController =
          shared_dynamic_cast<XdmfHDF5Controller>(previousControllers[i]);
1203
        // Stats for the data currently stored in the array
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    
        std::vector<unsigned int> dimensions;
        if (mMode != Hyperslab) {
          dimensions = array.getDimensions();
        }
        else {
	  dimensions = heavyDataController->getDimensions();
        }
        std::vector<unsigned int> dataspaceDimensions = dimensions;
        std::vector<unsigned int> start(dimensions.size(), 0);
        std::vector<unsigned int> stride(dimensions.size(), 1);

        if((mMode == Overwrite || mMode == Append || mMode == Hyperslab)
          && heavyDataController) {

1219 1220 1221 1222 1223 1224 1225 1226 1227
          // Write to the previous dataset
          dataSetPath.str(std::string());
          dataSetPath << heavyDataController->getDataSetPath();
          hdf5FilePath = heavyDataController->getFilePath();
          if(mMode == Hyperslab) {
            // Start, stride, and dataspace dimensions only matter for hyperslab mode
            dataspaceDimensions = heavyDataController->getDataspaceDimensions();
            start = heavyDataController->getStart();
            stride = heavyDataController->getStride();
1228 1229 1230 1231 1232
          }
        }
        else {
          dataSetPath.str(std::string());
          dataSetPath << "Data" << mDataSetId;
1233 1234
        }

1235 1236
        // Check here for if the file would become
        // larger than the limit after the addition.
1237
        // Then check subsequent files for the same limitation
1238
        std::string passPath = dataSetPath.str();
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
        controllerSplitting(array,
                            fapl,
                            controllerIndexOffset,
                            heavyDataController,
                            checkFileName,
                            checkFileExt,
                            dataSetPath.str(),
                            dimensions,
                            dataspaceDimensions,
                            start,
                            stride,
                            filesWritten,
                            arraysWritten,
                            startsWritten,
                            stridesWritten,
                            dimensionsWritten,
                            dataSizesWritten,
                            arrayOffsetsWritten);
1257

1258 1259
        if (mMode == Hyperslab)
        {
1260
          // In hyperslab mode, reset the file index and move to next iteration
1261
          i++;
1262
          setFileIndex(origFileIndex);
1263
        }
1264

1265 1266
      }

1267
      std::list<std::string>::iterator fileNameWalker = filesWritten.begin();
1268
      std::list<void *>::iterator arrayWalker = arraysWritten.begin();
1269 1270 1271 1272
      std::list<std::vector<unsigned int> >::iterator startWalker = startsWritten.begin();
      std::list<std::vector<unsigned int> >::iterator strideWalker = stridesWritten.begin();
      std::list<std::vector<unsigned int> >::iterator dimensionWalker = dimensionsWritten.begin();
      std::list<std::vector<unsigned int> >::iterator dataSizeWalker = dataSizesWritten.begin();
1273
      std::list<unsigned int>::iterator arrayOffsetWalker = arrayOffsetsWritten.begin();
1274

1275
      // Loop based on the amount of blocks split from the array.
1276
      for (unsigned int writeIndex = 0; writeIndex < arraysWritten.size(); ++writeIndex) {
1277

1278 1279
	// This is the section where the data is written to hdf5
	// If you want to change the writer to write to a different data format, do it here
1280

1281
        std::string curFileName = *fileNameWalker;
1282
        void * curArray = *arrayWalker;
1283 1284 1285 1286
        std::vector<unsigned int> curStart = *startWalker;
        std::vector<unsigned int> curStride = *strideWalker;
        std::vector<unsigned int> curDimensions = *dimensionWalker;
        std::vector<unsigned int> curDataSize = *dataSizeWalker;
1287
        unsigned int curArrayOffset = *arrayOffsetWalker;
1288

1289

1290
	bool closeFile = false;
1291 1292
        // This is meant to open files if it isn't already opened by the write prior
        // If it wasn't open prior to writing it will be closed after writing
1293 1294 1295 1296 1297
        if (mImpl->mOpenFile.compare(curFileName) != 0) {
          if(mImpl->mHDF5Handle < 0) {
            closeFile = true;
          }
          mImpl->openFile(curFileName,
1298
                          fapl, mDataSetId);
1299
        }
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	htri_t testingSet = H5Lexists(mImpl->mHDF5Handle,
                                      dataSetPath.str().c_str(),
                                      H5P_DEFAULT);

        hid_t dataset = 0;

        if (testingSet == 0) {
          dataset = -1;
        }
        else {
          dataset = H5Dopen(mImpl->mHDF5Handle,
                            dataSetPath.str().c_str(),
                            H5P_DEFAULT);
        }
1315

1316
        // If default mode find a new data set to write to (keep
1317
        // incrementing dataSetId)
1318
        if(dataset >=0 && mMode == Default) {
1319 1320 1321 1322
          while(true) {
            dataSetPath.str(std::string());
            dataSetPath << "Data" << ++mDataSetId;
            if(!H5Lexists(mImpl->mHDF5Handle,
1323
                          dataSetPath.str().c_str(),
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
                          H5P_DEFAULT)) {
              dataset = H5Dopen(mImpl->mHDF5Handle,
                                dataSetPath.str().c_str(),
                                H5P_DEFAULT);
              break;
            }
          }
        }

        // Restore previous error handler
        H5Eset_auto2(0, old_func, old_client_data);

        hid_t dataspace = H5S_ALL;
        hid_t memspace = H5S_ALL;

1339 1340
        std::vector<hsize_t> current_dims(curDataSize.begin(),
                                          curDataSize.end());
1341

1342 1343
        if(dataset < 0) {
          // If the dataset doesn't contain anything
1344

1345
          std::vector<hsize_t> maximum_dims(curDimensions.size(), H5S_UNLIMITED);
1346
          // Create a new dataspace
1347
          dataspace = H5Screate_simple(current_dims.size(),
1348 1349 1350
                                       &current_dims[0],
                                       &maximum_dims[0]);
          hid_t property = H5Pcreate(H5P_DATASET_CREATE);
1351 1352 1353 1354 1355 1356

          const hsize_t totalDimensionsSize =
            std::accumulate(current_dims.begin(),
                            current_dims.end(),
                            1,
                            std::multiplies<hsize_t>());
1357
          // The Nth root of the chunk size divided by the dimensions added together
1358 1359
          const double factor =
            std::pow(((double)mImpl->mChunkSize / totalDimensionsSize),
1360 1361
                     1.0 / current_dims.size());
          // The end result is the amount of slots alloted per unit of dimension
1362 1363
          std::vector<hsize_t> chunk_size(current_dims.begin(),
                                          current_dims.end());
1364 1365
	  if (mImpl->mChunkSize > 0) {
            // The chunk size won't do anything unless it's positive
1366 1367 1368 1369 1370 1371 1372 1373
            for(std::vector<hsize_t>::iterator iter = chunk_size.begin();
                iter != chunk_size.end(); ++iter) {
              *iter = (hsize_t)(*iter * factor);
              if(*iter == 0) {
                *iter = 1;
              }
            }
          }
1374 1375

          status = H5Pset_chunk(property, current_dims.size(), &chunk_size[0]);
1376
          // Use that dataspace to create a new dataset
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
          dataset = H5Dcreate(mImpl->mHDF5Handle,
                              dataSetPath.str().c_str(),
                              datatype,
                              dataspace,
                              H5P_DEFAULT,
                              property,
                              H5P_DEFAULT);
          status = H5Pclose(property);
        }

        if(mMode == Append) {
          // Need to resize dataset to fit new data

          // Get size of old dataset
          dataspace = H5Dget_space(dataset);
          hssize_t datasize = H5Sget_simple_extent_npoints(dataspace);
          status = H5Sclose(dataspace);

1395
          // Reset the datasize if the file or set is different
1396
          if (curFileName != previousControllers[i]->getFilePath()) {
1397 1398
            datasize = 0;
          }
1399 1400 1401 1402 1403 1404 1405
          if (shared_ptr<XdmfHDF5Controller> setPathController =
                shared_dynamic_cast<XdmfHDF5Controller>(previousControllers[i])) {
            if (dataSetPath.str() != setPathController->getDataSetPath()) {
              datasize = 0;
            }
          }
          else {
1406 1407 1408
            datasize = 0;
          }

1409 1410 1411 1412 1413 1414
          unsigned int sizeTotal = 1;

          for (unsigned int dataSizeIter = 0; dataSizeIter < curDataSize.size(); ++dataSizeIter) {
            sizeTotal = sizeTotal * curDataSize[dataSizeIter];
          }

1415
          // Resize to fit size of old and new data.
1416
          hsize_t newSize = sizeTotal + datasize;
1417
          status = H5Dset_extent(dataset, &newSize);
1418
          
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
          // Select hyperslab to write to.
          memspace = H5Screate_simple(1, &size, NULL);
          dataspace = H5Dget_space(dataset);
          hsize_t dataStart = datasize;
          status = H5Sselect_hyperslab(dataspace,
                                       H5S_SELECT_SET,
                                       &dataStart,
                                       NULL,
                                       &size,
                                       NULL);
        }
        else if(mMode == Overwrite) {
          // Overwriting - dataset rank must remain the same (hdf5 constraint)
          dataspace = H5Dget_space(dataset);

          const unsigned int ndims = H5Sget_simple_extent_ndims(dataspace);
1435
          if(ndims != current_dims.size()) {
1436
            XdmfError::message(XdmfError::FATAL,                            \
1437 1438 1439
                               "Data set rank different -- ndims != "
                               "current_dims.size() -- in "
                               "XdmfHDF5Writer::write");
1440
          }
1441 1442 1443 1444 1445 1446 1447 1448 1449

          status = H5Dset_extent(dataset, &current_dims[0]);
          dataspace = H5Dget_space(dataset);
        }
        else if(mMode == Hyperslab) {
          // Hyperslab - dataset rank must remain the same (hdf5 constraint)
          dataspace = H5Dget_space(dataset);

          const unsigned int ndims = H5Sget_simple_extent_ndims(dataspace);
1450
          if(ndims != current_dims.size()) {
1451
            XdmfError::message(XdmfError::FATAL,                            \
1452 1453 1454
                               "Data set rank different -- ndims != "
                               "current_dims.size() -- in "
                               "XdmfHDF5Writer::write");
1455
          }
1456 1457 1458
          status = H5Dset_extent(dataset, &current_dims[0]);
          dataspace = H5Dget_space(dataset);

1459 1460 1461 1462 1463 1464 1465 1466 1467



          std::vector<hsize_t> count(curDimensions.begin(),
                                     curDimensions.end());
          std::vector<hsize_t> currStride(curStride.begin(),
                                          curStride.end());
          std::vector<hsize_t> currStart(curStart.begin(),
                                         curStart.end());
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479

          memspace = H5Screate_simple(count.size(),
                                      &(count[0]),
                                      NULL);
          status = H5Sselect_hyperslab(dataspace,
                                       H5S_SELECT_SET,
                                       &currStart[0],
                                       &currStride[0],
                                       &count[0],
                                       NULL) ;

          if(status < 0) {
1480 1481 1482
            XdmfError::message(XdmfError::FATAL,
                               "H5Dset_extent returned failure in "
                               "XdmfHDF5Writer::write -- status: " + status);
1483 1484 1485 1486
          }
        }

        status = H5Dwrite(dataset,
1487
                          datatype,
1488
                          memspace,
1489
                          dataspace,
1490
                          H5P_DEFAULT,
1491
                          curArray);
1492

1493
        if(status < 0) {
1494 1495 1496
          XdmfError::message(XdmfError::FATAL,
                             "H5Dwrite returned failure in XdmfHDF5Writer::write "
                             "-- status: " + status);
1497
        }
1498

1499 1500 1501
        if(dataspace != H5S_ALL) {
          status = H5Sclose(dataspace);
        }
1502

1503 1504 1505
        if(memspace != H5S_ALL) {
          status = H5Sclose(memspace);
        }
1506

1507
        status = H5Dclose(dataset);
1508

1509
	// This is causing a lot of overhead
1510 1511 1512
        if(closeFile) {
          mImpl->closeFile();
        }
1513

1514 1515 1516
        if(mMode == Default) {
          ++mDataSetId;
        }
1517

1518 1519
        // Attach a new controller to the array
        shared_ptr<XdmfHDF5Controller> newDataController =
1520 1521
          shared_ptr<XdmfHDF5Controller>();
        //This generates an empty pointer
1522 1523 1524

        unsigned int newSize;
        if(mMode == Append) {
1525
          // Find data size
1526
          mImpl->openFile(curFileName,
1527
                          fapl, mDataSetId);
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
          hid_t checkset = H5Dopen(mImpl->mHDF5Handle,
                                   dataSetPath.str().c_str(),
                                   H5P_DEFAULT);
          hid_t checkspace = H5S_ALL;
          checkspace = H5Dget_space(checkset);
          newSize = H5Sget_simple_extent_npoints(checkspace);
          status = H5Dclose(checkset);
	  if(checkspace != H5S_ALL) {
	    status = H5Sclose(checkspace);
          }
 
          std::vector<unsigned int> insertStarts;
          insertStarts.push_back(0);
          std::vector<unsigned int> insertStrides;
          insertStrides.push_back(1);
          std::vector<unsigned int> insertDimensions;
          insertDimensions.push_back(newSize);
          std::vector<unsigned int> insertDataSpaceDimensions;
          insertDataSpaceDimensions.push_back(newSize);

1548
          newDataController = 
1549 1550 1551 1552 1553 1554 1555
            shared_dynamic_cast<XdmfHDF5Controller>(this->createController(curFileName,
                                                    dataSetPath.str(),
                                                    array.getArrayType(),
                                                    insertStarts,
                                                    insertStrides,
                                                    insertDimensions,
                                                    insertDataSpaceDimensions));
1556
        }
1557

1558 1559
        if(!newDataController) {
          // If the controller wasn't generated by append
1560
          newDataController =
1561 1562 1563 1564 1565 1566 1567
            shared_dynamic_cast<XdmfHDF5Controller>(this->createController(curFileName,
                                                    dataSetPath.str(),
                                                    array.getArrayType(),
                                                    curStart,
                                                    curStride,
                                                    curDimensions,
                                                    curDataSize));
1568
        }
1569

1570 1571
        newDataController->setArrayOffset(curArrayOffset);

1572 1573
        array.insert(newDataController);

1574 1575 1576 1577 1578 1579
        fileNameWalker++;
        arrayWalker++;
        startWalker++;
        strideWalker++;
        dimensionWalker++;
        dataSizeWalker++;
1580
        arrayOffsetWalker++;
1581 1582


1583
      }
1584

1585
    }
1586

1587 1588
    if(closeDatatype) {
      status = H5Tclose(datatype);
1589
    }
1590 1591 1592 1593

    if(mReleaseData) {
      array.release();
    }
1594
  }
1595
}