XdmfFunction.cpp 54.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfFunction.cpp                                                    */
/*                                                                           */
/*  Author:                                                                  */
/*     Andrew Burns                                                          */
/*     andrew.j.burns2@us.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2013 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.                                                 */
/*                                                                           */
/*****************************************************************************/


#include "XdmfArray.hpp"
#include "XdmfArrayType.hpp"
#include "XdmfFunction.hpp"
28
#include "XdmfWriter.hpp"
29
#include <stack>
30
#include <cmath>
31
#include <string.h>
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
#include "XdmfError.hpp"

class XdmfFunctionInternalImpl : public XdmfFunction::XdmfFunctionInternal {
  public:
    static shared_ptr<XdmfFunctionInternalImpl>
    New(shared_ptr<XdmfArray> (*newInternal)(std::vector<shared_ptr<XdmfArray> >))
    {
      shared_ptr<XdmfFunctionInternalImpl> p (new XdmfFunctionInternalImpl(newInternal));
      return p;
    }

    ~XdmfFunctionInternalImpl()
    {
    }

    virtual shared_ptr<XdmfArray> execute(std::vector<shared_ptr<XdmfArray> > valueVector)
    {
      return (*mInternalFunction)(valueVector);
    }
  private:
    XdmfFunctionInternalImpl(shared_ptr<XdmfArray> (*newInternal)(std::vector<shared_ptr<XdmfArray> >))
    {
      mInternalFunction = newInternal;
    }

    shared_ptr<XdmfArray> (*mInternalFunction)(std::vector<shared_ptr<XdmfArray> >);
};

class XdmfOperationInternalImpl : public XdmfFunction::XdmfOperationInternal {
  public:
    static shared_ptr<XdmfOperationInternalImpl>
    New(shared_ptr<XdmfArray> (*newInternal)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>))
    {
      shared_ptr<XdmfOperationInternalImpl> p (new XdmfOperationInternalImpl(newInternal));
      return p;
    }

    ~XdmfOperationInternalImpl()
    {
    }

    virtual shared_ptr<XdmfArray> execute(shared_ptr<XdmfArray> val1,
                                          shared_ptr<XdmfArray> val2)
    {
      return (*mInternalOperation)(val1, val2);
    }
  private:
    XdmfOperationInternalImpl(shared_ptr<XdmfArray> (*newInternal)(shared_ptr<XdmfArray>,
                                                                   shared_ptr<XdmfArray>))
    {
      mInternalOperation = newInternal;
    }

    shared_ptr<XdmfArray> (*mInternalOperation)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>);
};

88
std::string XdmfFunction::mSupportedOperations = "-+/*|#()";
89 90
const std::string XdmfFunction::mValidVariableChars =
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_:.";
91
const std::string XdmfFunction::mValidDigitChars = "1234567890.";
92 93 94
// 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
95 96 97 98 99 100 101 102 103
std::map<char, int> XdmfFunction::mOperationPriority =  
  { {'-', 4}, 
    {'+', 4},
    {'/', 3},
    {'*', 3},
    {'|', 2},
    {'#', 1},
    {'{', 0},
    {'}', 0} };
104 105 106 107 108 109 110 111
// 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

// Note, it doesn't handle overloaded functions well.
// Will generate errors unless overload methods are typecast.
std::map<std::string, shared_ptr<XdmfFunction::XdmfFunctionInternal> >
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
XdmfFunction::arrayFunctions = 
  { {"ABS", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::abs)},
    {"ABS_TOKEN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
						XdmfFunction::abs)},
    {"ACOS", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					   XdmfFunction::arccos)},
    {"ASIN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					   XdmfFunction::arcsin)},
    {"ATAN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					   XdmfFunction::arctan)},
    {"AVE", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::average)},
    {"COS", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::cos)},
    {"EXP", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::exponent)},
    {"JOIN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					   XdmfFunction::join)},
    {"LOG", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::log)},
    {"SIN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::sin)},
    {"SQRT", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					   XdmfFunction::sqrt)},
    {"SUM", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::sum)},
    {"TAN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
					  XdmfFunction::tan)} };
141 142

std::map<char, shared_ptr<XdmfFunction::XdmfOperationInternal> >
143 144 145 146 147 148 149
XdmfFunction::operations = {
  {'-', XdmfOperationInternalImpl::New(XdmfFunction::subtraction)},
  {'+', XdmfOperationInternalImpl::New(XdmfFunction::addition)},
  {'*', XdmfOperationInternalImpl::New(XdmfFunction::multiplication)},
  {'/', XdmfOperationInternalImpl::New(XdmfFunction::division)},
  {'|', XdmfOperationInternalImpl::New(XdmfFunction::chunk)},
  {'#', XdmfOperationInternalImpl::New(XdmfFunction::interlace)} };
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

shared_ptr<XdmfFunction>
XdmfFunction::New()
{
  shared_ptr<XdmfFunction> p(new XdmfFunction());
  return p;
}

shared_ptr<XdmfFunction>
XdmfFunction::New(std::string newExpression,
                  std::map<std::string, shared_ptr<XdmfArray> > newVariables)
{
  shared_ptr<XdmfFunction> p(new XdmfFunction(newExpression, newVariables));
  return p;
}

XdmfFunction::XdmfFunction():
167
  mExpression("")
168 169 170 171 172 173
{
}

XdmfFunction::XdmfFunction(std::string newExpression,
                           std::map<std::string, shared_ptr<XdmfArray> > newVariables):
  mVariableList(newVariables),
174
  mExpression(newExpression)
175 176 177 178 179 180 181 182 183
{
}

XdmfFunction::~XdmfFunction()
{
}

const std::string XdmfFunction::ItemTag = "Function";

184 185 186 187 188 189 190 191 192
shared_ptr<XdmfArray>
XdmfFunction::abs(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function abs");
  }
193
  bool release = false;
194
  if (!values[0]->isInitialized()) {
195 196 197
    values[0]->read();
    release = true;
  }
198 199 200
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::abs(values[0]->getValue<double>(i)));
  }
201 202 203
  if (release) {
    values[0]->release();
  }
204 205 206
  return returnArray;
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
int
XdmfFunction::addFunction(std::string name,
                          shared_ptr<XdmfArray>(*functionref)(std::vector<shared_ptr<XdmfArray> >))
{
  shared_ptr<XdmfFunctionInternalImpl> newFunction =
     XdmfFunctionInternalImpl::New(functionref);
  return XdmfFunction::addFunction(name, newFunction);
}

int
XdmfFunction::addFunction(std::string name,
                          shared_ptr<XdmfFunctionInternal> newFunction)
{
  // 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
225 226
      XdmfError::message(XdmfError::FATAL,
                         "Error: Function Name Contains Invalid Character(s)");
227 228 229 230 231 232 233
    }
  }
  size_t origsize = arrayFunctions.size();
  arrayFunctions[name] = newFunction;
  // 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
234 235
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Function Overwritten");
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  }
  return arrayFunctions.size();
}

int
XdmfFunction::addOperation(char newoperator,
                           shared_ptr<XdmfArray>(*operationref)(shared_ptr<XdmfArray>,
                                                                shared_ptr<XdmfArray>),
                           int priority)
{
  shared_ptr<XdmfOperationInternalImpl> newOperation =
     XdmfOperationInternalImpl::New(operationref);
  return XdmfFunction::addOperation(newoperator,
                                    newOperation,
                                    priority);
}

int
XdmfFunction::addOperation(char newoperator,
                           shared_ptr<XdmfOperationInternal> newOperation,
                           int priority)
{
  if (newoperator == '(' || newoperator == ')') {
259 260
    XdmfError::message(XdmfError::FATAL,
                       "Error: Parenthesis can not be redefined");
261 262 263
  }
  if (mValidVariableChars.find(newoperator) != std::string::npos
      || mValidDigitChars.find(newoperator) != std::string::npos) {
264 265
    XdmfError::message(XdmfError::FATAL,
                       "Error: Operation Overlaps with Variables");
266 267 268 269 270 271 272 273
  }
  // Give warning if the operation already exists
  size_t origsize = operations.size();
  // Place reference in the associated location
  operations[newoperator] = newOperation;
  if (origsize == operations.size()) {
    // It's nice to let people know they're doing this
    // So they don't get surprised about changes in behavior
274 275
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Operation Overwritten");
276 277 278 279 280 281 282 283 284 285 286 287 288
    // Overwrite the existing info for that operation
    // Add the priority to the specified location in the priority array
    mOperationPriority[newoperator] = priority;
  }
  else {
    // Create new operation
    // Add operation to the supported character string
    mSupportedOperations.push_back(newoperator);
    mOperationPriority[newoperator] = priority;
  }
  return operations.size();
}

289 290 291 292
shared_ptr<XdmfArray>
XdmfFunction::addition(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
293 294 295 296 297 298 299 300 301 302
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) + val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) + val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) + val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function addition");
    }
  }
318
  if (release1) {
319
    val1->release();
320 321
  }
  if (release2) {
322
    val2->release();
323
  }
324 325 326 327 328 329 330 331 332 333 334 335
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::arcsin(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function arcsin");
  }
336
  bool release = false;
337
  if (!values[0]->isInitialized()) {
338 339 340
    values[0]->read();
    release = true;
  }
341 342 343
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(asin(values[0]->getValue<double>(i)));
  }
344 345 346
  if (release) {
    values[0]->release();
  }
347 348 349 350 351 352 353 354 355 356 357 358
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::arccos(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function arccos");
  }
359
  bool release = false;
360
  if (!values[0]->isInitialized()) {
361 362 363
    values[0]->read();
    release = true;
  }
364 365 366
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(acos(values[0]->getValue<double>(i)));
  }
367 368 369
  if (release) {
    values[0]->release();
  }
370 371 372 373 374 375 376 377 378 379 380 381
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::arctan(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function arctan");
  }
382
  bool release = false;
383
  if (!values[0]->isInitialized()) {
384 385 386
    values[0]->read();
    release = true;
  }
387 388 389
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(atan(values[0]->getValue<double>(i)));
  }
390 391 392
  if (release) {
    values[0]->release();
  }
393 394 395
  return returnArray;
}

396 397 398
shared_ptr<XdmfArray>
XdmfFunction::average(std::vector<shared_ptr<XdmfArray> > values)
{
399 400
  double total = sum(values)->getValue<double>(0);;
  int totalSize = 0;
401
  bool release = false;
402 403
  for (unsigned int i = 0; i < values.size(); ++i)
  {
404 405 406 407 408
    release = false;
    if (!values[i]->isInitialized()) {
      values[i]->read();
      release = true;
    }
409
    totalSize += values[i]->getSize();
410 411 412
    if (release) {
      values[i]->release();
    }
413 414 415 416
  }
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  returnArray->insert(0, total/totalSize);
  return returnArray;
417 418
}

419 420 421 422 423 424 425 426 427
shared_ptr<XdmfArray>
XdmfFunction::cos(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function cos");
  }
428
  bool release = false;
429
  if (!values[0]->isInitialized()) {
430 431 432
    values[0]->read();
    release = true;
  }
433 434 435
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::cos(values[0]->getValue<double>(i)));
  }
436 437 438
  if (release) {
    values[0]->release();
  }
439 440 441
  return returnArray;
}

442 443 444 445 446 447 448 449 450 451 452
shared_ptr<XdmfArray>
XdmfFunction::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();
  // Determining what type to class it as in order to not lose data
  // and to still have the smallest data type of the two
  shared_ptr<const XdmfArrayType> resultType =
    XdmfArrayType::comparePrecision(val1->getArrayType(),
                                    val2->getArrayType());
453 454 455 456 457 458 459 460 461 462
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
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
  if (resultType == XdmfArrayType::Int8()) {
    char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int16()) {
    short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int32()) {
    int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int64()) {
    long sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt8()) {
    unsigned char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt16()) {
    unsigned short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt32()) {
    unsigned int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float32()) {
    float sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float64()) {
    double sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::String()) {
    std::string sampleValue = "";
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else {
    // error type not supported
    XdmfError::message(XdmfError::FATAL, "Invalid type during Chunk");
  }
  returnArray->insert(0, val1, 0, val1->getSize(),  1, 1);
  returnArray->insert(val1->getSize(), val2, 0, val2->getSize(), 1, 1);
509
  if (release1) {
510
    val1->release();
511 512
  }
  if (release2) {
513
    val2->release();
514
  }
515 516 517
  return returnArray;
}

518 519 520 521 522 523 524 525 526
shared_ptr<XdmfArray>
XdmfFunction::exponent(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 2) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: Two Arrays Needed for Function exponent");
  }
527 528 529 530 531 532 533 534 535 536
  bool release1 = false;
  bool release2 = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release1 = true;
  }
  if (!values[1]->isInitialized()) {
    values[1]->read();
    release2 = true;
  }
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
  for (unsigned int i = 0; i < values[0]->getSize() || i < values[1]->getSize(); ++i) {
    if (values[0]->getSize() == values[1]->getSize()) {
      returnArray->pushBack(std::pow(values[0]->getValue<double>(i), values[1]->getValue<double>(i)));
    }
    else if (values[0]->getSize() == 1) {
      returnArray->pushBack(std::pow(values[0]->getValue<double>(0), values[1]->getValue<double>(i)));
    }
    else if (values[1]->getSize() == 1) {
      returnArray->pushBack(std::pow(values[0]->getValue<double>(i), values[1]->getValue<double>(0)));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function exponent");
    }
  }
552
  if (release1) {
553
    values[0]->release();
554 555
  }
  if (release2) {
556
    values[1]->release();
557
  }
558 559 560 561 562 563
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::division(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
564 565 566 567 568 569 570 571 572 573
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) / val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) / val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) / val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function division");
    }
  }
590
  if (release1) {
591
    val1->release();
592 593
  }
  if (release2) {
594
    val2->release();
595
  }
596 597 598
  return returnArray;
}

599 600 601 602 603 604 605 606 607 608 609
shared_ptr<XdmfArray>
XdmfFunction::evaluateExpression(std::string expression,
                                 std::map<std::string,
                                   shared_ptr<XdmfArray> > variables)
{
  std::stack<shared_ptr<XdmfArray> > valueStack;
  std::stack<char> operationStack;

  // 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) {
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    bool hyphenIsDigit = false;
    // hyphen is a special case since it can be used to annotate negative numbers
    if (expression[i] == '-') {
      if (i == 0) {
        //would have to be a digit, otherwise it would be a unpaired operation
        hyphenIsDigit = true;
      }
      else if (mValidDigitChars.find(expression[i+1]) != std::string::npos) {
        // If value after is a valid digit,
        // check value before
        // If a digit, it's an operation
        // If a variable, it's an operation
        // If an operation, it's a digit character
        if (mSupportedOperations.find(expression[i-1]) != std::string::npos) {
          hyphenIsDigit = true;
        }
        else if (expression[i-1] <= ' ') {
          // If whitespace is in front of the hyphen it is presumed to be a negative sign
          // This is to handle passing negative values to functions properly
          hyphenIsDigit = true;
        }
      }
    }
633
    // Found to be a digit
634
    if (mValidDigitChars.find(expression[i]) != std::string::npos ||
635
        (expression[i] == '-' && hyphenIsDigit)) {
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
      // Progress until a non-digit is found
      int valueStart = i;
      if (i + 1 < expression.size()) {
        while (mValidDigitChars.find(expression[i+1]) != std::string::npos) {
          i++;
        }
      }
      // Push back to the value stack
      shared_ptr<XdmfArray> valueArray = XdmfArray::New();
      // Use this to convert to double
      valueArray->insert(0, atof(expression.substr(valueStart, i + 1 - valueStart).c_str()));
      valueStack.push(valueArray);
    }
    else if (mValidVariableChars.find(expression[i]) != std::string::npos) {
      // Found to be a variable
      int valueStart = i;
      // Progress until a nonvariable value is found
      if (i+1 < expression.size()){
        while (mValidVariableChars.find(expression[i+1]) != std::string::npos) {
          i++;
        }
      }
      // Convert to equivalent
      if (variables.find(expression.substr(valueStart, i + 1 - valueStart))
          == variables.end()) {
        if (arrayFunctions.find(expression.substr(valueStart, i + 1 - valueStart))
            == arrayFunctions.end()) {
663 664 665
          XdmfError::message(XdmfError::FATAL,
                             "Error: Invalid Variable in evaluateExpression "
                             + expression.substr(valueStart, i + 1 - valueStart));
666 667 668 669 670 671 672
        }
        else {
          std::string currentFunction =
            expression.substr(valueStart, i + 1 - valueStart);
          // Check if next character is an open parenthesis
          if (i+1 >= expression.size()) {
            if (expression[i+1] != '(') {
673 674 675
              XdmfError::message(XdmfError::FATAL,
                                 "Error: No values supplied to function "
                                 + expression.substr(valueStart, i + 1 - valueStart));
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
            }
          }
          // 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));
          }
          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;
          // Split that string at commas
          size_t parameterSplit = 0;
          while (parameterSplit != std::string::npos) {
            parameterSplit = 0;
            parameterSplit = functionParameters.find_first_of(",", parameterSplit);
            // Feed the substrings to the parse function
            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 {
        // Push equivalent to value stack
        valueStack.push(variables.find(expression.substr(valueStart, i + 1 - valueStart))->second);
      }
    }
    else if (mSupportedOperations.find(expression[i]) != std::string::npos) {
      // Found to be an operation
725
      // Pop operations off the stack until one of a lower or equal importance is found
726 727 728 729 730 731
      if (operationStack.size() > 0) {
        if (expression[i] == ')') {
          // To close a parenthesis pop off all operations until another parentheis is found
          while (operationStack.size() > 0 && operationStack.top() != '(') {
            // Must be at least two values for this loop to work properly
            if (valueStack.size() < 2) {
732 733
              XdmfError::message(XdmfError::FATAL,
                                 "Error: Not Enough Values in evaluateExpression");
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
            }
            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] == '(') {
          // Just add it if it's a start parenthesis
          // Nothing happens here in that case
          // Addition happens after the if statement
        }
        else {
          int operationLocation = getOperationPriority(expression[i]);
          int topOperationLocation = getOperationPriority(operationStack.top());
          // See order of operations to determine importance
          while (operationStack.size() > 0 && operationLocation < topOperationLocation) {
            // Must be at least two values for this loop to work properly
            if (valueStack.size() < 2) {
758 759
              XdmfError::message(XdmfError::FATAL,
                                 "Error: Not Enough Values in evaluateExpression");
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
            }
            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] != ')') {
        // Add the operation to the operation stack
        operationStack.push(expression[i]);
      }
    }
    // If not a value or operation the character is ignored
  }

  // Empty what's left in the stacks before finishing
  while (valueStack.size() > 1 && operationStack.size() > 0) {
    if (valueStack.size() < 2) {
      // Must be at least two values for this loop to work properly
788 789
      XdmfError::message(XdmfError::FATAL,
                         "Error: Not Enough Values in evaluateExpression");
790 791 792
    }
    else {
      if(operationStack.top() == '(') {
793 794
        XdmfError::message(XdmfError::WARNING,
                           "Warning: Unpaired Parenthesis");
795 796 797 798 799 800 801
      }
      else {
        shared_ptr<XdmfArray> val2 = valueStack.top();
        valueStack.pop();
        shared_ptr<XdmfArray> val1 = valueStack.top();
        valueStack.pop();
        if (operationStack.size() == 0) {
802 803
          XdmfError::message(XdmfError::FATAL,
                             "Error: Not Enough Operators in evaluateExpression");
804 805 806 807 808 809 810 811 812 813 814
        }
        else {
          valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
          operationStack.pop();
        }
      }
    }
  }

  // Throw error if there's extra operations
  if (operationStack.size() > 0) {
815 816
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Left Over Operators in evaluateExpression");
817 818 819
  }

  if (valueStack.size() > 1) {
820 821
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Left Over Values in evaluateExpression");
822 823
  }

824 825 826 827 828 829 830 831
  // Ensure that an array is returned
  // Will error out if this is not done.
  if (valueStack.size() > 0) {
    return valueStack.top();
  }
  else {
    return XdmfArray::New();
  }
832 833 834 835
}

shared_ptr<XdmfArray>
XdmfFunction::evaluateOperation(shared_ptr<XdmfArray> val1,
836 837
				shared_ptr<XdmfArray> val2,
				char operation)
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
{
  if (operations.find(operation) != operations.end()) {
    return operations[operation]->execute(val1, val2);
  }
  else {
    return shared_ptr<XdmfArray>();
  }
}

shared_ptr<XdmfArray>
XdmfFunction::evaluateFunction(std::vector<shared_ptr<XdmfArray> > valueVector,
                            std::string functionName)
{
  if (arrayFunctions.find(functionName) != arrayFunctions.end()) {
    return arrayFunctions[functionName]->execute(valueVector);
  }
  else {
    return shared_ptr<XdmfArray>();
  }
}

std::string
860
XdmfFunction::getExpression() const
861
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
862
  return mExpression;
863 864 865 866 867 868 869 870 871 872 873
}

std::string
XdmfFunction::getItemTag() const
{
  return ItemTag;
}

std::map<std::string, std::string>
XdmfFunction::getItemProperties() const
{
874
  std::map<std::string, std::string> functionProperties = XdmfArrayReference::getItemProperties();
875 876 877

  functionProperties["Expression"] = mExpression;

878 879 880 881 882 883 884 885 886 887
  std::stringstream variableStream;

  for (std::map<std::string, shared_ptr<XdmfArray> >::const_iterator variableIter = mVariableList.begin();
       variableIter != mVariableList.end();
       ++variableIter) {
    variableStream << "|" << variableIter->first;
  }

  functionProperties["VariableNames"] = variableStream.str();

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  return functionProperties;
}

int
XdmfFunction::getOperationPriority(char operation)
{
  size_t operationLocation = mSupportedOperations.find(operation);
  if (operationLocation != std::string::npos) {
    return mOperationPriority[operation];
  }
  else {
    return -1;
  }
}


const std::string
XdmfFunction::getSupportedOperations()
{
        return mSupportedOperations;
}

const std::vector<std::string>
XdmfFunction::getSupportedFunctions()
{
  std::vector<std::string> returnVector;
  for (std::map<std::string, shared_ptr<XdmfFunctionInternal> >::iterator functionWalker
       = arrayFunctions.begin();
       functionWalker != arrayFunctions.end();
       ++functionWalker) {
    returnVector.push_back(functionWalker->first);
  }
  return returnVector;
}

const std::string
XdmfFunction::getValidDigitChars()
{
        return mValidDigitChars;
}

const std::string
XdmfFunction::getValidVariableChars()
{
        return mValidVariableChars;
}

shared_ptr<XdmfArray>
XdmfFunction::getVariable(std::string key)
{
938 939 940 941 942 943
  if (mVariableList.count(key) > 0) {
    return mVariableList[key];
  }
  else {
    return shared_ptr<XdmfArray>();
  }
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
}

std::vector<std::string>
XdmfFunction::getVariableList()
{
  std::vector<std::string> keyAccumulator;
  for (std::map<std::string, shared_ptr<XdmfArray> >::iterator it = mVariableList.begin();
       it != mVariableList.end();
       ++it) {
    keyAccumulator.push_back(it->first);
  }
  return keyAccumulator;
}

shared_ptr<XdmfArray>
XdmfFunction::interlace(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  // Join interlace (evenly space the second array within the first one)
  // Builds a new array
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Resize to the combined size of both arrays
  // Determining what type to class it as in order to not lose data
  // and to still have the smallest data type of the two
  shared_ptr<const XdmfArrayType> resultType =
    XdmfArrayType::comparePrecision(val1->getArrayType(), val2->getArrayType());
969 970 971 972 973 974 975 976 977 978
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 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 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  if (resultType == XdmfArrayType::Int8()) {
    char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int16()) {
    short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int32()) {
    int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int64()) {
    long sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt8()) {
    unsigned char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt16()) {
    unsigned short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt32()) {
    unsigned int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float32()) {
    float sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float64()) {
    double sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::String()) {
    std::string sampleValue = "";
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else {
    // error type not supported
    XdmfError::message(XdmfError::FATAL, "Invalid type during Interlace");
  }

  // Determine ratio of array sizes
  int arrayRatio1 = (int)floor(static_cast<double>(val1->getSize())/val2->getSize());
  int arrayRatio2 = (int)floor(static_cast<double>(val2->getSize())/val1->getSize());
  if (arrayRatio1 < 1) {
    arrayRatio1 = 1;
  }
  if (arrayRatio2 < 1) {
    arrayRatio2 = 1;
  }
  // Stride is equal to the ratios rounded up and added together
  int stride = arrayRatio1+arrayRatio2;
  int arrayExcess1 = 0;
  int arrayExcess2 = 0;
  for (int i = 0; i < stride; ++i) {
    // Add the values of each array
    // using strides to interlace and starting index to offset
    // first array gets the first value of the new array
    if (i<arrayRatio1) {
      int amountWritten = val1->getSize()/arrayRatio1;
      if (((amountWritten * arrayRatio1) + i) < (int)val1->getSize()) {
        amountWritten++;
      }
1046 1047 1048
      if (amountWritten > floor(static_cast<double>(val2->getSize())/arrayRatio2)) {
        arrayExcess1 += amountWritten - (int)floor(static_cast<double>(val2->getSize())/arrayRatio2);
        amountWritten = (int)floor(static_cast<double>(val2->getSize())/arrayRatio2);
1049 1050 1051 1052 1053 1054 1055 1056 1057
      }
      returnArray->insert(i, val1, i, amountWritten, stride, arrayRatio1);
    }
    else {
      // Second array takes the rest
      int amountWritten = val2->getSize()/arrayRatio2;
      if (((amountWritten * arrayRatio2) + i) < (int)val2->getSize()) {
        amountWritten++;
      }
1058 1059 1060
      if (amountWritten > floor(static_cast<double>(val1->getSize())/arrayRatio1)) {
        arrayExcess2 += amountWritten - (int)floor(static_cast<double>(val1->getSize())/arrayRatio1);
        amountWritten = (int)floor(static_cast<double>(val1->getSize())/arrayRatio1);
1061 1062 1063 1064 1065 1066 1067
      }
      returnArray->insert(i, val2, i-arrayRatio1, amountWritten, stride, arrayRatio2);
    }
  }
  if (arrayExcess1 > 0) {
    returnArray->insert(val1->getSize()+val2->getSize()-arrayExcess1,
                        val1,
1068
                        val1->getSize()-arrayExcess1,
1069 1070 1071 1072 1073 1074 1075
                        arrayExcess1,
                        1,
                        1);
  }
  else if (arrayExcess2 > 0) {
    returnArray->insert(val1->getSize()+val2->getSize()-arrayExcess2,
                        val2,
1076
                        val2->getSize()-arrayExcess2,
1077 1078 1079 1080 1081
                        arrayExcess2,
                        1,
                        1);
  }
  // After all inserts are done, add the excess values to the end of the array
1082
  if (release1) {
1083
    val1->release();
1084 1085
  }
  if (release2) {
1086
    val2->release();
1087
  }
1088 1089 1090 1091 1092 1093 1094
  return returnArray;
}

void
XdmfFunction::insertVariable(std::string key, shared_ptr<XdmfArray> value)
{
  mVariableList[key] = value;
1095
  this->setIsChanged(true);
1096 1097
}

1098 1099 1100 1101
shared_ptr<XdmfArray>
XdmfFunction::join(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
1102
  bool release = false;
1103
  for (unsigned int i = 0; i < values.size(); ++i) {
1104 1105 1106 1107 1108
    release = false;
    if (!values[i]->isInitialized()) {
      values[i]->read();
      release = true;
    }
1109 1110 1111 1112 1113 1114
    returnArray->insert(returnArray->getSize(),
                        values[i],
                        0,
                        values[i]->getSize(),
                        1,
                        1);
1115 1116 1117
    if (release) {
      values[i]->release();
    }
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::log(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function log");
  }
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
  bool release1 = false;
  bool release2 = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release1 = true;
  }
  if (values.size() > 1) {
    if (!values[1]->isInitialized()) {
      values[1]->read();
      release2 = true;
    }
  }
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    if (values.size() > 1) {
      if (values[0]->getSize() == values[1]->getSize()) {
        returnArray->pushBack(std::log(values[0]->getValue<double>(i))/std::log(values[1]->getValue<double>(i)));
      }
      else if (values[1]->getSize() == 1) {
        returnArray->pushBack(std::log(values[0]->getValue<double>(i))/std::log(values[1]->getValue<double>(0)));
      }
      else {
        XdmfError::message(XdmfError::FATAL,
                           "Error: Array Size Missmatch in Function Log");
      }
    }
    else {
      returnArray->pushBack(std::log(values[0]->getValue<double>(i)));
    }
  }
1160
  if (release1) {
1161
    values[0]->release();
1162 1163
  }
  if (release2) {
1164
    values[1]->release();
1165
  }
1166 1167 1168 1169 1170 1171 1172
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::multiplication(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) * val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) * val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) * val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function multiplication");
    }
  }
1198
  if (release1) {
1199
    val1->release();
1200 1201
  }
  if (release2) {
1202
    val2->release();
1203
  }
1204 1205 1206 1207
  return returnArray;
}


1208
shared_ptr<XdmfArray>
1209
XdmfFunction::read() const
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
{
  return evaluateExpression(mExpression, mVariableList);
}

void
XdmfFunction::removeVariable(std::string key)
{
  std::map<std::string, shared_ptr<XdmfArray> >::iterator removeWalker =
    mVariableList.find(key);
  if (removeWalker != mVariableList.end()) {
    mVariableList.erase(removeWalker);
  }
1222
  this->setIsChanged(true);
1223 1224 1225 1226 1227
}

void
XdmfFunction::setExpression(std::string newExpression)
{
Andrew J. Burns (Cont's avatar
Andrew J. Burns (Cont committed
1228
  mExpression = newExpression;
1229
  this->setIsChanged(true);
1230 1231
}

1232 1233 1234 1235 1236 1237 1238 1239 1240
shared_ptr<XdmfArray>
XdmfFunction::sin(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function sin");
  }
1241
  bool release = false;
1242
  if (!values[0]->isInitialized()) {
1243 1244 1245
    values[0]->read();
    release = true;
  }
1246 1247 1248
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::sin(values[0]->getValue<double>(i)));
  }
1249 1250 1251
  if (release) {
    values[0]->release();
  }
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::sqrt(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function sqrt");
  }
1264
  bool release = false;
1265
  if (!values[0]->isInitialized()) {
1266 1267 1268
    values[0]->read();
    release = true;
  }
1269 1270 1271
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::sqrt(values[0]->getValue<double>(i)));
  }
1272 1273 1274
  if (release) {
    values[0]->release();
  }
1275 1276 1277 1278 1279 1280 1281
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::subtraction(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) - val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) - val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) - val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function subtraction");
    }
  }
1307
  if (release1) {
1308
    val1->release();
1309 1310
  }
  if (release2) {
1311
    val2->release();
1312
  }
1313 1314 1315
  return returnArray;
}

1316 1317 1318 1319
shared_ptr<XdmfArray>
XdmfFunction::sum(std::vector<shared_ptr<XdmfArray> > values)
{
  double total = 0.0;
1320
  bool release = false;
1321
  for (unsigned int i = 0; i < values.size(); ++i) {
1322
    release = false;
1323
    if (!values[i]->isInitialized()) {
1324 1325 1326
      values[i]->read();
      release = true;
    }
1327 1328 1329
    for (unsigned int j = 0; j < values[i]->getSize(); ++j) {
      total += values[i]->getValue<double>(j);
    }
1330 1331 1332
    if (release) {
      values[i]->release();
    }
1333 1334 1335 1336 1337 1338
  }
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  returnArray->insert(0, total);
  return returnArray;
}

1339 1340 1341 1342 1343 1344 1345 1346 1347
shared_ptr<XdmfArray>
XdmfFunction::tan(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function tan");
  }
1348
  bool release = false;
1349
  if (!values[0]->isInitialized()) {
1350 1351 1352
    values[0]->read();
    release = true;
  }
1353 1354 1355
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::tan(values[0]->getValue<double>(i)));
  }
1356 1357 1358
  if (release) {
    values[0]->release();
  }
1359 1360 1361
  return returnArray;
}

1362 1363 1364 1365 1366
void
XdmfFunction::traverse(const shared_ptr<XdmfBaseVisitor> visitor)
{
  XdmfItem::traverse(visitor);

1367 1368 1369 1370 1371 1372 1373 1374
  bool originalXPath;

  if (shared_ptr<XdmfWriter> writer =
        shared_dynamic_cast<XdmfWriter>(visitor)) {
    originalXPath = writer->getWriteXPaths();
    writer->setWriteXPaths(false);
  }

1375 1376 1377 1378
  shared_ptr<XdmfArray> spacerarray = XdmfArray::New();
  spacerarray->pushBack((int)0);
  spacerarray->accept(visitor);

1379 1380 1381 1382 1383
  if (shared_ptr<XdmfWriter> writer =
        shared_dynamic_cast<XdmfWriter>(visitor)) {
    writer->setWriteXPaths(originalXPath);
  } 

1384 1385 1386 1387 1388 1389
  for (std::map<std::string, shared_ptr<XdmfArray> >::iterator it = mVariableList.begin();
       it != mVariableList.end();
       ++it) {
    it->second->accept(visitor);
  }
}
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

// C Wrappers

class XdmfCFunctionInternalImpl : public XdmfFunction::XdmfFunctionInternal {
  public:
    static shared_ptr<XdmfCFunctionInternalImpl>
    New(XDMFARRAY * (*newInternal)(XDMFARRAY **, unsigned int))
    {
      shared_ptr<XdmfCFunctionInternalImpl> p (new XdmfCFunctionInternalImpl(newInternal));
      return p;
    }

    ~XdmfCFunctionInternalImpl()
    {
    }

    virtual shared_ptr<XdmfArray> execute(std::vector<shared_ptr<XdmfArray> > valueVector)
    {
      XDMFARRAY ** valueArray = new XDMFARRAY *[valueVector.size()]();
      for (unsigned int i = 0; i < valueVector.size(); ++i) {
1410
        valueArray[i] = (XDMFARRAY *)(&valueVector[i]);
1411
      }
1412 1413 1414 1415 1416
      shared_ptr<XdmfArray> * ptr = (shared_ptr<XdmfArray> *)((*mInternalFunction)(valueArray, valueVector.size()));
      shared_ptr<XdmfArray> ptrCopy = *ptr;
      delete ptr;
      delete [] valueArray;
      return ptrCopy;
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    }
  private:
    XdmfCFunctionInternalImpl(XDMFARRAY * (*newInternal)(XDMFARRAY **, unsigned int))
    {
      mInternalFunction = newInternal;
    }

    XDMFARRAY * (*mInternalFunction)(XDMFARRAY **, unsigned int);
};

class XdmfCOperationInternalImpl : public XdmfFunction::XdmfOperationInternal {
  public:
    static shared_ptr<XdmfCOperationInternalImpl>
    New(XDMFARRAY * (*newInternal)(XDMFARRAY *, XDMFARRAY *))
    {
      shared_ptr<XdmfCOperationInternalImpl> p (new XdmfCOperationInternalImpl(newInternal));
      return p;
    }

    ~XdmfCOperationInternalImpl()
    {
    }

    virtual shared_ptr<XdmfArray> execute(shared_ptr<XdmfArray> val1,
                                          shared_ptr<XdmfArray> val2)
    {
1443 1444 1445 1446
      shared_ptr<XdmfArray> * ptr = (shared_ptr<XdmfArray> *)((*mInternalOperation)((XDMFARRAY*)&val1, (XDMFARRAY*)&val2));
      shared_ptr<XdmfArray> ptrCopy = *ptr;
      delete ptr;
      return ptrCopy;
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    }
  private:
    XdmfCOperationInternalImpl(XDMFARRAY * (*newInternal)(XDMFARRAY *, XDMFARRAY *))
    {
      mInternalOperation = newInternal;
    }

    XDMFARRAY * (*mInternalOperation)(XDMFARRAY *, XDMFARRAY *);
};

XDMFFUNCTION * XdmfFunctionNew()
{
1459 1460
  shared_ptr<XdmfFunction> * p = new shared_ptr<XdmfFunction>(XdmfFunction::New());
  return (XDMFFUNCTION *) p;
1461 1462 1463 1464
}

XDMFFUNCTION * XdmfFunctionNewInit(char * newExpression,  char ** keys, XDMFARRAY ** values, int numVariables)
{
1465 1466 1467
  std::map<std::string, shared_ptr<XdmfArray> > variableMap;
  for (int i = 0; i < numVariables; ++i) {
    variableMap[keys[i]] = *(shared_ptr<XdmfArray> *)(values[i]);
1468
  }
1469 1470
  shared_ptr<XdmfFunction> * p = new shared_ptr<XdmfFunction>(XdmfFunction::New(newExpression, variableMap));
  return (XDMFFUNCTION *) p;
1471 1472 1473 1474 1475
}

int XdmfFunctionAddFunction(char * name, XDMFARRAY *(*functionref)(XDMFARRAY **, unsigned int), int * status)
{
  XDMF_ERROR_WRAP_START(status)
1476 1477 1478
  shared_ptr<XdmfCFunctionInternalImpl> newFunction =
    XdmfCFunctionInternalImpl::New(functionref);
  return XdmfFunction::addFunction(name, newFunction);
1479 1480 1481 1482 1483 1484 1485
  XDMF_ERROR_WRAP_END(status)
  return -1;
}

int XdmfFunctionAddOperation(char newoperator, XDMFARRAY *(*operationref)(XDMFARRAY *, XDMFARRAY *), int priority, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1486 1487 1488 1489 1490
  shared_ptr<XdmfCOperationInternalImpl> newOperation =
    XdmfCOperationInternalImpl::New(operationref);
  return XdmfFunction::addOperation(newoperator,
				    newOperation,
				    priority);
1491 1492 1493 1494 1495 1496
  XDMF_ERROR_WRAP_END(status)
  return -1;
}

XDMFARRAY * XdmfFunctionAverage(XDMFARRAY ** values, int numValues)
{
1497 1498 1499
  std::vector<shared_ptr<XdmfArray> > valueVector;
  for (int i = 0; i < numValues; ++i) {
    valueVector.push_back(*(shared_ptr<XdmfArray> *)values[i]);
1500
  }
1501 1502
  shared_ptr<XdmfArray> * average = new shared_ptr<XdmfArray>(XdmfFunction::average(valueVector));
  return (XDMFARRAY *) average;
1503 1504 1505 1506 1507
}

XDMFARRAY * XdmfFunctionChunk(XDMFARRAY * val1, XDMFARRAY * val2, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1508 1509 1510 1511
  shared_ptr<XdmfArray> & refVal1 = *(shared_ptr<XdmfArray> *)(val1);
  shared_ptr<XdmfArray> & refVal2 = *(shared_ptr<XdmfArray> *)(val2);
  shared_ptr<XdmfArray> * chunk = new shared_ptr<XdmfArray>(XdmfFunction::chunk(refVal1, refVal2));
  return (XDMFARRAY *) chunk;
1512 1513 1514 1515 1516 1517 1518
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

XDMFARRAY * XdmfFunctionEvaluateExpression(char * expression, char ** keys, XDMFARRAY ** values, int numVariables, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1519 1520 1521
  std::map<std::string, shared_ptr<XdmfArray> > variableMap;
  for (int i = 0; i < numVariables; ++i) {
    variableMap[keys[i]] = *(shared_ptr<XdmfArray> *)values[i];
1522
  }
1523 1524
  shared_ptr<XdmfArray> * generatedArray = new shared_ptr<XdmfArray>(XdmfFunction::evaluateExpression(expression, variableMap));
  return (XDMFARRAY *) generatedArray;
1525 1526 1527 1528 1529 1530 1531
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

XDMFARRAY * XdmfFunctionEvaluateOperation(XDMFARRAY * val1, XDMFARRAY * val2, char operation, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1532 1533 1534 1535
  shared_ptr<XdmfArray> & refVal1 = *(shared_ptr<XdmfArray> *)(val1);
  shared_ptr<XdmfArray> & refVal2 = *(shared_ptr<XdmfArray> *)(val2);
  shared_ptr<XdmfArray> * generatedArray = new shared_ptr<XdmfArray>(XdmfFunction::evaluateOperation(refVal1, refVal2, operation));
  return (XDMFARRAY *) generatedArray;
1536 1537 1538 1539 1540 1541 1542
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

XDMFARRAY * XdmfFunctionEvaluateFunction(XDMFARRAY ** valueVector, int numValues, char * functionName, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1543 1544 1545
  std::vector<shared_ptr<XdmfArray> > evaluatedVector;
  for (int i = 0; i < numValues; ++i) {
    evaluatedVector.push_back(*(shared_ptr<XdmfArray> *)valueVector[i]);
1546
  }
1547 1548
  shared_ptr<XdmfArray> * generatedArray = new shared_ptr<XdmfArray>(XdmfFunction::evaluateFunction(evaluatedVector, functionName));
  return (XDMFARRAY *) generatedArray;
1549
  XDMF_ERROR_WRAP_END(status)
1550
    return NULL;
1551 1552 1553 1554
}

char * XdmfFunctionGetExpression(XDMFFUNCTION * function)
{
1555 1556 1557
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function);
  char * returnPointer = strdup(refFunction->getExpression().c_str());
  return returnPointer;
1558 1559 1560 1561
}

unsigned int XdmfFunctionGetNumberVariables(XDMFFUNCTION * function)
{
1562 1563
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function);
  return refFunction->getVariableList().size();
1564 1565 1566 1567 1568 1569 1570 1571 1572
}

int XdmfFunctionGetOperationPriority(char operation)
{
  return XdmfFunction::getOperationPriority(operation);
}

char * XdmfFunctionGetSupportedOperations()
{
1573
  return strdup(XdmfFunction::getSupportedOperations().c_str());
1574 1575 1576 1577
}

char ** XdmfFunctionGetSupportedFunctions()
{
1578 1579 1580 1581
  std::vector<std::string> supportedFunctions = XdmfFunction::getSupportedFunctions();
  char ** returnPointer = (char **) malloc(sizeof(char *) * (supportedFunctions.size() + 1));
  for (unsigned int i = 0; i < supportedFunctions.size(); ++i) {
    returnPointer[i] = strdup(supportedFunctions[i].c_str());
1582
  }
1583 1584
  returnPointer[supportedFunctions.size()] = NULL;
  return returnPointer;
1585 1586 1587 1588 1589 1590 1591 1592 1593
}

unsigned int XdmfFunctionGetNumberSupportedFunctions()
{
  return XdmfFunction::getSupportedFunctions().size();
}

char * XdmfFunctionGetValidDigitChars()
{
1594
  return strdup(XdmfFunction::getValidDigitChars().c_str());
1595 1596 1597 1598
}

char * XdmfFunctionGetValidVariableChars()
{
1599
  return strdup(XdmfFunction::getValidVariableChars().c_str());
1600 1601 1602 1603
}

XDMFARRAY * XdmfFunctionGetVariable(XDMFFUNCTION * function, char * key)
{
1604 1605 1606
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function); 
  shared_ptr<XdmfArray> * returnArray = new shared_ptr<XdmfArray>(refFunction->getVariable(key));
  return (XDMFARRAY *) returnArray;
1607 1608 1609 1610
}

char ** XdmfFunctionGetVariableList(XDMFFUNCTION * function)
{
1611 1612 1613 1614 1615
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function); 
  const std::vector<std::string> variablelist = refFunction->getVariableList();
  char ** returnpointer = (char **) malloc(sizeof(char *) * (variablelist.size() + 1));
  for (unsigned int i = 0; i < variablelist.size(); ++i) {
    returnpointer[i] = strdup(variablelist[i].c_str());
1616
  }
1617 1618
  returnpointer[variablelist.size()] = NULL; // end of list
  return returnpointer;
1619 1620 1621 1622 1623
}

XDMFARRAY * XdmfFunctionInterlace(XDMFARRAY * val1, XDMFARRAY * val2, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1624 1625 1626 1627
  shared_ptr<XdmfArray> & refVal1 = *(shared_ptr<XdmfArray> *)(val1);
  shared_ptr<XdmfArray> & refVal2 = *(shared_ptr<XdmfArray> *)(val2);
  shared_ptr<XdmfArray> * interlace = new shared_ptr<XdmfArray>(XdmfFunction::interlace(refVal1, refVal2));
  return (XDMFARRAY *) interlace;
1628 1629 1630 1631 1632 1633
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

void XdmfFunctionInsertVariable(XDMFFUNCTION * function, char * key, XDMFARRAY * value, int passControl)
{
1634 1635 1636
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function); 
  shared_ptr<XdmfArray> & refValue = *(shared_ptr<XdmfArray> *)(value);
  refFunction->insertVariable(key, refValue);
1637 1638 1639 1640
}

void XdmfFunctionRemoveVariable(XDMFFUNCTION * function, char * key)
{
1641 1642
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function); 
  refFunction->removeVariable(key);
1643 1644 1645 1646 1647
}

void XdmfFunctionSetExpression(XDMFFUNCTION * function, char * newExpression, int * status)
{
  XDMF_ERROR_WRAP_START(status)
1648 1649
  shared_ptr<XdmfFunction> & refFunction = *(shared_ptr<XdmfFunction> *)(function); 
  refFunction->setExpression(newExpression);
1650 1651 1652 1653 1654
  XDMF_ERROR_WRAP_END(status)
}

XDMFARRAY * XdmfFunctionSum(XDMFARRAY ** values, int numValues)
{
1655 1656 1657
  std::vector<shared_ptr<XdmfArray> > valueVector;
  for (int i = 0; i < numValues; ++i) {
    valueVector.push_back(*(shared_ptr<XdmfArray> *)values[i]);
1658
  }
1659 1660
  shared_ptr<XdmfArray> * sum = new shared_ptr<XdmfArray>(XdmfFunction::sum(valueVector));
  return (XDMFARRAY *) sum;
1661 1662 1663 1664 1665 1666
}

// C Wrappers for parent classes are generated by macros

XDMF_ITEM_C_CHILD_WRAPPER(XdmfFunction, XDMFFUNCTION)
XDMF_ARRAYREFERENCE_C_CHILD_WRAPPER(XdmfFunction, XDMFFUNCTION)