XdmfArray.cpp 62.6 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 : XdmfArray.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.                                                 */
/*                                                                           */
/*****************************************************************************/
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
23

24
#include <boost/tokenizer.hpp>
25
#include <boost/assign.hpp>
26
#include <limits>
27
#include <sstream>
28
#include <utility>
29 30
#include <stack>
#include <math.h>
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
31
#include "XdmfArray.hpp"
32
#include "XdmfArrayType.hpp"
33
#include "XdmfHDF5Controller.hpp"
34
#include "XdmfHeavyDataController.hpp"
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
35
#include "XdmfVisitor.hpp"
36
#include "XdmfError.hpp"
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
37

38 39 40
std::string XdmfArray::mSupportedOperations = "|#()";
const std::string XdmfArray::mValidVariableChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_:.";
const std::string XdmfArray::mValidDigitChars = "-1234567890.";
41 42
// list the priorities for the operations, based on the order of operations
// the index of the corresponding operation in validOperationChars is the same as the index of its priority in this array
43
int XdmfArray::mOperationPriority [8] = {2, 1, 0, 0};
44 45
// the higher the value, the earlier the operation is evaluated in the order of operations
// with the exception of parenthesis which are evaluated as soon as the closing parenthesis is found
46

47
// note, it doesn't handle overloaded functions well. Will generate errors unless overload methods are typecast.
48 49 50 51 52
std::map<std::string, shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >)> XdmfArray::arrayFunctions = boost::assign::map_list_of ("SUM", (shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))XdmfArray::sum) ("AVE", (shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))XdmfArray::ave);
std::map<char, shared_ptr<XdmfArray> (*)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>)> XdmfArray::operations = boost::assign::map_list_of ('|', XdmfArray::chunk) ('#', XdmfArray::interlace);



53 54 55 56 57
XDMF_CHILDREN_IMPLEMENTATION(XdmfArray,
                             XdmfHeavyDataController,
                             HeavyDataController,
                             Name)

58
class XdmfArray::Clear : public boost::static_visitor<void> {
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
59
public:
60

61 62 63 64 65 66
  Clear(XdmfArray * const array) :
    mArray(array)
  {
  }

  void
67
  operator()(const boost::blank & array) const
68
  {
69
    return;
70 71 72 73
  }

  template<typename T>
  void
74
  operator()(const shared_ptr<std::vector<T> > & array) const
75
  {
76
    array->clear();
77
  }
78 79 80 81 82 83 84 85 86 87

  template<typename T>
  void
  operator()(const boost::shared_array<const T> & array) const
  {
    mArray->internalizeArrayPointer();
    boost::apply_visitor(*this,
                         mArray->mArray);
  }

88
private: 
89
  XdmfArray * const mArray;
90 91
};

92
class XdmfArray::Erase : public boost::static_visitor<void> {
93 94
public:

95 96 97
  Erase(XdmfArray * const array,
        const unsigned int index) :
    mArray(array),
98 99 100
    mIndex(index)
  {
  }
101

102
  void
103
  operator()(const boost::blank & array) const
104 105 106 107
  {
    return;
  }

108 109
  template<typename T>
  void
110
  operator()(const shared_ptr<std::vector<T> > & array) const
111 112 113
  {
    array->erase(array->begin() + mIndex);
  }
114

115 116
  template<typename T>
  void
117
  operator()(const boost::shared_array<const T> & array) const
118 119 120 121 122 123
  {
    mArray->internalizeArrayPointer();
    boost::apply_visitor(*this,
                         mArray->mArray);
  }

124 125
private:

126
  XdmfArray * const mArray;
127
  const unsigned int mIndex;
128 129
};

130
class XdmfArray::GetArrayType :
131
  public boost::static_visitor<shared_ptr<const XdmfArrayType> > {
132 133
public:

134 135
  GetArrayType(const shared_ptr<XdmfHeavyDataController> & heavyDataController) :
    mHeavyDataController(heavyDataController)
136 137 138
  {
  }

139
  shared_ptr<const XdmfArrayType>
140 141 142 143 144
  getArrayType(const char * const) const
  {
    return XdmfArrayType::Int8();
  }

145
  shared_ptr<const XdmfArrayType>
146 147 148 149 150
  getArrayType(const short * const) const
  {
    return XdmfArrayType::Int16();
  }

151
  shared_ptr<const XdmfArrayType>
152 153 154 155 156
  getArrayType(const int * const) const
  {
    return XdmfArrayType::Int32();
  }

157
  shared_ptr<const XdmfArrayType>
158 159 160 161 162
  getArrayType(const long * const) const
  {
    return XdmfArrayType::Int64();
  }

163
  shared_ptr<const XdmfArrayType>
164 165 166 167 168
  getArrayType(const float * const) const
  {
    return XdmfArrayType::Float32();
  }

169
  shared_ptr<const XdmfArrayType>
170 171 172 173 174
  getArrayType(const double * const) const
  {
    return XdmfArrayType::Float64();
  }

175
  shared_ptr<const XdmfArrayType>
176 177 178 179 180
  getArrayType(const unsigned char * const) const
  {
    return XdmfArrayType::UInt8();
  }

181
  shared_ptr<const XdmfArrayType>
182 183 184 185 186
  getArrayType(const unsigned short * const) const
  {
    return XdmfArrayType::UInt16();
  }

187
  shared_ptr<const XdmfArrayType>
188 189 190 191 192
  getArrayType(const unsigned int * const) const
  {
    return XdmfArrayType::UInt32();
  }

Kenneth Leiter's avatar
Kenneth Leiter committed
193 194 195 196 197 198
  shared_ptr<const XdmfArrayType>
  getArrayType(const std::string * const) const
  {
    return XdmfArrayType::String();
  }

199
  shared_ptr<const XdmfArrayType>
200
  operator()(const boost::blank & array) const
201
  {
202 203
    if(mHeavyDataController) {
      return mHeavyDataController->getType();
204 205 206 207
    }
    return XdmfArrayType::Uninitialized();
  }

208
  template<typename T>
209 210
  shared_ptr<const XdmfArrayType>
  operator()(const shared_ptr<std::vector<T> > & array) const
211 212 213 214 215
  {
    return this->getArrayType(&(array.get()->operator[](0)));
  }

  template<typename T>
216
  shared_ptr<const XdmfArrayType>
217 218 219 220
  operator()(const boost::shared_array<const T> & array) const
  {
    return this->getArrayType(array.get());
  }
221 222 223 224

private:

  const shared_ptr<XdmfHeavyDataController> mHeavyDataController;
225 226 227 228 229
};

class XdmfArray::GetCapacity : public boost::static_visitor<unsigned int> {
public:

230 231 232
  GetCapacity()
  {
  }
233

234
  unsigned int
235
  operator()(const boost::blank & array) const
236 237 238 239
  {
    return 0;
  }

240 241
  template<typename T>
  unsigned int
242
  operator()(const shared_ptr<std::vector<T> > & array) const
243 244 245
  {
    return array->capacity();
  }
246 247 248

  template<typename T>
  unsigned int
249
  operator()(const boost::shared_array<const T> & array) const
250 251 252
  {
    return 0;
  }
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
253 254
};

255
class XdmfArray::GetValuesPointer :
256
  public boost::static_visitor<const void *> {
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
257 258
public:

259 260 261 262
  GetValuesPointer()
  {
  }

263
  const void *
264
  operator()(const boost::blank & array) const
265 266 267 268
  {
    return NULL;
  }

269
  template<typename T>
270
  const void *
271
  operator()(const shared_ptr<std::vector<T> > & array) const
272 273 274 275 276
  {
    return &array->operator[](0);
  }

  template<typename T>
277
  const void *
278 279 280 281
  operator()(const boost::shared_array<const T> & array) const
  {
    return array.get();
  }
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
282 283
};

284
class XdmfArray::GetValuesString : public boost::static_visitor<std::string> {
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
285 286
public:

287 288 289 290 291
  GetValuesString(const int arrayPointerNumValues) :
    mArrayPointerNumValues(arrayPointerNumValues)
  {
  }

292
  template<typename T, typename U>
293
  std::string
294
  getValuesString(const T * const array,
295 296
                  const int numValues) const
  {
297
    const int lastIndex = numValues - 1;
298 299 300 301 302

    if(lastIndex < 0) {
      return "";
    }

303
    std::stringstream toReturn;
304
    toReturn.precision(std::numeric_limits<U>::digits10 + 2);
305
    for(int i=0; i<lastIndex; ++i) {
306
      toReturn << (U)array[i] << " ";
307
    }
308
    toReturn << (U)array[lastIndex];
309 310 311
    return toReturn.str();
  }

312 313 314 315 316 317 318
  std::string
  getValuesString(const char * const array,
                  const int numValues) const
  {
    return getValuesString<char, int>(array, numValues);
  }

319 320 321 322
  std::string
  getValuesString(const unsigned char * const array,
                  const int numValues) const
  {
323
    return getValuesString<unsigned char, int>(array, numValues);
324 325 326 327 328 329 330
  }

  template<typename T>
  std::string
  getValuesString(const T * const array,
                  const int numValues) const
  {
331
    return getValuesString<T, T>(array, numValues);
332 333
  }

334
  std::string
335
  operator()(const boost::blank & array) const
336 337 338 339
  {
    return "";
  }

340 341
  template<typename T>
  std::string
342
  operator()(const shared_ptr<std::vector<T> > & array) const
343 344 345 346 347 348 349 350 351 352
  {
    return getValuesString(&(array->operator[](0)), array->size());
  }

  template<typename T>
  std::string
  operator()(const boost::shared_array<const T> & array) const
  {
    return getValuesString(array.get(), mArrayPointerNumValues);
  }
353 354 355

private:

356
  const unsigned int mArrayPointerNumValues;
357 358
};

359 360 361
class XdmfArray::InsertArray : public boost::static_visitor<void> {
public:

362 363
  InsertArray(XdmfArray * const array,
              const unsigned int startIndex,
364 365 366
              const unsigned int valuesStartIndex,
              const unsigned int numValues,
              const unsigned int arrayStride,
367
              const unsigned int valuesStride,
368 369 370
              std::vector<unsigned int> & dimensions,
              const shared_ptr<const XdmfArray> & arrayToCopy) :
    mArray(array),
371 372 373 374
    mStartIndex(startIndex),
    mValuesStartIndex(valuesStartIndex),
    mNumValues(numValues),
    mArrayStride(arrayStride),
375
    mValuesStride(valuesStride),
376 377
    mDimensions(dimensions),
    mArrayToCopy(arrayToCopy)
378 379 380 381
  {
  }

  void
382
  operator()(const boost::blank & array) const
383 384 385 386 387 388 389 390 391
  {
    mArray->initialize(mArrayToCopy->getArrayType());
    boost::apply_visitor(*this,
                         mArray->mArray);
  }

  template<typename T>
  void
  operator()(const shared_ptr<std::vector<T> > & array) const
392
  {
393
    unsigned int size = mStartIndex + (mNumValues - 1) * mArrayStride + 1;
394 395
    if(array->size() < size) {
      array->resize(size);
396
      mDimensions.clear();
397
    }
398 399 400 401 402 403 404 405 406 407 408 409 410 411
    mArrayToCopy->getValues(mValuesStartIndex,
                            &(array->operator[](mStartIndex)),
                            mNumValues,
                            mValuesStride,
                            mArrayStride);
  }

  template<typename T>
  void
  operator()(const boost::shared_array<const T> & array) const
  {
    mArray->internalizeArrayPointer();
    boost::apply_visitor(*this,
                         mArray->mArray);
412
  }
413 414 415

private:

416
  XdmfArray * const mArray;
417 418 419 420 421
  const unsigned int mStartIndex;
  const unsigned int mValuesStartIndex;
  const unsigned int mNumValues;
  const unsigned int mArrayStride;
  const unsigned int mValuesStride;
422
  std::vector<unsigned int> & mDimensions;
423
  const shared_ptr<const XdmfArray> mArrayToCopy;
424 425
};

426
class XdmfArray::InternalizeArrayPointer : public boost::static_visitor<void> {
427 428
public:

429 430 431 432 433
  InternalizeArrayPointer(XdmfArray * const array) :
    mArray(array)
  {
  }

434
  void
435
  operator()(const boost::blank & array) const
436 437 438 439 440 441
  {
    return;
  }

  template<typename T>
  void
442
  operator()(const shared_ptr<std::vector<T> > & array) const
443 444 445 446
  {
    return;
  }

447 448 449 450
  template<typename T>
  void
  operator()(const boost::shared_array<const T> & array) const
  {
451 452 453 454
    const T * const pointer = array.get();
    shared_ptr<std::vector<T> > newArray(new std::vector<T>(pointer,
                                                            pointer + mArray->mArrayPointerNumValues));
    mArray->mArray = newArray;
455 456
    mArray->mArrayPointerNumValues = 0;
  }
457 458 459

private:

460
  XdmfArray * const mArray;
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
461 462
};

463 464 465 466 467 468 469 470
class XdmfArray::IsInitialized : public boost::static_visitor<bool> {
public:

  IsInitialized()
  {
  }

  bool
471
  operator()(const boost::blank &) const
472 473 474 475 476 477
  {
    return false;
  }

  template<typename T>
  bool
478
  operator()(const shared_ptr<std::vector<T> > &) const
479 480 481 482 483 484
  {
    return true;
  }

  template<typename T>
  bool
485
  operator()(const T &) const
486 487 488 489 490
  {
    return true;
  }
};

491
class XdmfArray::Reserve : public boost::static_visitor<void> {
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
492 493
public:

494 495 496 497
  Reserve(XdmfArray * const array,
          const unsigned int size):
    mArray(array),
    mSize(size)
498 499 500 501
  {
  }

  void
502
  operator()(const boost::blank & array) const
503
  {
504
    mArray->mTmpReserveSize = mSize;
505
  }
506

507 508 509
  template<typename T>
  void
  operator()(shared_ptr<std::vector<T> > & array) const
510
  {
511
    array->reserve(mSize);
512
  }
513

514 515
  template<typename T>
  void
516
  operator()(const boost::shared_array<const T> & array) const
517
  {
518 519 520
    mArray->internalizeArrayPointer();
    boost::apply_visitor(*this,
                         mArray->mArray);
521
  }
522 523 524

private:

525
  XdmfArray * const mArray;
526
  const unsigned int mSize;
527 528
};

529 530 531
class XdmfArray::Size : public boost::static_visitor<unsigned int> {
public:

532 533 534 535 536 537
  Size(const XdmfArray * const array) :
    mArray(array)
  {
  }

  unsigned int
538
  operator()(const boost::blank & array) const
539
  {
540
    if(mArray->mHeavyDataControllers.size()>0) {
541
      int total = 0;
542
      for (unsigned int i = 0; i < mArray->mHeavyDataControllers.size(); ++i) {
543 544
        total += mArray->mHeavyDataControllers[i]->getSize();
      }
545
      return total;
546 547
    }
    return 0;
548
  }
549

550 551
  template<typename T>
  unsigned int
552
  operator()(const shared_ptr<std::vector<T> > & array) const
553 554 555
  {
    return array->size();
  }
556 557 558

  template<typename T>
  unsigned int
559
  operator()(const boost::shared_array<const T> & array) const
560 561 562 563 564 565
  {
    return mArray->mArrayPointerNumValues;
  }

private:

566
  const XdmfArray * const mArray; 
567 568
};

569
shared_ptr<XdmfArray>
570
XdmfArray::New()
571
{
572
  shared_ptr<XdmfArray> p(new XdmfArray());
573
  return p;
574 575
}

Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
576
XdmfArray::XdmfArray() :
577 578 579
  mArrayPointerNumValues(0),
  mName(""),
  mTmpReserveSize(0)
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
580 581 582 583 584 585 586
{
}

XdmfArray::~XdmfArray()
{
}

587
const std::string XdmfArray::ItemTag = "DataItem";
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
int
XdmfArray::addFunction(std::string name, shared_ptr<XdmfArray>(*functionref)(std::vector<shared_ptr<XdmfArray> >))
{
  // check to ensure that the name has valid characters
  for (unsigned int i = 0; i < name.size(); ++i) {
    // if the character is not found in the list of valid characters
    if (mValidVariableChars.find(name[i]) == std::string::npos) {
      // then throw an error
      try {
        XdmfError::message(XdmfError::FATAL,
                           "Error: Function Name Contains Invalid Character(s)");
      }
      catch (XdmfError e) {
        throw e;
      }
    }
  }
  size_t origsize = arrayFunctions.size();
  arrayFunctions[name] = functionref;
  // if no new functions were added
  if (origsize == arrayFunctions.size()) {
    // toss a warning, it's nice to let people know that they're doing this
    try {
      XdmfError::message(XdmfError::WARNING,
                         "Warning: Function Overwritten");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
  return arrayFunctions.size();
}

shared_ptr<XdmfArray>
XdmfArray::ave(std::vector<shared_ptr<XdmfArray> > values)
{
        double total = sum(values)->getValue<double>(0);;
        int totalSize = 0;
        for (unsigned int i = 0; i < values.size(); ++i)
        {
                totalSize += values[i]->getSize();
        }
        shared_ptr<XdmfArray> returnArray = XdmfArray::New();
        returnArray->insert(0, total/totalSize);
        return returnArray;
}

636 637
void
XdmfArray::clear()
638
{
639
  boost::apply_visitor(Clear(this), 
640 641
                       mArray);
  mDimensions.clear();
642 643
}

644 645 646 647 648 649 650 651 652 653 654
shared_ptr<XdmfArray>
XdmfArray::chunk(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  // join chunk (add the new array to the end of the first one)
  // joins into new array and returns it
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  returnArray->insert(0, val1, 0, val1->getSize(),  1, 1);
  returnArray->insert(val1->getSize(), val2, 0, val2->getSize(), 1, 1);
  return returnArray;
}

655 656
void
XdmfArray::erase(const unsigned int index)
657
{
658 659 660 661
  boost::apply_visitor(Erase(this,
                             index),
                       mArray);
  mDimensions.clear();
662 663
}

664 665
// This function and the functions it depends on are reimplemented in XdmfCore.i in order to properly interface with python.
// There are differences between the versions, but the overall algorithm remains mostly the same.
666 667 668
shared_ptr<XdmfArray>
XdmfArray::evaluateExpression(std::string expression, std::map<std::string, shared_ptr<XdmfArray> > variables)
{
669 670 671
  std::stack<shared_ptr<XdmfArray> > valueStack;
  std::stack<char> operationStack;

672 673 674
  // string is parsed left to right
  // elements of the same priority are evaluated right to left
  for (unsigned int i = 0; i < expression.size(); ++i) {
675
    if (mValidDigitChars.find(expression[i]) != std::string::npos) {//found to be a digit
676
      // progress until a non-digit is found
677
      int valueStart = i;
678 679 680 681
      if (i + 1 < expression.size()) {
        while (mValidDigitChars.find(expression[i+1]) != std::string::npos) {
          i++;
        }
682
      }
683
      // push back to the value stack
684
      shared_ptr<XdmfArray> valueArray = XdmfArray::New();
685 686
      // use this to convert to double
      valueArray->insert(0, atof(expression.substr(valueStart, i + 1 - valueStart).c_str()));
687 688
      valueStack.push(valueArray);
    }
689 690
    else if (mValidVariableChars.find(expression[i]) != std::string::npos) {
      // found to be a variable
691
      int valueStart = i;
692 693 694 695 696
      // progress until a nonvariable value is found
      if (i+1 < expression.size()){ 
        while (mValidVariableChars.find(expression[i+1]) != std::string::npos) {
          i++;
        }
697
      }
698
      // convert to equivalent
699 700
      if (variables.find(expression.substr(valueStart, i + 1 - valueStart)) == variables.end()) {
        if (arrayFunctions.find(expression.substr(valueStart, i + 1 - valueStart)) == arrayFunctions.end()) {
701 702 703 704 705 706 707
          try {
            XdmfError::message(XdmfError::FATAL,
                               "Error: Invalid Variable in evaluateExpression " + expression.substr(valueStart, i + 1 - valueStart));
          }
          catch (XdmfError e) {
            throw e;
          }
708 709 710
        }
        else {
          std::string currentFunction = expression.substr(valueStart, i + 1 - valueStart);
711 712 713 714 715 716 717 718 719 720
          // check if next character is an open parenthesis
          if (i+1 >= expression.size()) {
            if (expression[i+1] != '(') {
              try {
                XdmfError::message(XdmfError::FATAL,
                                   "Error: No values supplied to function " + expression.substr(valueStart, i + 1 - valueStart));
              }
              catch (XdmfError e) {
                throw e;
              }
721
            }
722
          }
723 724 725 726 727 728
          // if it is grab the string between paranthesis

          if (i + 2 >= expression.size()) {
            XdmfError::message(XdmfError::FATAL,
                               "Error: Missing closing parethesis to function " + expression.substr(valueStart, i + 1 - valueStart));
          }
729 730 731 732 733 734 735 736 737 738 739 740 741 742
          i = i + 2;
          valueStart = i;
          int numOpenParenthesis = 0;
          while ((expression[i] != ')' || numOpenParenthesis) && i < expression.size()) {
            if (expression[i] == '(') {
              numOpenParenthesis++;
            }
            else if (expression[i] == ')') {
              numOpenParenthesis--;
            }
            i++;
          }
          std::string functionParameters = expression.substr(valueStart, i - valueStart);
          std::vector<shared_ptr<XdmfArray> > parameterVector;
743
          // split that string at commas
744 745 746 747
          size_t parameterSplit = 0;
          while (parameterSplit != std::string::npos) {
            parameterSplit = 0;
            parameterSplit = functionParameters.find_first_of(",", parameterSplit);
748
            // feed the substrings to the parse function
749 750 751 752 753 754 755 756 757 758 759 760
            if (parameterSplit == std::string::npos) {
              parameterVector.push_back(evaluateExpression(functionParameters, variables));
            }
            else {
              parameterVector.push_back(evaluateExpression(functionParameters.substr(0, parameterSplit), variables));
              functionParameters = functionParameters.substr(parameterSplit+1);
            }
          }
          valueStack.push(evaluateFunction(parameterVector, currentFunction));
        }
      }
      else {
761
        // push equivalent to value stack
762 763 764
        valueStack.push(variables.find(expression.substr(valueStart, i + 1 - valueStart))->second);
      }
    }
765 766 767
    else if (mSupportedOperations.find(expression[i]) != std::string::npos) {
      // found to be an operation
      // pop operations off the stack until one of a lower or equal importance is found
768 769
      if (operationStack.size() > 0) {
        if (expression[i] == ')') {
770
          // to close a parenthesis pop off all operations until another parentheis is found
771
          while (operationStack.size() > 0 && operationStack.top() != '(') {
772 773
            // must be at least two values for this loop to work properly
            if (valueStack.size() < 2) {
774 775 776 777 778 779 780
              try {
                XdmfError::message(XdmfError::FATAL,
                                   "Error: Not Enough Values in evaluateExpression");
              }
              catch (XdmfError e) {
                throw e;
              }
781 782 783 784 785 786 787 788 789 790 791 792 793
            }
            else {
              shared_ptr<XdmfArray> val2 = valueStack.top();
              valueStack.pop();
              shared_ptr<XdmfArray> val1 = valueStack.top();
              valueStack.pop();
              valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
              operationStack.pop();
            }
          }
          operationStack.pop();
        }
        else if (expression[i] == '(') {
794 795 796
          // just add it if it's a start parenthesis
          // nothing happens here in that case
          // addition happens after the if statement
797 798 799 800
        }
        else {
          int operationLocation = getOperationPriority(expression[i]);
          int topOperationLocation = getOperationPriority(operationStack.top());
801
          // see order of operations to determine importance
802
          while (operationStack.size() > 0 && operationLocation < topOperationLocation) {
803 804
            // must be at least two values for this loop to work properly
            if (valueStack.size() < 2) {
805 806 807 808 809 810 811
              try {
                XdmfError::message(XdmfError::FATAL,
                                   "Error: Not Enough Values in evaluateExpression");
              }
              catch (XdmfError e) {
                throw e;
              }
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
            }
            else {
              shared_ptr<XdmfArray> val2 = valueStack.top();
              valueStack.pop();
              shared_ptr<XdmfArray> val1 = valueStack.top();
              valueStack.pop();
              valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
              operationStack.pop();
              if (operationStack.size() == 0) {
                break;
              }
              topOperationLocation = getOperationPriority(operationStack.top());
            }
          }
        }
      }
      if (expression[i] != ')') {
829
        // add the operation to the operation stack
830 831 832
        operationStack.push(expression[i]);
      }
    }
833
    // if not a value or operation the character is ignored
834
  }
835

836
  // empty what's left in the stacks before finishing
837 838
  while (valueStack.size() > 1 && operationStack.size() > 0) {
    if (valueStack.size() < 2) {//must be at least two values for this loop to work properly
839 840 841 842 843 844 845
      try {
        XdmfError::message(XdmfError::FATAL,
                           "Error: Not Enough Values in evaluateExpression");
      }
      catch (XdmfError e) {
        throw e;
      }
846 847 848
    }
    else {
      if(operationStack.top() == '(') {
849 850 851 852 853 854 855
        try {
          XdmfError::message(XdmfError::WARNING,
                             "Warning: Unpaired Parenthesis");
        }
        catch (XdmfError e) {
          throw e;
        }
856 857 858 859 860 861 862
      }
      else {
        shared_ptr<XdmfArray> val2 = valueStack.top();
        valueStack.pop();
        shared_ptr<XdmfArray> val1 = valueStack.top();
        valueStack.pop();
        if (operationStack.size() == 0) {
863 864 865 866 867 868 869
          try {
            XdmfError::message(XdmfError::FATAL,
                               "Error: Not Enough Operators in evaluateExpression");
          }
          catch (XdmfError e) {
            throw e;
          }
870 871 872 873 874 875 876 877
        }
        else {
          valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
          operationStack.pop();
        }
      }
    }
  }
878

879
  // throw error if there's extra operations
880
  if (operationStack.size() > 0) {
881 882 883 884 885 886 887
    try {
      XdmfError::message(XdmfError::WARNING,
                         "Warning: Left Over Operators in evaluateExpression");
    }
    catch (XdmfError e) {
      throw e;
    }
888
  }
889

890
  if (valueStack.size() > 1) {
891 892 893 894 895 896 897
    try {
      XdmfError::message(XdmfError::WARNING,
                         "Warning: Left Over Values in evaluateExpression");
    }
    catch (XdmfError e) {
      throw e;
    }
898
  }
899

900
  return valueStack.top();
901 902 903 904 905
}

shared_ptr<XdmfArray>
XdmfArray::evaluateOperation(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2, char operation)
{
906 907 908 909 910 911
  if (operations.find(operation) != operations.end()) {
    return (*(shared_ptr<XdmfArray>(*)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>))operations[operation])(val1, val2);
  }
  else {
    return shared_ptr<XdmfArray>();
  }
912 913 914 915 916
}

int
XdmfArray::addOperation(char newoperator, shared_ptr<XdmfArray>(*operationref)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>), int priority)
{
917
  if (newoperator == '(' || newoperator == ')') {
918 919 920 921 922 923 924
    try {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Parenthesis can not be redefined");
    }
    catch (XdmfError e) {
      throw e;
    }
925
  }
926
  // give warning if the operation already exists
927
  size_t origsize = operations.size();
928 929 930 931
  // place reference in the associated location
  operations[newoperator] = operationref;
  // it's nice to let people know they're doing this so they don't get surprised about changes in behavior
  if (origsize == operations.size()) {
932 933 934 935 936 937 938
    try {
      XdmfError::message(XdmfError::WARNING,
                         "Warning: Function Overwritten");
    }
    catch (XdmfError e) {
      throw e;
    }
939 940
    // overwrite the existing info for that operation
    // add the priority to the specified location in the priority array
941 942 943 944
    size_t priorityLocation = mSupportedOperations.find(newoperator);
    mOperationPriority[priorityLocation] = priority;
  }
  else {
945 946
    // create new operation
    // as long as the operation isn't a valid function character
947
    if (mValidVariableChars.find(newoperator) != std::string::npos || mValidDigitChars.find(newoperator) != std::string::npos) {
948 949 950 951 952 953 954
      try {
        XdmfError::message(XdmfError::FATAL,
                           "Error: Operation Overlaps with Variables");
      }
      catch (XdmfError e) {
        throw e;
      }
955
    }
956 957 958
    else {
      // build the operation
      // add operation to the supported character string
959
      mSupportedOperations.push_back(newoperator);
960
      unsigned int priorityArraySize = sizeof(mOperationPriority)/sizeof(int);
961 962 963
      // first check to see if the priority array is large enough
      if (mSupportedOperations.size()-1 > priorityArraySize) {
        // if it isn't make it bigger, double size should be fine
964 965
        int newArray [priorityArraySize*2];
        std::copy(mOperationPriority, mOperationPriority+(priorityArraySize-1), newArray);
966
	*mOperationPriority = *newArray;
967 968 969 970 971 972
      }
      size_t priorityLocation = mSupportedOperations.find(newoperator);
      mOperationPriority[priorityLocation] = priority;
    }
  }
  return operations.size();
973 974
}

975
// this is how you use references to functions
976
shared_ptr<XdmfArray>
977
XdmfArray::evaluateFunction(std::vector<shared_ptr<XdmfArray> > valueVector, std::string functionName)
978
{
979 980 981 982 983 984
  if (arrayFunctions.find(functionName) != arrayFunctions.end()) {
    return (*(shared_ptr<XdmfArray>(*)(std::vector<shared_ptr<XdmfArray> >))arrayFunctions[functionName])(valueVector);
  }
  else {
    return shared_ptr<XdmfArray>();
  }
985 986
}

987 988
shared_ptr<const XdmfArrayType>
XdmfArray::getArrayType() const
989
{
990 991 992
  if (mHeavyDataControllers.size()>0) {
    return boost::apply_visitor(GetArrayType(mHeavyDataControllers[0]), 
                                mArray);
993
  }
994 995 996
  else {
    return boost::apply_visitor(GetArrayType(shared_ptr<XdmfHDF5Controller>()),
                                mArray);
997
  }
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
}

unsigned int
XdmfArray::getCapacity() const
{
  return boost::apply_visitor(GetCapacity(), 
                              mArray);
}

std::vector<unsigned int>
XdmfArray::getDimensions() const
{
  if(mDimensions.size() == 0) {
    if(!this->isInitialized() && mHeavyDataControllers.size() > 0) {
      std::vector<unsigned int> returnDimensions;
      std::vector<unsigned int> tempDimensions;
      // find the controller with the most dimensions
      int dimControllerIndex = 0;
      unsigned int dimSizeMax = 0;
      unsigned int dimTotal = 0;
      for (unsigned int i = 0; i < mHeavyDataControllers.size(); ++i) {
        dimTotal += mHeavyDataControllers[i]->getSize();
        if (mHeavyDataControllers[i]->getSize() > dimSizeMax) {
          dimSizeMax = mHeavyDataControllers[i]->getSize();
          dimControllerIndex = i;
        }
      }
      // total up the size of the lower dimensions
      int controllerDimensionSubtotal = 1;
      for (unsigned int i = 0; i < mHeavyDataControllers[dimControllerIndex]->getDimensions().size() - 1; ++i) {
        returnDimensions.push_back(mHeavyDataControllers[dimControllerIndex]->getDimensions()[i]);
        controllerDimensionSubtotal *= mHeavyDataControllers[dimControllerIndex]->getDimensions()[i];
      }
      // divide the total contained by the dimensions by the size of the lower dimensions
      returnDimensions.push_back(dimTotal/controllerDimensionSubtotal);
      return returnDimensions;
1034
    }
1035 1036
    const unsigned int size = this->getSize();
    return std::vector<unsigned int>(1, size);
1037
  }
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  return mDimensions;
}

std::string
XdmfArray::getDimensionsString() const
{
  const std::vector<unsigned int> dimensions = this->getDimensions();
  return GetValuesString(dimensions.size()).getValuesString(&dimensions[0],
                                                            dimensions.size());
}

std::map<std::string, std::string>
XdmfArray::getItemProperties() const
{
  std::map<std::string, std::string> arrayProperties;
  if(mHeavyDataControllers.size()>0) {
    arrayProperties.insert(std::make_pair("Format",
                                          mHeavyDataControllers[0]->getName()));
1056
  }
1057 1058
  else {
    arrayProperties.insert(std::make_pair("Format", "XML"));
1059
  }
1060 1061 1062 1063
  arrayProperties.insert(std::make_pair("Dimensions", 
                                        this->getDimensionsString()));
  if(mName.compare("") != 0) {
    arrayProperties.insert(std::make_pair("Name", mName));
1064
  }
1065
  shared_ptr<const XdmfArrayType> type = this->getArrayType();
1066 1067
  type->getProperties(arrayProperties);
  return arrayProperties;
1068 1069
}

1070 1071
std::string
XdmfArray::getItemTag() const
1072
{
1073
  return ItemTag;
1074 1075
}

1076 1077
std::string
XdmfArray::getName() const
1078
{
1079
  return mName;
1080 1081
}

1082 1083 1084
int
XdmfArray::getOperationPriority(char operation)
{
1085 1086 1087 1088 1089 1090 1091
  size_t operationLocation = mSupportedOperations.find(operation);
  if (operationLocation != std::string::npos) {
    return mOperationPriority[operationLocation];
  }
  else {
    return -1;
  }
1092 1093
}

1094 1095
unsigned int
XdmfArray::getSize() const
1096
{
1097
  return boost::apply_visitor(Size(this), 
1098
                              mArray);
1099 1100
}

1101 1102 1103 1104 1105 1106 1107 1108 1109
const std::string
XdmfArray::getSupportedOperations()
{
	return mSupportedOperations;
}

const std::vector<std::string>
XdmfArray::getSupportedFunctions()
{
1110 1111
  std::vector<std::string> returnVector;
  for (std::map<std::string, shared_ptr<XdmfArray>(*)(std::vector<shared_ptr<XdmfArray> >)>::iterator functionWalker = arrayFunctions.begin();
1112
       functionWalker != arrayFunctions.end(); ++functionWalker) {
1113 1114 1115
    returnVector.push_back(functionWalker->first);
  }
  return returnVector;
1116 1117 1118
}

const std::string
1119
XdmfArray::getValidDigitChars()
1120
{
1121
        return mValidDigitChars;
1122 1123 1124
}

const std::string
1125
XdmfArray::getValidVariableChars()
1126
{
1127
	return mValidVariableChars;
1128 1129
}

1130 1131
void *
XdmfArray::getValuesInternal()
1132
{
1133 1134
  return const_cast<void *>
    (static_cast<const XdmfArray &>(*this).getValuesInternal());
1135 1136
}

1137 1138
const void *
XdmfArray::getValuesInternal() const
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
1139
{
1140
  return boost::apply_visitor(GetValuesPointer(), 
1141
                              mArray);
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
1142 1143
}

1144 1145
std::string
XdmfArray::getValuesString() const
Ken Leiter (Civ ARL/CISD) kleiter's avatar
ENH:  
Ken Leiter (Civ ARL/CISD) kleiter committed
1146
{
1147
  return boost::apply_visitor(GetValuesString(mArrayPointerNumValues), 
1148
                              mArray);
Kenneth Leiter's avatar