/[escript]/trunk/escript/src/Data.cpp
ViewVC logotype

Diff of /trunk/escript/src/Data.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/esys2/escript/src/Data/Data.cpp revision 122 by jgs, Thu Jun 9 05:38:05 2005 UTC temp/escript/src/Data.cpp revision 1387 by trankine, Fri Jan 11 07:45:26 2008 UTC
# Line 1  Line 1 
 // $Id$  
 /*=============================================================================  
1    
2   ******************************************************************************  /* $Id$ */
  *                                                                            *  
  *       COPYRIGHT ACcESS 2004 -  All Rights Reserved                         *  
  *                                                                            *  
  * This software is the property of ACcESS.  No part of this code             *  
  * may be copied in any form or by any means without the expressed written    *  
  * consent of ACcESS.  Copying, use or modification of this software          *  
  * by any unauthorised person is illegal unless that                          *  
  * person has a software license agreement with ACcESS.                       *  
  *                                                                            *  
  ******************************************************************************  
3    
4  ******************************************************************************/  /*******************************************************
5     *
6  #include "escript/Data/Data.h"   *           Copyright 2003-2007 by ACceSS MNRF
7     *       Copyright 2007 by University of Queensland
8     *
9     *                http://esscc.uq.edu.au
10     *        Primary Business: Queensland, Australia
11     *  Licensed under the Open Software License version 3.0
12     *     http://www.opensource.org/licenses/osl-3.0.php
13     *
14     *******************************************************/
15    
16    #include "Data.h"
17    
18    #include "DataExpanded.h"
19    #include "DataConstant.h"
20    #include "DataTagged.h"
21    #include "DataEmpty.h"
22    #include "DataArrayView.h"
23    #include "FunctionSpaceFactory.h"
24    #include "AbstractContinuousDomain.h"
25    #include "UnaryFuncs.h"
26    extern "C" {
27    #include "escript/blocktimer.h"
28    }
29    
 #include <iostream>  
30  #include <fstream>  #include <fstream>
31  #include <algorithm>  #include <algorithm>
32  #include <vector>  #include <vector>
 #include <exception>  
33  #include <functional>  #include <functional>
 #include <math.h>  
34    
35  #include <boost/python/str.hpp>  #include <boost/python/dict.hpp>
36  #include <boost/python/extract.hpp>  #include <boost/python/extract.hpp>
37  #include <boost/python/long.hpp>  #include <boost/python/long.hpp>
38    
 #include "escript/Data/DataException.h"  
 #include "escript/Data/DataExpanded.h"  
 #include "escript/Data/DataConstant.h"  
 #include "escript/Data/DataTagged.h"  
 #include "escript/Data/DataEmpty.h"  
 #include "escript/Data/DataArray.h"  
 #include "escript/Data/FunctionSpaceFactory.h"  
 #include "escript/Data/AbstractContinuousDomain.h"  
 #include "escript/Data/UnaryFuncs.h"  
   
39  using namespace std;  using namespace std;
40  using namespace boost::python;  using namespace boost::python;
41  using namespace boost;  using namespace boost;
# Line 51  Data::Data() Line 48  Data::Data()
48    DataAbstract* temp=new DataEmpty();    DataAbstract* temp=new DataEmpty();
49    shared_ptr<DataAbstract> temp_data(temp);    shared_ptr<DataAbstract> temp_data(temp);
50    m_data=temp_data;    m_data=temp_data;
51      m_protected=false;
52  }  }
53    
54  Data::Data(double value,  Data::Data(double value,
# Line 62  Data::Data(double value, Line 60  Data::Data(double value,
60    for (int i = 0; i < shape.attr("__len__")(); ++i) {    for (int i = 0; i < shape.attr("__len__")(); ++i) {
61      dataPointShape.push_back(extract<const int>(shape[i]));      dataPointShape.push_back(extract<const int>(shape[i]));
62    }    }
63    DataArray temp(dataPointShape,value);  
64    initialise(temp.getView(),what,expanded);    int len = DataArrayView::noValues(dataPointShape);
65      DataVector temp_data(len,value,len);
66      DataArrayView temp_dataView(temp_data, dataPointShape);
67    
68      initialise(temp_dataView, what, expanded);
69    
70      m_protected=false;
71  }  }
72    
73  Data::Data(double value,  Data::Data(double value,
# Line 71  Data::Data(double value, Line 75  Data::Data(double value,
75         const FunctionSpace& what,         const FunctionSpace& what,
76             bool expanded)             bool expanded)
77  {  {
78    DataArray temp(dataPointShape,value);    int len = DataArrayView::noValues(dataPointShape);
79    pair<int,int> dataShape=what.getDataShape();  
80    initialise(temp.getView(),what,expanded);    DataVector temp_data(len,value,len);
81      DataArrayView temp_dataView(temp_data, dataPointShape);
82    
83      initialise(temp_dataView, what, expanded);
84    
85      m_protected=false;
86  }  }
87    
88  Data::Data(const Data& inData)  Data::Data(const Data& inData)
89  {  {
90    m_data=inData.m_data;    m_data=inData.m_data;
91      m_protected=inData.isProtected();
92  }  }
93    
94  Data::Data(const Data& inData,  Data::Data(const Data& inData,
# Line 89  Data::Data(const Data& inData, Line 99  Data::Data(const Data& inData,
99    DataAbstract* tmp = inData.m_data->getSlice(region);    DataAbstract* tmp = inData.m_data->getSlice(region);
100    shared_ptr<DataAbstract> temp_data(tmp);    shared_ptr<DataAbstract> temp_data(tmp);
101    m_data=temp_data;    m_data=temp_data;
102      m_protected=false;
103  }  }
104    
105  Data::Data(const Data& inData,  Data::Data(const Data& inData,
# Line 98  Data::Data(const Data& inData, Line 109  Data::Data(const Data& inData,
109      m_data=inData.m_data;      m_data=inData.m_data;
110    } else {    } else {
111      Data tmp(0,inData.getPointDataView().getShape(),functionspace,true);      Data tmp(0,inData.getPointDataView().getShape(),functionspace,true);
112      // Note for Lutz, Must use a reference or pointer to a derived object      // Note: Must use a reference or pointer to a derived object
113      // in order to get polymorphic behaviour. Shouldn't really      // in order to get polymorphic behaviour. Shouldn't really
114      // be able to create an instance of AbstractDomain but that was done      // be able to create an instance of AbstractDomain but that was done
115      // as a boost python work around which may no longer be required.      // as a boost:python work around which may no longer be required.
116      const AbstractDomain& inDataDomain=inData.getDomain();      const AbstractDomain& inDataDomain=inData.getDomain();
117      if  (inDataDomain==functionspace.getDomain()) {      if  (inDataDomain==functionspace.getDomain()) {
118        inDataDomain.interpolateOnDomain(tmp,inData);        inDataDomain.interpolateOnDomain(tmp,inData);
# Line 110  Data::Data(const Data& inData, Line 121  Data::Data(const Data& inData,
121      }      }
122      m_data=tmp.m_data;      m_data=tmp.m_data;
123    }    }
124      m_protected=false;
125  }  }
126    
127  Data::Data(const DataTagged::TagListType& tagKeys,  Data::Data(const DataTagged::TagListType& tagKeys,
# Line 121  Data::Data(const DataTagged::TagListType Line 133  Data::Data(const DataTagged::TagListType
133    DataAbstract* temp=new DataTagged(tagKeys,values,defaultValue,what);    DataAbstract* temp=new DataTagged(tagKeys,values,defaultValue,what);
134    shared_ptr<DataAbstract> temp_data(temp);    shared_ptr<DataAbstract> temp_data(temp);
135    m_data=temp_data;    m_data=temp_data;
136      m_protected=false;
137    if (expanded) {    if (expanded) {
138      expand();      expand();
139    }    }
# Line 131  Data::Data(const numeric::array& value, Line 144  Data::Data(const numeric::array& value,
144             bool expanded)             bool expanded)
145  {  {
146    initialise(value,what,expanded);    initialise(value,what,expanded);
147      m_protected=false;
148  }  }
149    
150  Data::Data(const DataArrayView& value,  Data::Data(const DataArrayView& value,
# Line 138  Data::Data(const DataArrayView& value, Line 152  Data::Data(const DataArrayView& value,
152             bool expanded)             bool expanded)
153  {  {
154    initialise(value,what,expanded);    initialise(value,what,expanded);
155      m_protected=false;
156  }  }
157    
158  Data::Data(const object& value,  Data::Data(const object& value,
# Line 146  Data::Data(const object& value, Line 161  Data::Data(const object& value,
161  {  {
162    numeric::array asNumArray(value);    numeric::array asNumArray(value);
163    initialise(asNumArray,what,expanded);    initialise(asNumArray,what,expanded);
164      m_protected=false;
165  }  }
166    
167    
168  Data::Data(const object& value,  Data::Data(const object& value,
169             const Data& other)             const Data& other)
170  {  {
171    
172      numeric::array asNumArray(value);
173    
174    
175      // extract the shape of the numarray
176      DataArrayView::ShapeType tempShape;
177      for (int i=0; i < asNumArray.getrank(); i++) {
178        tempShape.push_back(extract<int>(asNumArray.getshape()[i]));
179      }
180      // get the space for the data vector
181      int len = DataArrayView::noValues(tempShape);
182      DataVector temp_data(len, 0.0, len);
183      DataArrayView temp_dataView(temp_data, tempShape);
184      temp_dataView.copy(asNumArray);
185    
186    //    //
187    // Create DataConstant using the given value and all other parameters    // Create DataConstant using the given value and all other parameters
188    // copied from other. If value is a rank 0 object this Data    // copied from other. If value is a rank 0 object this Data
189    // will assume the point data shape of other.    // will assume the point data shape of other.
190    DataArray temp(value);  
191    if (temp.getView().getRank()==0) {    if (temp_dataView.getRank()==0) {
192      //      int len = DataArrayView::noValues(other.getPointDataView().getShape());
193      // Create a DataArray with the scalar value for all elements  
194      DataArray temp2(other.getPointDataView().getShape(),temp.getView()());      DataVector temp2_data(len, temp_dataView(), len);
195      initialise(temp2.getView(),other.getFunctionSpace(),false);      DataArrayView temp2_dataView(temp2_data, other.getPointDataView().getShape());
196        initialise(temp2_dataView, other.getFunctionSpace(), false);
197    
198    } else {    } else {
199      //      //
200      // Create a DataConstant with the same sample shape as other      // Create a DataConstant with the same sample shape as other
201      initialise(temp.getView(),other.getFunctionSpace(),false);      initialise(temp_dataView, other.getFunctionSpace(), false);
202    }    }
203      m_protected=false;
204    }
205    
206    Data::~Data()
207    {
208    
209  }  }
210    
211  escriptDataC  escriptDataC
# Line 203  Data::getShapeTuple() const Line 243  Data::getShapeTuple() const
243          throw DataException("Error - illegal Data rank.");          throw DataException("Error - illegal Data rank.");
244    }    }
245  }  }
   
246  void  void
247  Data::copy(const Data& other)  Data::copy(const Data& other)
248  {  {
# Line 256  Data::copy(const Data& other) Line 295  Data::copy(const Data& other)
295    throw DataException("Error - Copy not implemented for this Data type.");    throw DataException("Error - Copy not implemented for this Data type.");
296  }  }
297    
298    
299    void
300    Data::setToZero()
301    {
302      {
303        DataExpanded* temp=dynamic_cast<DataExpanded*>(m_data.get());
304        if (temp!=0) {
305           temp->setToZero();
306           return;
307        }
308      }
309      {
310        DataTagged* temp=dynamic_cast<DataTagged*>(m_data.get());
311        if (temp!=0) {
312          temp->setToZero();
313          return;
314        }
315      }
316      {
317        DataConstant* temp=dynamic_cast<DataConstant*>(m_data.get());
318        if (temp!=0) {
319          temp->setToZero();
320          return;
321        }
322      }
323      throw DataException("Error - Data can not be set to zero.");
324    }
325    
326  void  void
327  Data::copyWithMask(const Data& other,  Data::copyWithMask(const Data& other,
328                     const Data& mask)                     const Data& mask)
# Line 302  Data::isConstant() const Line 369  Data::isConstant() const
369  }  }
370    
371  void  void
372    Data::setProtection()
373    {
374       m_protected=true;
375    }
376    
377    bool
378    Data::isProtected() const
379    {
380       return m_protected;
381    }
382    
383    
384    
385    void
386  Data::expand()  Data::expand()
387  {  {
388    if (isConstant()) {    if (isConstant()) {
# Line 343  Data::tag() Line 424  Data::tag()
424    }    }
425  }  }
426    
427  void  Data
428  Data::reshapeDataPoint(const DataArrayView::ShapeType& shape)  Data::oneOver() const
429  {  {
430    m_data->reshapeDataPoint(shape);    return C_TensorUnaryOperation(*this, bind1st(divides<double>(),1.));
431  }  }
432    
433  Data  Data
434  Data::wherePositive() const  Data::wherePositive() const
435  {  {
436    return escript::unaryOp(*this,bind2nd(greater<double>(),0.0));    return C_TensorUnaryOperation(*this, bind2nd(greater<double>(),0.0));
437  }  }
438    
439  Data  Data
440  Data::whereNegative() const  Data::whereNegative() const
441  {  {
442    return escript::unaryOp(*this,bind2nd(less<double>(),0.0));    return C_TensorUnaryOperation(*this, bind2nd(less<double>(),0.0));
443  }  }
444    
445  Data  Data
446  Data::whereNonNegative() const  Data::whereNonNegative() const
447  {  {
448    return escript::unaryOp(*this,bind2nd(greater_equal<double>(),0.0));    return C_TensorUnaryOperation(*this, bind2nd(greater_equal<double>(),0.0));
449  }  }
450    
451  Data  Data
452  Data::whereNonPositive() const  Data::whereNonPositive() const
453  {  {
454    return escript::unaryOp(*this,bind2nd(less_equal<double>(),0.0));    return C_TensorUnaryOperation(*this, bind2nd(less_equal<double>(),0.0));
455  }  }
456    
457  Data  Data
458  Data::whereZero() const  Data::whereZero(double tol) const
459  {  {
460    return escript::unaryOp(*this,bind2nd(equal_to<double>(),0.0));    Data dataAbs=abs();
461      return C_TensorUnaryOperation(dataAbs, bind2nd(less_equal<double>(),tol));
462  }  }
463    
464  Data  Data
465  Data::whereNonZero() const  Data::whereNonZero(double tol) const
466  {  {
467    return escript::unaryOp(*this,bind2nd(not_equal_to<double>(),0.0));    Data dataAbs=abs();
468      return C_TensorUnaryOperation(dataAbs, bind2nd(greater<double>(),tol));
469  }  }
470    
471  Data  Data
# Line 409  Data::probeInterpolation(const FunctionS Line 492  Data::probeInterpolation(const FunctionS
492  Data  Data
493  Data::gradOn(const FunctionSpace& functionspace) const  Data::gradOn(const FunctionSpace& functionspace) const
494  {  {
495      double blocktimer_start = blocktimer_time();
496    if (functionspace.getDomain()!=getDomain())    if (functionspace.getDomain()!=getDomain())
497      throw DataException("Error - gradient cannot be calculated on different domains.");      throw DataException("Error - gradient cannot be calculated on different domains.");
498    DataArrayView::ShapeType grad_shape=getPointDataView().getShape();    DataArrayView::ShapeType grad_shape=getPointDataView().getShape();
499    grad_shape.push_back(functionspace.getDim());    grad_shape.push_back(functionspace.getDim());
500    Data out(0.0,grad_shape,functionspace,true);    Data out(0.0,grad_shape,functionspace,true);
501    getDomain().setToGradient(out,*this);    getDomain().setToGradient(out,*this);
502      blocktimer_increment("grad()", blocktimer_start);
503    return out;    return out;
504  }  }
505    
# Line 442  Data::getDataPointShape() const Line 527  Data::getDataPointShape() const
527    return getPointDataView().getShape();    return getPointDataView().getShape();
528  }  }
529    
530    
531    
532  const  const
533  boost::python::numeric::array  boost::python::numeric::array
534  Data::convertToNumArray()  Data:: getValueOfDataPoint(int dataPointNo)
535  {  {
536    //    size_t length=0;
537    // determine the total number of data points    int i, j, k, l;
   int numSamples = getNumSamples();  
   int numDataPointsPerSample = getNumDataPointsPerSample();  
   int numDataPoints = numSamples * numDataPointsPerSample;  
   
538    //    //
539    // determine the rank and shape of each data point    // determine the rank and shape of each data point
540    int dataPointRank = getDataPointRank();    int dataPointRank = getDataPointRank();
# Line 462  Data::convertToNumArray() Line 545  Data::convertToNumArray()
545    boost::python::numeric::array numArray(0.0);    boost::python::numeric::array numArray(0.0);
546    
547    //    //
548    // the rank of the returned numeric array will be the rank of    // the shape of the returned numeric array will be the same
549    // the data points, plus one. Where the rank of the array is n,    // as that of the data point
550    // the last n-1 dimensions will be equal to the shape of the    int arrayRank = dataPointRank;
551    // data points, whilst the first dimension will be equal to the    DataArrayView::ShapeType arrayShape = dataPointShape;
   // total number of data points. Thus the array will consist of  
   // a serial vector of the data points.  
   int arrayRank = dataPointRank + 1;  
   DataArrayView::ShapeType arrayShape;  
   arrayShape.push_back(numDataPoints);  
   for (int d=0; d<dataPointRank; d++) {  
      arrayShape.push_back(dataPointShape[d]);  
   }  
552    
553    //    //
554    // resize the numeric array to the shape just calculated    // resize the numeric array to the shape just calculated
555      if (arrayRank==0) {
556        numArray.resize(1);
557      }
558    if (arrayRank==1) {    if (arrayRank==1) {
559      numArray.resize(arrayShape[0]);      numArray.resize(arrayShape[0]);
560    }    }
# Line 489  Data::convertToNumArray() Line 567  Data::convertToNumArray()
567    if (arrayRank==4) {    if (arrayRank==4) {
568      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);
569    }    }
   if (arrayRank==5) {  
     numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3],arrayShape[4]);  
   }  
570    
571    //    if (getNumDataPointsPerSample()>0) {
572    // loop through each data point in turn, loading the values for that data point         int sampleNo = dataPointNo/getNumDataPointsPerSample();
573    // into the numeric array.         int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
574    int dataPoint = 0;         //
575    for (int sampleNo = 0; sampleNo < numSamples; sampleNo++) {         // Check a valid sample number has been supplied
576      for (int dataPointNo = 0; dataPointNo < numDataPointsPerSample; dataPointNo++) {         if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {
577        DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNo);             throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");
578        if (dataPointRank==0) {         }
579          numArray[dataPoint]=dataPointView();  
580        }         //
581        if (dataPointRank==1) {         // Check a valid data point number has been supplied
582          for (int i=0; i<dataPointShape[0]; i++) {         if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {
583            numArray[dataPoint][i]=dataPointView(i);             throw DataException("Error - Data::convertToNumArray: invalid dataPointNoInSample.");
584          }         }
585        }         // TODO: global error handling
586        if (dataPointRank==2) {         // create a view of the data if it is stored locally
587          for (int i=0; i<dataPointShape[0]; i++) {         DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNoInSample);
588            for (int j=0; j<dataPointShape[1]; j++) {  
589              numArray[dataPoint][i][j] = dataPointView(i,j);         switch( dataPointRank ){
590            }              case 0 :
591          }                  numArray[0] = dataPointView();
592        }                  break;
593        if (dataPointRank==3) {              case 1 :
594          for (int i=0; i<dataPointShape[0]; i++) {                  for( i=0; i<dataPointShape[0]; i++ )
595            for (int j=0; j<dataPointShape[1]; j++) {                      numArray[i]=dataPointView(i);
596              for (int k=0; k<dataPointShape[2]; k++) {                  break;
597                numArray[dataPoint][i][j][k]=dataPointView(i,j,k);              case 2 :
598              }                  for( i=0; i<dataPointShape[0]; i++ )
599            }                      for( j=0; j<dataPointShape[1]; j++)
600          }                          numArray[make_tuple(i,j)]=dataPointView(i,j);
601        }                  break;
602        if (dataPointRank==4) {              case 3 :
603          for (int i=0; i<dataPointShape[0]; i++) {                  for( i=0; i<dataPointShape[0]; i++ )
604            for (int j=0; j<dataPointShape[1]; j++) {                      for( j=0; j<dataPointShape[1]; j++ )
605              for (int k=0; k<dataPointShape[2]; k++) {                          for( k=0; k<dataPointShape[2]; k++)
606                for (int l=0; l<dataPointShape[3]; l++) {                              numArray[make_tuple(i,j,k)]=dataPointView(i,j,k);
607                  numArray[dataPoint][i][j][k][l]=dataPointView(i,j,k,l);                  break;
608                }              case 4 :
609              }                  for( i=0; i<dataPointShape[0]; i++ )
610            }                      for( j=0; j<dataPointShape[1]; j++ )
611          }                          for( k=0; k<dataPointShape[2]; k++ )
612        }                              for( l=0; l<dataPointShape[3]; l++)
613        dataPoint++;                                  numArray[make_tuple(i,j,k,l)]=dataPointView(i,j,k,l);
614      }                  break;
615        }
616    }    }
   
617    //    //
618    // return the loaded array    // return the array
619    return numArray;    return numArray;
 }  
620    
621  const  }
622  boost::python::numeric::array  void
623  Data::convertToNumArrayFromSampleNo(int sampleNo)  Data::setValueOfDataPointToPyObject(int dataPointNo, const boost::python::object& py_object)
624  {  {
625    //      // this will throw if the value cannot be represented
626    // Check a valid sample number has been supplied      boost::python::numeric::array num_array(py_object);
627    if (sampleNo >= getNumSamples()) {      setValueOfDataPointToArray(dataPointNo,num_array);
     throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");  
   }  
628    
   //  
   // determine the number of data points per sample  
   int numDataPointsPerSample = getNumDataPointsPerSample();  
629    
630    //  }
   // determine the rank and shape of each data point  
   int dataPointRank = getDataPointRank();  
   DataArrayView::ShapeType dataPointShape = getDataPointShape();  
631    
632    void
633    Data::setValueOfDataPointToArray(int dataPointNo, const boost::python::numeric::array& num_array)
634    {
635      if (isProtected()) {
636            throw DataException("Error - attempt to update protected Data object.");
637      }
638    //    //
639    // create the numeric array to be returned    // check rank
640    boost::python::numeric::array numArray(0.0);    if (num_array.getrank()<getDataPointRank())
641          throw DataException("Rank of numarray does not match Data object rank");
642    
643    //    //
644    // the rank of the returned numeric array will be the rank of    // check shape of num_array
645    // the data points, plus one. Where the rank of the array is n,    for (int i=0; i<getDataPointRank(); i++) {
646    // the last n-1 dimensions will be equal to the shape of the      if (extract<int>(num_array.getshape()[i])!=getDataPointShape()[i])
647    // data points, whilst the first dimension will be equal to the         throw DataException("Shape of numarray does not match Data object rank");
   // total number of data points. Thus the array will consist of  
   // a serial vector of the data points.  
   int arrayRank = dataPointRank + 1;  
   DataArrayView::ShapeType arrayShape;  
   arrayShape.push_back(numDataPointsPerSample);  
   for (int d=0; d<dataPointRank; d++) {  
      arrayShape.push_back(dataPointShape[d]);  
648    }    }
   
649    //    //
650    // resize the numeric array to the shape just calculated    // make sure data is expanded:
651    if (arrayRank==1) {    if (!isExpanded()) {
652      numArray.resize(arrayShape[0]);      expand();
   }  
   if (arrayRank==2) {  
     numArray.resize(arrayShape[0],arrayShape[1]);  
   }  
   if (arrayRank==3) {  
     numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2]);  
   }  
   if (arrayRank==4) {  
     numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);  
653    }    }
654    if (arrayRank==5) {    if (getNumDataPointsPerSample()>0) {
655      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3],arrayShape[4]);         int sampleNo = dataPointNo/getNumDataPointsPerSample();
656           int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
657           m_data->copyToDataPoint(sampleNo, dataPointNoInSample,num_array);
658      } else {
659           m_data->copyToDataPoint(-1, 0,num_array);
660    }    }
661    }
662    
663    //  void
664    // loop through each data point in turn, loading the values for that data point  Data::setValueOfDataPoint(int dataPointNo, const double value)
665    // into the numeric array.  {
666    for (int dataPoint = 0; dataPoint < numDataPointsPerSample; dataPoint++) {    if (isProtected()) {
667      DataArrayView dataPointView = getDataPoint(sampleNo, dataPoint);          throw DataException("Error - attempt to update protected Data object.");
     if (dataPointRank==0) {  
       numArray[dataPoint]=dataPointView();  
     }  
     if (dataPointRank==1) {  
       for (int i=0; i<dataPointShape[0]; i++) {  
         numArray[dataPoint][i]=dataPointView(i);  
       }  
     }  
     if (dataPointRank==2) {  
       for (int i=0; i<dataPointShape[0]; i++) {  
         for (int j=0; j<dataPointShape[1]; j++) {  
           numArray[dataPoint][i][j] = dataPointView(i,j);  
         }  
       }  
     }  
     if (dataPointRank==3) {  
       for (int i=0; i<dataPointShape[0]; i++) {  
         for (int j=0; j<dataPointShape[1]; j++) {  
           for (int k=0; k<dataPointShape[2]; k++) {  
             numArray[dataPoint][i][j][k]=dataPointView(i,j,k);  
           }  
         }  
       }  
     }  
     if (dataPointRank==4) {  
       for (int i=0; i<dataPointShape[0]; i++) {  
         for (int j=0; j<dataPointShape[1]; j++) {  
           for (int k=0; k<dataPointShape[2]; k++) {  
             for (int l=0; l<dataPointShape[3]; l++) {  
               numArray[dataPoint][i][j][k][l]=dataPointView(i,j,k,l);  
             }  
           }  
         }  
       }  
     }  
668    }    }
   
669    //    //
670    // return the loaded array    // make sure data is expanded:
671    return numArray;    if (!isExpanded()) {
672        expand();
673      }
674      if (getNumDataPointsPerSample()>0) {
675           int sampleNo = dataPointNo/getNumDataPointsPerSample();
676           int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
677           m_data->copyToDataPoint(sampleNo, dataPointNoInSample,value);
678      } else {
679           m_data->copyToDataPoint(-1, 0,value);
680      }
681  }  }
682    
683  const  const
684  boost::python::numeric::array  boost::python::numeric::array
685  Data::convertToNumArrayFromDPNo(int sampleNo,  Data::getValueOfGlobalDataPoint(int procNo, int dataPointNo)
                                 int dataPointNo)  
686  {  {
687    //    size_t length=0;
688    // Check a valid sample number has been supplied    int i, j, k, l, pos;
   if (sampleNo >= getNumSamples()) {  
     throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");  
   }  
   
   //  
   // Check a valid data point number has been supplied  
   if (dataPointNo >= getNumDataPointsPerSample()) {  
     throw DataException("Error - Data::convertToNumArray: invalid dataPointNo.");  
   }  
   
689    //    //
690    // determine the rank and shape of each data point    // determine the rank and shape of each data point
691    int dataPointRank = getDataPointRank();    int dataPointRank = getDataPointRank();
# Line 696  Data::convertToNumArrayFromDPNo(int samp Line 719  Data::convertToNumArrayFromDPNo(int samp
719      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);
720    }    }
721    
722      // added for the MPI communication
723      length=1;
724      for( i=0; i<arrayRank; i++ ) length *= arrayShape[i];
725      double *tmpData = new double[length];
726    
727    //    //
728    // load the values for the data point into the numeric array.    // load the values for the data point into the numeric array.
   DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNo);  
   if (dataPointRank==0) {  
     numArray[0]=dataPointView();  
   }  
   if (dataPointRank==1) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       numArray[i]=dataPointView(i);  
     }  
   }  
   if (dataPointRank==2) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       for (int j=0; j<dataPointShape[1]; j++) {  
         numArray[i][j] = dataPointView(i,j);  
       }  
     }  
   }  
   if (dataPointRank==3) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       for (int j=0; j<dataPointShape[1]; j++) {  
         for (int k=0; k<dataPointShape[2]; k++) {  
           numArray[i][j][k]=dataPointView(i,j,k);  
         }  
       }  
     }  
   }  
   if (dataPointRank==4) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       for (int j=0; j<dataPointShape[1]; j++) {  
         for (int k=0; k<dataPointShape[2]; k++) {  
           for (int l=0; l<dataPointShape[3]; l++) {  
             numArray[i][j][k][l]=dataPointView(i,j,k,l);  
           }  
         }  
       }  
     }  
   }  
729    
730        // updated for the MPI case
731        if( get_MPIRank()==procNo ){
732                 if (getNumDataPointsPerSample()>0) {
733                    int sampleNo = dataPointNo/getNumDataPointsPerSample();
734                    int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
735                    //
736                    // Check a valid sample number has been supplied
737                    if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {
738                      throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");
739                    }
740    
741                    //
742                    // Check a valid data point number has been supplied
743                    if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {
744                      throw DataException("Error - Data::convertToNumArray: invalid dataPointNoInSample.");
745                    }
746                    // TODO: global error handling
747            // create a view of the data if it is stored locally
748            DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNoInSample);
749    
750            // pack the data from the view into tmpData for MPI communication
751            pos=0;
752            switch( dataPointRank ){
753                case 0 :
754                    tmpData[0] = dataPointView();
755                    break;
756                case 1 :
757                    for( i=0; i<dataPointShape[0]; i++ )
758                        tmpData[i]=dataPointView(i);
759                    break;
760                case 2 :
761                    for( i=0; i<dataPointShape[0]; i++ )
762                        for( j=0; j<dataPointShape[1]; j++, pos++ )
763                            tmpData[pos]=dataPointView(i,j);
764                    break;
765                case 3 :
766                    for( i=0; i<dataPointShape[0]; i++ )
767                        for( j=0; j<dataPointShape[1]; j++ )
768                            for( k=0; k<dataPointShape[2]; k++, pos++ )
769                                tmpData[pos]=dataPointView(i,j,k);
770                    break;
771                case 4 :
772                    for( i=0; i<dataPointShape[0]; i++ )
773                        for( j=0; j<dataPointShape[1]; j++ )
774                            for( k=0; k<dataPointShape[2]; k++ )
775                                for( l=0; l<dataPointShape[3]; l++, pos++ )
776                                    tmpData[pos]=dataPointView(i,j,k,l);
777                    break;
778            }
779                }
780        }
781            #ifdef PASO_MPI
782            // broadcast the data to all other processes
783        MPI_Bcast( tmpData, length, MPI_DOUBLE, procNo, get_MPIComm() );
784            #endif
785    
786        // unpack the data
787        switch( dataPointRank ){
788            case 0 :
789                numArray[0]=tmpData[0];
790                break;
791            case 1 :
792                for( i=0; i<dataPointShape[0]; i++ )
793                    numArray[i]=tmpData[i];
794                break;
795            case 2 :
796                for( i=0; i<dataPointShape[0]; i++ )
797                    for( j=0; j<dataPointShape[1]; j++ )
798                       numArray[make_tuple(i,j)]=tmpData[i+j*dataPointShape[0]];
799                break;
800            case 3 :
801                for( i=0; i<dataPointShape[0]; i++ )
802                    for( j=0; j<dataPointShape[1]; j++ )
803                        for( k=0; k<dataPointShape[2]; k++ )
804                            numArray[make_tuple(i,j,k)]=tmpData[i+dataPointShape[0]*(j*+k*dataPointShape[1])];
805                break;
806            case 4 :
807                for( i=0; i<dataPointShape[0]; i++ )
808                    for( j=0; j<dataPointShape[1]; j++ )
809                        for( k=0; k<dataPointShape[2]; k++ )
810                            for( l=0; l<dataPointShape[3]; l++ )
811                                    numArray[make_tuple(i,j,k,l)]=tmpData[i+dataPointShape[0]*(j*+dataPointShape[1]*(k+l*dataPointShape[2]))];
812                break;
813        }
814    
815        delete [] tmpData;
816    //    //
817    // return the loaded array    // return the loaded array
818    return numArray;    return numArray;
819  }  }
820    
821    
822    
823  boost::python::numeric::array  boost::python::numeric::array
824  Data::integrate() const  Data::integrate() const
825  {  {
826    int index;    int index;
827    int rank = getDataPointRank();    int rank = getDataPointRank();
828    DataArrayView::ShapeType shape = getDataPointShape();    DataArrayView::ShapeType shape = getDataPointShape();
829      int dataPointSize = getDataPointSize();
830    
831    //    //
832    // calculate the integral values    // calculate the integral values
833    vector<double> integrals(getDataPointSize());    vector<double> integrals(dataPointSize);
834      vector<double> integrals_local(dataPointSize);
835    #ifdef PASO_MPI
836      AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals_local,*this);
837      // Global sum: use an array instead of a vector because elements of array are guaranteed to be contiguous in memory
838      double *tmp = new double[dataPointSize];
839      double *tmp_local = new double[dataPointSize];
840      for (int i=0; i<dataPointSize; i++) { tmp_local[i] = integrals_local[i]; }
841      MPI_Allreduce( &tmp_local[0], &tmp[0], dataPointSize, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
842      for (int i=0; i<dataPointSize; i++) { integrals[i] = tmp[i]; }
843      delete[] tmp;
844      delete[] tmp_local;
845    #else
846    AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals,*this);    AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals,*this);
847    #endif
848    
849    //    //
850    // create the numeric array to be returned    // create the numeric array to be returned
# Line 769  Data::integrate() const Line 863  Data::integrate() const
863      }      }
864    }    }
865    if (rank==2) {    if (rank==2) {
866      bp_array.resize(shape[0],shape[1]);         bp_array.resize(shape[0],shape[1]);
867      for (int i=0; i<shape[0]; i++) {         for (int i=0; i<shape[0]; i++) {
868        for (int j=0; j<shape[1]; j++) {           for (int j=0; j<shape[1]; j++) {
869          index = i + shape[0] * j;             index = i + shape[0] * j;
870          bp_array[i,j] = integrals[index];             bp_array[make_tuple(i,j)] = integrals[index];
871        }           }
872      }         }
873    }    }
874    if (rank==3) {    if (rank==3) {
875      bp_array.resize(shape[0],shape[1],shape[2]);      bp_array.resize(shape[0],shape[1],shape[2]);
# Line 783  Data::integrate() const Line 877  Data::integrate() const
877        for (int j=0; j<shape[1]; j++) {        for (int j=0; j<shape[1]; j++) {
878          for (int k=0; k<shape[2]; k++) {          for (int k=0; k<shape[2]; k++) {
879            index = i + shape[0] * ( j + shape[1] * k );            index = i + shape[0] * ( j + shape[1] * k );
880            bp_array[i,j,k] = integrals[index];            bp_array[make_tuple(i,j,k)] = integrals[index];
881          }          }
882        }        }
883      }      }
# Line 795  Data::integrate() const Line 889  Data::integrate() const
889          for (int k=0; k<shape[2]; k++) {          for (int k=0; k<shape[2]; k++) {
890            for (int l=0; l<shape[3]; l++) {            for (int l=0; l<shape[3]; l++) {
891              index = i + shape[0] * ( j + shape[1] * ( k + shape[2] * l ) );              index = i + shape[0] * ( j + shape[1] * ( k + shape[2] * l ) );
892              bp_array[i,j,k,l] = integrals[index];              bp_array[make_tuple(i,j,k,l)] = integrals[index];
893            }            }
894          }          }
895        }        }
# Line 810  Data::integrate() const Line 904  Data::integrate() const
904  Data  Data
905  Data::sin() const  Data::sin() const
906  {  {
907    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sin);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sin);
908  }  }
909    
910  Data  Data
911  Data::cos() const  Data::cos() const
912  {  {
913    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::cos);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::cos);
914  }  }
915    
916  Data  Data
917  Data::tan() const  Data::tan() const
918  {  {
919    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::tan);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::tan);
920  }  }
921    
922  Data  Data
923  Data::log() const  Data::asin() const
924  {  {
925    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log10);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::asin);
926  }  }
927    
928  Data  Data
929  Data::ln() const  Data::acos() const
930    {
931      return C_TensorUnaryOperation<double (*)(double)>(*this, ::acos);
932    }
933    
934    
935    Data
936    Data::atan() const
937  {  {
938    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::atan);
939    }
940    
941    Data
942    Data::sinh() const
943    {
944        return C_TensorUnaryOperation<double (*)(double)>(*this, ::sinh);
945    
946    }
947    
948    Data
949    Data::cosh() const
950    {
951        return C_TensorUnaryOperation<double (*)(double)>(*this, ::cosh);
952    }
953    
954    Data
955    Data::tanh() const
956    {
957        return C_TensorUnaryOperation<double (*)(double)>(*this, ::tanh);
958    }
959    
960    
961    Data
962    Data::erf() const
963    {
964    #ifdef _WIN32
965      throw DataException("Error - Data:: erf function is not supported on _WIN32 platforms.");
966    #else
967      return C_TensorUnaryOperation(*this, ::erf);
968    #endif
969    }
970    
971    Data
972    Data::asinh() const
973    {
974    #ifdef _WIN32
975      return C_TensorUnaryOperation(*this, escript::asinh_substitute);
976    #else
977      return C_TensorUnaryOperation(*this, ::asinh);
978    #endif
979    }
980    
981    Data
982    Data::acosh() const
983    {
984    #ifdef _WIN32
985      return C_TensorUnaryOperation(*this, escript::acosh_substitute);
986    #else
987      return C_TensorUnaryOperation(*this, ::acosh);
988    #endif
989    }
990    
991    Data
992    Data::atanh() const
993    {
994    #ifdef _WIN32
995      return C_TensorUnaryOperation(*this, escript::atanh_substitute);
996    #else
997      return C_TensorUnaryOperation(*this, ::atanh);
998    #endif
999    }
1000    
1001    Data
1002    Data::log10() const
1003    {
1004      return C_TensorUnaryOperation<double (*)(double)>(*this, ::log10);
1005    }
1006    
1007    Data
1008    Data::log() const
1009    {
1010      return C_TensorUnaryOperation<double (*)(double)>(*this, ::log);
1011  }  }
1012    
1013  Data  Data
1014  Data::sign() const  Data::sign() const
1015  {  {
1016    return escript::unaryOp(*this,escript::fsign);    return C_TensorUnaryOperation(*this, escript::fsign);
1017  }  }
1018    
1019  Data  Data
1020  Data::abs() const  Data::abs() const
1021  {  {
1022    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::fabs);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::fabs);
1023  }  }
1024    
1025  Data  Data
1026  Data::neg() const  Data::neg() const
1027  {  {
1028    return escript::unaryOp(*this,negate<double>());    return C_TensorUnaryOperation(*this, negate<double>());
1029  }  }
1030    
1031  Data  Data
1032  Data::pos() const  Data::pos() const
1033  {  {
1034    return (*this);    Data result;
1035      // perform a deep copy
1036      result.copy(*this);
1037      return result;
1038  }  }
1039    
1040  Data  Data
1041  Data::exp() const  Data::exp() const
1042  {  {
1043    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::exp);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::exp);
1044  }  }
1045    
1046  Data  Data
1047  Data::sqrt() const  Data::sqrt() const
1048  {  {
1049    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sqrt);    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sqrt);
1050  }  }
1051    
1052  double  double
1053  Data::Lsup() const  Data::Lsup() const
1054  {  {
1055      double localValue, globalValue;
1056    //    //
1057    // set the initial absolute maximum value to zero    // set the initial absolute maximum value to zero
   return algorithm(DataAlgorithmAdapter<AbsMax>(0));  
 }  
1058    
1059  double    AbsMax abs_max_func;
1060  Data::Linf() const    localValue = algorithm(abs_max_func,0);
1061  {  #ifdef PASO_MPI
1062    //    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1063    // set the initial absolute minimum value to max double    return globalValue;
1064    return algorithm(DataAlgorithmAdapter<AbsMin>(numeric_limits<double>::max()));  #else
1065      return localValue;
1066    #endif
1067  }  }
1068    
1069  double  double
1070  Data::sup() const  Data::sup() const
1071  {  {
1072      double localValue, globalValue;
1073    //    //
1074    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1075    return algorithm(DataAlgorithmAdapter<FMax>(numeric_limits<double>::max()*-1));    FMax fmax_func;
1076      localValue = algorithm(fmax_func,numeric_limits<double>::max()*-1);
1077    #ifdef PASO_MPI
1078      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1079      return globalValue;
1080    #else
1081      return localValue;
1082    #endif
1083  }  }
1084    
1085  double  double
1086  Data::inf() const  Data::inf() const
1087  {  {
1088      double localValue, globalValue;
1089    //    //
1090    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1091    return algorithm(DataAlgorithmAdapter<FMin>(numeric_limits<double>::max()));    FMin fmin_func;
1092      localValue = algorithm(fmin_func,numeric_limits<double>::max());
1093    #ifdef PASO_MPI
1094      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD );
1095      return globalValue;
1096    #else
1097      return localValue;
1098    #endif
1099  }  }
1100    
1101    /* TODO */
1102    /* global reduction */
1103  Data  Data
1104  Data::maxval() const  Data::maxval() const
1105  {  {
1106    //    //
1107    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1108    return dp_algorithm(DataAlgorithmAdapter<FMax>(numeric_limits<double>::max()*-1));    FMax fmax_func;
1109      return dp_algorithm(fmax_func,numeric_limits<double>::max()*-1);
1110  }  }
1111    
1112  Data  Data
# Line 918  Data::minval() const Line 1114  Data::minval() const
1114  {  {
1115    //    //
1116    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1117    return dp_algorithm(DataAlgorithmAdapter<FMin>(numeric_limits<double>::max()));    FMin fmin_func;
1118      return dp_algorithm(fmin_func,numeric_limits<double>::max());
1119  }  }
1120    
1121  const boost::python::tuple  Data
1122  Data::mindp() const  Data::swapaxes(const int axis0, const int axis1) const
1123  {  {
1124    Data temp=minval();       int axis0_tmp,axis1_tmp;
1125         DataArrayView::ShapeType s=getDataPointShape();
1126    int numSamples=temp.getNumSamples();       DataArrayView::ShapeType ev_shape;
1127    int numDPPSample=temp.getNumDataPointsPerSample();       // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1128         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1129    int i,j,lowi=0,lowj=0;       int rank=getDataPointRank();
1130    double min=numeric_limits<double>::max();       if (rank<2) {
1131            throw DataException("Error - Data::swapaxes argument must have at least rank 2.");
1132    for (i=0; i<numSamples; i++) {       }
1133      for (j=0; j<numDPPSample; j++) {       if (axis0<0 || axis0>rank-1) {
1134        double next=temp.getDataPoint(i,j)();          throw DataException("Error - Data::swapaxes: axis0 must be between 0 and rank-1=" + rank-1);
1135        if (next<min) {       }
1136          min=next;       if (axis1<0 || axis1>rank-1) {
1137          lowi=i;           throw DataException("Error - Data::swapaxes: axis1 must be between 0 and rank-1=" + rank-1);
1138          lowj=j;       }
1139        }       if (axis0 == axis1) {
1140      }           throw DataException("Error - Data::swapaxes: axis indices must be different.");
1141    }       }
1142         if (axis0 > axis1) {
1143             axis0_tmp=axis1;
1144             axis1_tmp=axis0;
1145         } else {
1146             axis0_tmp=axis0;
1147             axis1_tmp=axis1;
1148         }
1149         for (int i=0; i<rank; i++) {
1150           if (i == axis0_tmp) {
1151              ev_shape.push_back(s[axis1_tmp]);
1152           } else if (i == axis1_tmp) {
1153              ev_shape.push_back(s[axis0_tmp]);
1154           } else {
1155              ev_shape.push_back(s[i]);
1156           }
1157         }
1158         Data ev(0.,ev_shape,getFunctionSpace());
1159         ev.typeMatchRight(*this);
1160         m_data->swapaxes(ev.m_data.get(), axis0_tmp, axis1_tmp);
1161         return ev;
1162    
1163    }
1164    
1165    Data
1166    Data::symmetric() const
1167    {
1168         // check input
1169         DataArrayView::ShapeType s=getDataPointShape();
1170         if (getDataPointRank()==2) {
1171            if(s[0] != s[1])
1172               throw DataException("Error - Data::symmetric can only be calculated for rank 2 object with equal first and second dimension.");
1173         }
1174         else if (getDataPointRank()==4) {
1175            if(!(s[0] == s[2] && s[1] == s[3]))
1176               throw DataException("Error - Data::symmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1177         }
1178         else {
1179            throw DataException("Error - Data::symmetric can only be calculated for rank 2 or 4 object.");
1180         }
1181         Data ev(0.,getDataPointShape(),getFunctionSpace());
1182         ev.typeMatchRight(*this);
1183         m_data->symmetric(ev.m_data.get());
1184         return ev;
1185    }
1186    
1187    Data
1188    Data::nonsymmetric() const
1189    {
1190         // check input
1191         DataArrayView::ShapeType s=getDataPointShape();
1192         if (getDataPointRank()==2) {
1193            if(s[0] != s[1])
1194               throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 object with equal first and second dimension.");
1195            DataArrayView::ShapeType ev_shape;
1196            ev_shape.push_back(s[0]);
1197            ev_shape.push_back(s[1]);
1198            Data ev(0.,ev_shape,getFunctionSpace());
1199            ev.typeMatchRight(*this);
1200            m_data->nonsymmetric(ev.m_data.get());
1201            return ev;
1202         }
1203         else if (getDataPointRank()==4) {
1204            if(!(s[0] == s[2] && s[1] == s[3]))
1205               throw DataException("Error - Data::nonsymmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1206            DataArrayView::ShapeType ev_shape;
1207            ev_shape.push_back(s[0]);
1208            ev_shape.push_back(s[1]);
1209            ev_shape.push_back(s[2]);
1210            ev_shape.push_back(s[3]);
1211            Data ev(0.,ev_shape,getFunctionSpace());
1212            ev.typeMatchRight(*this);
1213            m_data->nonsymmetric(ev.m_data.get());
1214            return ev;
1215         }
1216         else {
1217            throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 or 4 object.");
1218         }
1219    }
1220    
1221    Data
1222    Data::trace(int axis_offset) const
1223    {
1224         DataArrayView::ShapeType s=getDataPointShape();
1225         if (getDataPointRank()==2) {
1226            DataArrayView::ShapeType ev_shape;
1227            Data ev(0.,ev_shape,getFunctionSpace());
1228            ev.typeMatchRight(*this);
1229            m_data->trace(ev.m_data.get(), axis_offset);
1230            return ev;
1231         }
1232         if (getDataPointRank()==3) {
1233            DataArrayView::ShapeType ev_shape;
1234            if (axis_offset==0) {
1235              int s2=s[2];
1236              ev_shape.push_back(s2);
1237            }
1238            else if (axis_offset==1) {
1239              int s0=s[0];
1240              ev_shape.push_back(s0);
1241            }
1242            Data ev(0.,ev_shape,getFunctionSpace());
1243            ev.typeMatchRight(*this);
1244            m_data->trace(ev.m_data.get(), axis_offset);
1245            return ev;
1246         }
1247         if (getDataPointRank()==4) {
1248            DataArrayView::ShapeType ev_shape;
1249            if (axis_offset==0) {
1250              ev_shape.push_back(s[2]);
1251              ev_shape.push_back(s[3]);
1252            }
1253            else if (axis_offset==1) {
1254              ev_shape.push_back(s[0]);
1255              ev_shape.push_back(s[3]);
1256            }
1257        else if (axis_offset==2) {
1258          ev_shape.push_back(s[0]);
1259          ev_shape.push_back(s[1]);
1260        }
1261            Data ev(0.,ev_shape,getFunctionSpace());
1262            ev.typeMatchRight(*this);
1263        m_data->trace(ev.m_data.get(), axis_offset);
1264            return ev;
1265         }
1266         else {
1267            throw DataException("Error - Data::trace can only be calculated for rank 2, 3 or 4 object.");
1268         }
1269    }
1270    
1271    return make_tuple(lowi,lowj);  Data
1272    Data::transpose(int axis_offset) const
1273    {
1274         DataArrayView::ShapeType s=getDataPointShape();
1275         DataArrayView::ShapeType ev_shape;
1276         // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1277         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1278         int rank=getDataPointRank();
1279         if (axis_offset<0 || axis_offset>rank) {
1280            throw DataException("Error - Data::transpose must have 0 <= axis_offset <= rank=" + rank);
1281         }
1282         for (int i=0; i<rank; i++) {
1283           int index = (axis_offset+i)%rank;
1284           ev_shape.push_back(s[index]); // Append to new shape
1285         }
1286         Data ev(0.,ev_shape,getFunctionSpace());
1287         ev.typeMatchRight(*this);
1288         m_data->transpose(ev.m_data.get(), axis_offset);
1289         return ev;
1290  }  }
1291    
1292  Data  Data
1293  Data::length() const  Data::eigenvalues() const
1294    {
1295         // check input
1296         DataArrayView::ShapeType s=getDataPointShape();
1297         if (getDataPointRank()!=2)
1298            throw DataException("Error - Data::eigenvalues can only be calculated for rank 2 object.");
1299         if(s[0] != s[1])
1300            throw DataException("Error - Data::eigenvalues can only be calculated for object with equal first and second dimension.");
1301         // create return
1302         DataArrayView::ShapeType ev_shape(1,s[0]);
1303         Data ev(0.,ev_shape,getFunctionSpace());
1304         ev.typeMatchRight(*this);
1305         m_data->eigenvalues(ev.m_data.get());
1306         return ev;
1307    }
1308    
1309    const boost::python::tuple
1310    Data::eigenvalues_and_eigenvectors(const double tol) const
1311  {  {
1312    return dp_algorithm(DataAlgorithmAdapter<Length>(0));       DataArrayView::ShapeType s=getDataPointShape();
1313         if (getDataPointRank()!=2)
1314            throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for rank 2 object.");
1315         if(s[0] != s[1])
1316            throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for object with equal first and second dimension.");
1317         // create return
1318         DataArrayView::ShapeType ev_shape(1,s[0]);
1319         Data ev(0.,ev_shape,getFunctionSpace());
1320         ev.typeMatchRight(*this);
1321         DataArrayView::ShapeType V_shape(2,s[0]);
1322         Data V(0.,V_shape,getFunctionSpace());
1323         V.typeMatchRight(*this);
1324         m_data->eigenvalues_and_eigenvectors(ev.m_data.get(),V.m_data.get(),tol);
1325         return make_tuple(boost::python::object(ev),boost::python::object(V));
1326  }  }
1327    
1328  Data  const boost::python::tuple
1329  Data::trace() const  Data::minGlobalDataPoint() const
1330  {  {
1331    return dp_algorithm(DataAlgorithmAdapter<Trace>(0));    // NB: calc_minGlobalDataPoint( had to be split off from minGlobalDataPoint( as boost::make_tuple causes an
1332      // abort (for unknown reasons) if there are openmp directives with it in the
1333      // surrounding function
1334    
1335      int DataPointNo;
1336      int ProcNo;
1337      calc_minGlobalDataPoint(ProcNo,DataPointNo);
1338      return make_tuple(ProcNo,DataPointNo);
1339  }  }
1340    
1341  Data  void
1342  Data::transpose(int axis) const  Data::calc_minGlobalDataPoint(int& ProcNo,
1343                            int& DataPointNo) const
1344  {  {
1345    // not implemented    int i,j;
1346    throw DataException("Error - Data::transpose not implemented yet.");    int lowi=0,lowj=0;
1347    return Data();    double min=numeric_limits<double>::max();
1348    
1349      Data temp=minval();
1350    
1351      int numSamples=temp.getNumSamples();
1352      int numDPPSample=temp.getNumDataPointsPerSample();
1353    
1354      double next,local_min;
1355      int local_lowi,local_lowj;
1356    
1357      #pragma omp parallel private(next,local_min,local_lowi,local_lowj)
1358      {
1359        local_min=min;
1360        #pragma omp for private(i,j) schedule(static)
1361        for (i=0; i<numSamples; i++) {
1362          for (j=0; j<numDPPSample; j++) {
1363            next=temp.getDataPoint(i,j)();
1364            if (next<local_min) {
1365              local_min=next;
1366              local_lowi=i;
1367              local_lowj=j;
1368            }
1369          }
1370        }
1371        #pragma omp critical
1372        if (local_min<min) {
1373          min=local_min;
1374          lowi=local_lowi;
1375          lowj=local_lowj;
1376        }
1377      }
1378    
1379    #ifdef PASO_MPI
1380        // determine the processor on which the minimum occurs
1381        next = temp.getDataPoint(lowi,lowj)();
1382        int lowProc = 0;
1383        double *globalMins = new double[get_MPISize()+1];
1384        int error = MPI_Gather ( &next, 1, MPI_DOUBLE, globalMins, 1, MPI_DOUBLE, 0, get_MPIComm() );
1385    
1386        if( get_MPIRank()==0 ){
1387            next = globalMins[lowProc];
1388            for( i=1; i<get_MPISize(); i++ )
1389                if( next>globalMins[i] ){
1390                    lowProc = i;
1391                    next = globalMins[i];
1392                }
1393        }
1394        MPI_Bcast( &lowProc, 1, MPI_DOUBLE, 0, get_MPIComm() );
1395    
1396        delete [] globalMins;
1397        ProcNo = lowProc;
1398    #else
1399        ProcNo = 0;
1400    #endif
1401      DataPointNo = lowj + lowi * numDPPSample;
1402  }  }
1403    
1404  void  void
1405  Data::saveDX(std::string fileName) const  Data::saveDX(std::string fileName) const
1406  {  {
1407    getDomain().saveDX(fileName,*this);    boost::python::dict args;
1408      args["data"]=boost::python::object(this);
1409      getDomain().saveDX(fileName,args);
1410    return;    return;
1411  }  }
1412    
1413  void  void
1414  Data::saveVTK(std::string fileName) const  Data::saveVTK(std::string fileName) const
1415  {  {
1416    getDomain().saveVTK(fileName,*this);    boost::python::dict args;
1417      args["data"]=boost::python::object(this);
1418      getDomain().saveVTK(fileName,args);
1419    return;    return;
1420  }  }
1421    
1422  Data&  Data&
1423  Data::operator+=(const Data& right)  Data::operator+=(const Data& right)
1424  {  {
1425      if (isProtected()) {
1426            throw DataException("Error - attempt to update protected Data object.");
1427      }
1428    binaryOp(right,plus<double>());    binaryOp(right,plus<double>());
1429    return (*this);    return (*this);
1430  }  }
# Line 990  Data::operator+=(const Data& right) Line 1432  Data::operator+=(const Data& right)
1432  Data&  Data&
1433  Data::operator+=(const boost::python::object& right)  Data::operator+=(const boost::python::object& right)
1434  {  {
1435    binaryOp(right,plus<double>());    Data tmp(right,getFunctionSpace(),false);
1436      binaryOp(tmp,plus<double>());
1437      return (*this);
1438    }
1439    Data&
1440    Data::operator=(const Data& other)
1441    {
1442      copy(other);
1443    return (*this);    return (*this);
1444  }  }
1445    
1446  Data&  Data&
1447  Data::operator-=(const Data& right)  Data::operator-=(const Data& right)
1448  {  {
1449      if (isProtected()) {
1450            throw DataException("Error - attempt to update protected Data object.");
1451      }
1452    binaryOp(right,minus<double>());    binaryOp(right,minus<double>());
1453    return (*this);    return (*this);
1454  }  }
# Line 1004  Data::operator-=(const Data& right) Line 1456  Data::operator-=(const Data& right)
1456  Data&  Data&
1457  Data::operator-=(const boost::python::object& right)  Data::operator-=(const boost::python::object& right)
1458  {  {
1459    binaryOp(right,minus<double>());    Data tmp(right,getFunctionSpace(),false);
1460      binaryOp(tmp,minus<double>());
1461    return (*this);    return (*this);
1462  }  }
1463    
1464  Data&  Data&
1465  Data::operator*=(const Data& right)  Data::operator*=(const Data& right)
1466  {  {
1467      if (isProtected()) {
1468            throw DataException("Error - attempt to update protected Data object.");
1469      }
1470    binaryOp(right,multiplies<double>());    binaryOp(right,multiplies<double>());
1471    return (*this);    return (*this);
1472  }  }
# Line 1018  Data::operator*=(const Data& right) Line 1474  Data::operator*=(const Data& right)
1474  Data&  Data&
1475  Data::operator*=(const boost::python::object& right)  Data::operator*=(const boost::python::object& right)
1476  {  {
1477    binaryOp(right,multiplies<double>());    Data tmp(right,getFunctionSpace(),false);
1478      binaryOp(tmp,multiplies<double>());
1479    return (*this);    return (*this);
1480  }  }
1481    
1482  Data&  Data&
1483  Data::operator/=(const Data& right)  Data::operator/=(const Data& right)
1484  {  {
1485      if (isProtected()) {
1486            throw DataException("Error - attempt to update protected Data object.");
1487      }
1488    binaryOp(right,divides<double>());    binaryOp(right,divides<double>());
1489    return (*this);    return (*this);
1490  }  }
# Line 1032  Data::operator/=(const Data& right) Line 1492  Data::operator/=(const Data& right)
1492  Data&  Data&
1493  Data::operator/=(const boost::python::object& right)  Data::operator/=(const boost::python::object& right)
1494  {  {
1495    binaryOp(right,divides<double>());    Data tmp(right,getFunctionSpace(),false);
1496      binaryOp(tmp,divides<double>());
1497    return (*this);    return (*this);
1498  }  }
1499    
1500  Data  Data
1501    Data::rpowO(const boost::python::object& left) const
1502    {
1503      Data left_d(left,*this);
1504      return left_d.powD(*this);
1505    }
1506    
1507    Data
1508  Data::powO(const boost::python::object& right) const  Data::powO(const boost::python::object& right) const
1509  {  {
1510    Data result;    Data tmp(right,getFunctionSpace(),false);
1511    result.copy(*this);    return powD(tmp);
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1512  }  }
1513    
1514  Data  Data
1515  Data::powD(const Data& right) const  Data::powD(const Data& right) const
1516  {  {
1517    Data result;    return C_TensorBinaryOperation<double (*)(double, double)>(*this, right, ::pow);
   result.copy(*this);  
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1518  }  }
1519    
1520  //  //
1521  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1522  Data  Data
1523  escript::operator+(const Data& left, const Data& right)  escript::operator+(const Data& left, const Data& right)
1524  {  {
1525    Data result;    return C_TensorBinaryOperation(left, right, plus<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result+=right;  
   return result;  
1526  }  }
1527    
1528  //  //
1529  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1530  Data  Data
1531  escript::operator-(const Data& left, const Data& right)  escript::operator-(const Data& left, const Data& right)
1532  {  {
1533    Data result;    return C_TensorBinaryOperation(left, right, minus<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result-=right;  
   return result;  
1534  }  }
1535    
1536  //  //
1537  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1538  Data  Data
1539  escript::operator*(const Data& left, const Data& right)  escript::operator*(const Data& left, const Data& right)
1540  {  {
1541    Data result;    return C_TensorBinaryOperation(left, right, multiplies<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result*=right;  
   return result;  
1542  }  }
1543    
1544  //  //
1545  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1546  Data  Data
1547  escript::operator/(const Data& left, const Data& right)  escript::operator/(const Data& left, const Data& right)
1548  {  {
1549    Data result;    return C_TensorBinaryOperation(left, right, divides<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result/=right;  
   return result;  
1550  }  }
1551    
1552  //  //
1553  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1554  Data  Data
1555  escript::operator+(const Data& left, const boost::python::object& right)  escript::operator+(const Data& left, const boost::python::object& right)
1556  {  {
1557    //    return left+Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result+=right;  
   return result;  
1558  }  }
1559    
1560  //  //
1561  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1562  Data  Data
1563  escript::operator-(const Data& left, const boost::python::object& right)  escript::operator-(const Data& left, const boost::python::object& right)
1564  {  {
1565    //    return left-Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result-=right;  
   return result;  
1566  }  }
1567    
1568  //  //
1569  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1570  Data  Data
1571  escript::operator*(const Data& left, const boost::python::object& right)  escript::operator*(const Data& left, const boost::python::object& right)
1572  {  {
1573    //    return left*Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result*=right;  
   return result;  
1574  }  }
1575    
1576  //  //
1577  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1578  Data  Data
1579  escript::operator/(const Data& left, const boost::python::object& right)  escript::operator/(const Data& left, const boost::python::object& right)
1580  {  {
1581    //    return left/Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result/=right;  
   return result;  
1582  }  }
1583    
1584  //  //
1585  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1586  Data  Data
1587  escript::operator+(const boost::python::object& left, const Data& right)  escript::operator+(const boost::python::object& left, const Data& right)
1588  {  {
1589    //    return Data(left,right.getFunctionSpace(),false)+right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result+=right;  
   return result;  
1590  }  }
1591    
1592  //  //
1593  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1594  Data  Data
1595  escript::operator-(const boost::python::object& left, const Data& right)  escript::operator-(const boost::python::object& left, const Data& right)
1596  {  {
1597    //    return Data(left,right.getFunctionSpace(),false)-right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result-=right;  
   return result;  
1598  }  }
1599    
1600  //  //
1601  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1602  Data  Data
1603  escript::operator*(const boost::python::object& left, const Data& right)  escript::operator*(const boost::python::object& left, const Data& right)
1604  {  {
1605    //    return Data(left,right.getFunctionSpace(),false)*right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result*=right;  
   return result;  
1606  }  }
1607    
1608  //  //
1609  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1610  Data  Data
1611  escript::operator/(const boost::python::object& left, const Data& right)  escript::operator/(const boost::python::object& left, const Data& right)
1612  {  {
1613    //    return Data(left,right.getFunctionSpace(),false)/right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result/=right;  
   return result;  
1614  }  }
1615    
1616  //  //
 // NOTE: It is essential to specify the namepsace this operator belongs to  
1617  //bool escript::operator==(const Data& left, const Data& right)  //bool escript::operator==(const Data& left, const Data& right)
1618  //{  //{
1619  //  /*  //  /*
# Line 1268  escript::operator/(const boost::python:: Line 1658  escript::operator/(const boost::python::
1658  //  return ret;  //  return ret;
1659  //}  //}
1660    
1661    /* TODO */
1662    /* global reduction */
1663  Data  Data
1664  Data::getItem(const boost::python::object& key) const  Data::getItem(const boost::python::object& key) const
1665  {  {
1666    const DataArrayView& view=getPointDataView();    const DataArrayView& view=getPointDataView();
1667    
# Line 1282  Data::getItem(const boost::python::objec Line 1674  Data::getItem(const boost::python::objec
1674    return getSlice(slice_region);    return getSlice(slice_region);
1675  }  }
1676    
1677    /* TODO */
1678    /* global reduction */
1679  Data  Data
1680  Data::getSlice(const DataArrayView::RegionType& region) const  Data::getSlice(const DataArrayView::RegionType& region) const
1681  {  {
1682    return Data(*this,region);    return Data(*this,region);
1683  }  }
1684    
1685    /* TODO */
1686    /* global reduction */
1687  void  void
1688  Data::setItemO(const boost::python::object& key,  Data::setItemO(const boost::python::object& key,
1689                 const boost::python::object& value)                 const boost::python::object& value)
# Line 1301  Data::setItemD(const boost::python::obje Line 1697  Data::setItemD(const boost::python::obje
1697                 const Data& value)                 const Data& value)
1698  {  {
1699    const DataArrayView& view=getPointDataView();    const DataArrayView& view=getPointDataView();
1700    
1701    DataArrayView::RegionType slice_region=view.getSliceRegion(key);    DataArrayView::RegionType slice_region=view.getSliceRegion(key);
1702    if (slice_region.size()!=view.getRank()) {    if (slice_region.size()!=view.getRank()) {
1703      throw DataException("Error - slice size does not match Data rank.");      throw DataException("Error - slice size does not match Data rank.");
# Line 1316  void Line 1713  void
1713  Data::setSlice(const Data& value,  Data::setSlice(const Data& value,
1714                 const DataArrayView::RegionType& region)                 const DataArrayView::RegionType& region)
1715  {  {
1716      if (isProtected()) {
1717            throw DataException("Error - attempt to update protected Data object.");
1718      }
1719    Data tempValue(value);    Data tempValue(value);
1720    typeMatchLeft(tempValue);    typeMatchLeft(tempValue);
1721    typeMatchRight(tempValue);    typeMatchRight(tempValue);
# Line 1351  Data::typeMatchRight(const Data& right) Line 1751  Data::typeMatchRight(const Data& right)
1751  }  }
1752    
1753  void  void
1754    Data::setTaggedValueByName(std::string name,
1755                               const boost::python::object& value)
1756    {
1757         if (getFunctionSpace().getDomain().isValidTagName(name)) {
1758            int tagKey=getFunctionSpace().getDomain().getTag(name);
1759            setTaggedValue(tagKey,value);
1760         }
1761    }
1762    void
1763  Data::setTaggedValue(int tagKey,  Data::setTaggedValue(int tagKey,
1764                       const boost::python::object& value)                       const boost::python::object& value)
1765  {  {
1766      if (isProtected()) {
1767            throw DataException("Error - attempt to update protected Data object.");
1768      }
1769    //    //
1770    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
1771    tag();    if (isConstant()) tag();
1772    
1773      numeric::array asNumArray(value);
1774    
1775    
1776    if (!isTagged()) {    // extract the shape of the numarray
1777      throw DataException("Error - DataTagged conversion failed!!");    DataArrayView::ShapeType tempShape;
1778      for (int i=0; i < asNumArray.getrank(); i++) {
1779        tempShape.push_back(extract<int>(asNumArray.getshape()[i]));
1780    }    }
1781    
1782    //    // get the space for the data vector
1783    // Construct DataArray from boost::python::object input value    int len = DataArrayView::noValues(tempShape);
1784    DataArray valueDataArray(value);    DataVector temp_data(len, 0.0, len);
1785      DataArrayView temp_dataView(temp_data, tempShape);
1786      temp_dataView.copy(asNumArray);
1787    
1788    //    //
1789    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
1790    m_data->setTaggedValue(tagKey,valueDataArray.getView());    m_data->setTaggedValue(tagKey,temp_dataView);
1791  }  }
1792    
1793  void  void
1794  Data::setTaggedValueFromCPP(int tagKey,  Data::setTaggedValueFromCPP(int tagKey,
1795                              const DataArrayView& value)                              const DataArrayView& value)
1796  {  {
1797      if (isProtected()) {
1798            throw DataException("Error - attempt to update protected Data object.");
1799      }
1800    //    //
1801    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
1802    tag();    if (isConstant()) tag();
1803    
   if (!isTagged()) {  
     throw DataException("Error - DataTagged conversion failed!!");  
   }  
                                                                                                                 
1804    //    //
1805    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
1806    m_data->setTaggedValue(tagKey,value);    m_data->setTaggedValue(tagKey,value);
1807  }  }
1808    
1809  void  int
1810  Data::setRefValue(int ref,  Data::getTagNumber(int dpno)
                   const boost::python::numeric::array& value)  
 {  
   //  
   // Construct DataArray from boost::python::object input value  
   DataArray valueDataArray(value);  
   
   //  
   // Call DataAbstract::setRefValue  
   m_data->setRefValue(ref,valueDataArray);  
 }  
   
 void  
 Data::getRefValue(int ref,  
                   boost::python::numeric::array& value)  
1811  {  {
1812    //    return getFunctionSpace().getTagFromSampleNo(dpno);
   // Construct DataArray for boost::python::object return value  
   DataArray valueDataArray(value);  
   
   //  
   // Load DataArray with values from data-points specified by ref  
   m_data->getRefValue(ref,valueDataArray);  
   
   //  
   // Load values from valueDataArray into return numarray  
   
   // extract the shape of the numarray  
   int rank = value.getrank();  
   DataArrayView::ShapeType shape;  
   for (int i=0; i < rank; i++) {  
     shape.push_back(extract<int>(value.getshape()[i]));  
   }  
   
   // and load the numarray with the data from the DataArray  
   DataArrayView valueView = valueDataArray.getView();  
   
   if (rank==0) {  
     throw DataException("Data::getRefValue error: only rank 1 data handled for now.");  
   }  
   if (rank==1) {  
     for (int i=0; i < shape[0]; i++) {  
       value[i] = valueView(i);  
     }  
   }  
   if (rank==2) {  
     throw DataException("Data::getRefValue error: only rank 1 data handled for now.");  
   }  
   if (rank==3) {  
     throw DataException("Data::getRefValue error: only rank 1 data handled for now.");  
   }  
   if (rank==4) {  
     throw DataException("Data::getRefValue error: only rank 1 data handled for now.");  
   }  
   
1813  }  }
1814    
1815  void  void
# Line 1471  Data::archiveData(const std::string file Line 1837  Data::archiveData(const std::string file
1837      dataType = 3;      dataType = 3;
1838      cout << "\tdataType: DataExpanded" << endl;      cout << "\tdataType: DataExpanded" << endl;
1839    }    }
1840    
1841    if (dataType == -1) {    if (dataType == -1) {
1842      throw DataException("archiveData Error: undefined dataType");      throw DataException("archiveData Error: undefined dataType");
1843    }    }
# Line 1484  Data::archiveData(const std::string file Line 1851  Data::archiveData(const std::string file
1851    int dataPointSize = getDataPointSize();    int dataPointSize = getDataPointSize();
1852    int dataLength = getLength();    int dataLength = getLength();
1853    DataArrayView::ShapeType dataPointShape = getDataPointShape();    DataArrayView::ShapeType dataPointShape = getDataPointShape();
1854    int referenceNumbers[noSamples];    vector<int> referenceNumbers(noSamples);
1855    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
1856      referenceNumbers[sampleNo] = getFunctionSpace().getReferenceNoFromSampleNo(sampleNo);      referenceNumbers[sampleNo] = getFunctionSpace().getReferenceIDOfSample(sampleNo);
1857    }    }
1858    int tagNumbers[noSamples];    vector<int> tagNumbers(noSamples);
1859    if (isTagged()) {    if (isTagged()) {
1860      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
1861        tagNumbers[sampleNo] = getFunctionSpace().getTagFromSampleNo(sampleNo);        tagNumbers[sampleNo] = getFunctionSpace().getTagFromSampleNo(sampleNo);
# Line 1510  Data::archiveData(const std::string file Line 1877  Data::archiveData(const std::string file
1877    cout << ">" << endl;    cout << ">" << endl;
1878    
1879    //    //
1880    // Write common data items to archive file    // Open archive file
1881    ofstream archiveFile;    ofstream archiveFile;
1882    archiveFile.open(fileName.data(), ios::out);    archiveFile.open(fileName.data(), ios::out);
1883    
# Line 1518  Data::archiveData(const std::string file Line 1885  Data::archiveData(const std::string file
1885      throw DataException("archiveData Error: problem opening archive file");      throw DataException("archiveData Error: problem opening archive file");
1886    }    }
1887    
1888      //
1889      // Write common data items to archive file
1890    archiveFile.write(reinterpret_cast<char *>(&dataType),sizeof(int));    archiveFile.write(reinterpret_cast<char *>(&dataType),sizeof(int));
1891    archiveFile.write(reinterpret_cast<char *>(&noSamples),sizeof(int));    archiveFile.write(reinterpret_cast<char *>(&noSamples),sizeof(int));
1892    archiveFile.write(reinterpret_cast<char *>(&noDPPSample),sizeof(int));    archiveFile.write(reinterpret_cast<char *>(&noDPPSample),sizeof(int));
# Line 1541  Data::archiveData(const std::string file Line 1910  Data::archiveData(const std::string file
1910      throw DataException("archiveData Error: problem writing to archive file");      throw DataException("archiveData Error: problem writing to archive file");
1911    }    }
1912    
   archiveFile.close();  
   
   if (!archiveFile.good()) {  
     throw DataException("archiveData Error: problem closing archive file");  
   }  
   
1913    //    //
1914    // Collect and archive underlying data values for each Data type    // Archive underlying data values for each Data type
1915      int noValues;
1916    switch (dataType) {    switch (dataType) {
1917      case 0:      case 0:
1918        // DataEmpty        // DataEmpty
1919          noValues = 0;
1920          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1921          cout << "\tnoValues: " << noValues << endl;
1922        break;        break;
1923      case 1:      case 1:
1924        // DataConstant        // DataConstant
1925          noValues = m_data->getLength();
1926          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1927          cout << "\tnoValues: " << noValues << endl;
1928          if (m_data->archiveData(archiveFile,noValues)) {
1929            throw DataException("archiveData Error: problem writing data to archive file");
1930          }
1931        break;        break;
1932      case 2:      case 2:
1933        // DataTagged        // DataTagged
1934          noValues = m_data->getLength();
1935          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1936          cout << "\tnoValues: " << noValues << endl;
1937          if (m_data->archiveData(archiveFile,noValues)) {
1938            throw DataException("archiveData Error: problem writing data to archive file");
1939          }
1940        break;        break;
1941      case 3:      case 3:
1942        // DataExpanded        // DataExpanded
1943          noValues = m_data->getLength();
1944          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1945          cout << "\tnoValues: " << noValues << endl;
1946          if (m_data->archiveData(archiveFile,noValues)) {
1947            throw DataException("archiveData Error: problem writing data to archive file");
1948          }
1949        break;        break;
1950    }    }
1951    
1952      if (!archiveFile.good()) {
1953        throw DataException("archiveData Error: problem writing data to archive file");
1954      }
1955    
1956      //
1957      // Close archive file
1958      archiveFile.close();
1959    
1960      if (!archiveFile.good()) {
1961        throw DataException("archiveData Error: problem closing archive file");
1962      }
1963    
1964  }  }
1965    
1966  void  void
# Line 1589  Data::extractData(const std::string file Line 1986  Data::extractData(const std::string file
1986    int flatShape[4];    int flatShape[4];
1987    
1988    //    //
1989    // Open the archive file and read common data items    // Open the archive file
1990    ifstream archiveFile;    ifstream archiveFile;
1991    archiveFile.open(fileName.data(), ios::in);    archiveFile.open(fileName.data(), ios::in);
1992    
# Line 1597  Data::extractData(const std::string file Line 1994  Data::extractData(const std::string file
1994      throw DataException("extractData Error: problem opening archive file");      throw DataException("extractData Error: problem opening archive file");
1995    }    }
1996    
1997      //
1998      // Read common data items from archive file
1999    archiveFile.read(reinterpret_cast<char *>(&dataType),sizeof(int));    archiveFile.read(reinterpret_cast<char *>(&dataType),sizeof(int));
2000    archiveFile.read(reinterpret_cast<char *>(&noSamples),sizeof(int));    archiveFile.read(reinterpret_cast<char *>(&noSamples),sizeof(int));
2001    archiveFile.read(reinterpret_cast<char *>(&noDPPSample),sizeof(int));    archiveFile.read(reinterpret_cast<char *>(&noDPPSample),sizeof(int));
# Line 1610  Data::extractData(const std::string file Line 2009  Data::extractData(const std::string file
2009        dataPointShape.push_back(flatShape[dim]);        dataPointShape.push_back(flatShape[dim]);
2010      }      }
2011    }    }
2012    int referenceNumbers[noSamples];    vector<int> referenceNumbers(noSamples);
2013    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
2014      archiveFile.read(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));      archiveFile.read(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));
2015    }    }
2016    int tagNumbers[noSamples];    vector<int> tagNumbers(noSamples);
2017    if (dataType==2) {    if (dataType==2) {
2018      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
2019        archiveFile.read(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));        archiveFile.read(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));
# Line 1625  Data::extractData(const std::string file Line 2024  Data::extractData(const std::string file
2024      throw DataException("extractData Error: problem reading from archive file");      throw DataException("extractData Error: problem reading from archive file");
2025    }    }
2026    
2027    archiveFile.close();    //
2028      // Verify the values just read from the archive file
   if (!archiveFile.good()) {  
     throw DataException("extractData Error: problem closing archive file");  
   }  
   
2029    switch (dataType) {    switch (dataType) {
2030      case 0:      case 0:
2031        cout << "\tdataType: DataEmpty" << endl;        cout << "\tdataType: DataEmpty" << endl;
# Line 1667  Data::extractData(const std::string file Line 2062  Data::extractData(const std::string file
2062      throw DataException("extractData Error: incompatible FunctionSpace");      throw DataException("extractData Error: incompatible FunctionSpace");
2063    }    }
2064    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
2065      if (referenceNumbers[sampleNo] != fspace.getReferenceNoFromSampleNo(sampleNo)) {      if (referenceNumbers[sampleNo] != fspace.getReferenceIDOfSample(sampleNo)) {
2066        throw DataException("extractData Error: incompatible FunctionSpace");        throw DataException("extractData Error: incompatible FunctionSpace");
2067      }      }
2068    }    }
# Line 1685  Data::extractData(const std::string file Line 2080  Data::extractData(const std::string file
2080    
2081    //    //
2082    // Load this DataVector with the appropriate values    // Load this DataVector with the appropriate values
2083      int noValues;
2084      archiveFile.read(reinterpret_cast<char *>(&noValues),sizeof(int));
2085      cout << "\tnoValues: " << noValues << endl;
2086    switch (dataType) {    switch (dataType) {
2087      case 0:      case 0:
2088        // DataEmpty        // DataEmpty
2089          if (noValues != 0) {
2090            throw DataException("extractData Error: problem reading data from archive file");
2091          }
2092        break;        break;
2093      case 1:      case 1:
2094        // DataConstant        // DataConstant
2095          if (dataVec.extractData(archiveFile,noValues)) {
2096            throw DataException("extractData Error: problem reading data from archive file");
2097          }
2098        break;        break;
2099      case 2:      case 2:
2100        // DataTagged        // DataTagged
2101          if (dataVec.extractData(archiveFile,noValues)) {
2102            throw DataException("extractData Error: problem reading data from archive file");
2103          }
2104        break;        break;
2105      case 3:      case 3:
2106        // DataExpanded        // DataExpanded
2107          if (dataVec.extractData(archiveFile,noValues)) {
2108            throw DataException("extractData Error: problem reading data from archive file");
2109          }
2110        break;        break;
2111    }    }
2112    
2113      if (!archiveFile.good()) {
2114        throw DataException("extractData Error: problem reading from archive file");
2115      }
2116    
2117      //
2118      // Close archive file
2119      archiveFile.close();
2120    
2121      if (!archiveFile.good()) {
2122        throw DataException("extractData Error: problem closing archive file");
2123      }
2124    
2125    //    //
2126    // Construct an appropriate Data object    // Construct an appropriate Data object
2127    DataAbstract* tempData;    DataAbstract* tempData;
# Line 1723  Data::extractData(const std::string file Line 2145  Data::extractData(const std::string file
2145    }    }
2146    shared_ptr<DataAbstract> temp_data(tempData);    shared_ptr<DataAbstract> temp_data(tempData);
2147    m_data=temp_data;    m_data=temp_data;
   
2148  }  }
2149    
2150  ostream& escript::operator<<(ostream& o, const Data& data)  ostream& escript::operator<<(ostream& o, const Data& data)
# Line 1731  ostream& escript::operator<<(ostream& o, Line 2152  ostream& escript::operator<<(ostream& o,
2152    o << data.toString();    o << data.toString();
2153    return o;    return o;
2154  }  }
2155    
2156    Data
2157    escript::C_GeneralTensorProduct(Data& arg_0,
2158                         Data& arg_1,
2159                         int axis_offset,
2160                         int transpose)
2161    {
2162      // General tensor product: res(SL x SR) = arg_0(SL x SM) * arg_1(SM x SR)
2163      // SM is the product of the last axis_offset entries in arg_0.getShape().
2164    
2165      // Interpolate if necessary and find an appropriate function space
2166      Data arg_0_Z, arg_1_Z;
2167      if (arg_0.getFunctionSpace()!=arg_1.getFunctionSpace()) {
2168        if (arg_0.probeInterpolation(arg_1.getFunctionSpace())) {
2169          arg_0_Z = arg_0.interpolate(arg_1.getFunctionSpace());
2170          arg_1_Z = Data(arg_1);
2171        }
2172        else if (arg_1.probeInterpolation(arg_0.getFunctionSpace())) {
2173          arg_1_Z=arg_1.interpolate(arg_0.getFunctionSpace());
2174          arg_0_Z =Data(arg_0);
2175        }
2176        else {
2177          throw DataException("Error - C_GeneralTensorProduct: arguments have incompatible function spaces.");
2178        }
2179      } else {
2180          arg_0_Z = Data(arg_0);
2181          arg_1_Z = Data(arg_1);
2182      }
2183      // Get rank and shape of inputs
2184      int rank0 = arg_0_Z.getDataPointRank();
2185      int rank1 = arg_1_Z.getDataPointRank();
2186      DataArrayView::ShapeType shape0 = arg_0_Z.getDataPointShape();
2187      DataArrayView::ShapeType shape1 = arg_1_Z.getDataPointShape();
2188    
2189      // Prepare for the loops of the product and verify compatibility of shapes
2190      int start0=0, start1=0;
2191      if (transpose == 0)       {}
2192      else if (transpose == 1)  { start0 = axis_offset; }
2193      else if (transpose == 2)  { start1 = rank1-axis_offset; }
2194      else              { throw DataException("C_GeneralTensorProduct: Error - transpose should be 0, 1 or 2"); }
2195    
2196      // Adjust the shapes for transpose
2197      DataArrayView::ShapeType tmpShape0;
2198      DataArrayView::ShapeType tmpShape1;
2199      for (int i=0; i<rank0; i++)   { tmpShape0.push_back( shape0[(i+start0)%rank0] ); }
2200      for (int i=0; i<rank1; i++)   { tmpShape1.push_back( shape1[(i+start1)%rank1] ); }
2201    
2202    #if 0
2203      // For debugging: show shape after transpose
2204      char tmp[100];
2205      std::string shapeStr;
2206      shapeStr = "(";
2207      for (int i=0; i<rank0; i++)   { sprintf(tmp, "%d,", tmpShape0[i]); shapeStr += tmp; }
2208      shapeStr += ")";
2209      cout << "C_GeneralTensorProduct: Shape of arg0 is " << shapeStr << endl;
2210      shapeStr = "(";
2211      for (int i=0; i<rank1; i++)   { sprintf(tmp, "%d,", tmpShape1[i]); shapeStr += tmp; }
2212      shapeStr += ")";
2213      cout << "C_GeneralTensorProduct: Shape of arg1 is " << shapeStr << endl;
2214    #endif
2215    
2216      // Prepare for the loops of the product
2217      int SL=1, SM=1, SR=1;
2218      for (int i=0; i<rank0-axis_offset; i++)   {
2219        SL *= tmpShape0[i];
2220      }
2221      for (int i=rank0-axis_offset; i<rank0; i++)   {
2222        if (tmpShape0[i] != tmpShape1[i-(rank0-axis_offset)]) {
2223          throw DataException("C_GeneralTensorProduct: Error - incompatible shapes");
2224        }
2225        SM *= tmpShape0[i];
2226      }
2227      for (int i=axis_offset; i<rank1; i++)     {
2228        SR *= tmpShape1[i];
2229      }
2230    
2231      // Define the shape of the output
2232      DataArrayView::ShapeType shape2;
2233      for (int i=0; i<rank0-axis_offset; i++) { shape2.push_back(tmpShape0[i]); } // First part of arg_0_Z
2234      for (int i=axis_offset; i<rank1; i++)   { shape2.push_back(tmpShape1[i]); } // Last part of arg_1_Z
2235    
2236      // Declare output Data object
2237      Data res;
2238    
2239      if      (arg_0_Z.isConstant()   && arg_1_Z.isConstant()) {
2240        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataConstant output
2241        double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[0]);
2242        double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[0]);
2243        double *ptr_2 = &((res.getPointDataView().getData())[0]);
2244        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2245      }
2246      else if (arg_0_Z.isConstant()   && arg_1_Z.isTagged()) {
2247    
2248        // Prepare the DataConstant input
2249        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2250        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2251    
2252        // Borrow DataTagged input from Data object
2253        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2254        if (tmp_1==0) { throw DataException("GTP_1 Programming error - casting to DataTagged."); }
2255    
2256        // Prepare a DataTagged output 2
2257        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataTagged output
2258        res.tag();
2259        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2260        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2261    
2262        // Prepare offset into DataConstant
2263        int offset_0 = tmp_0->getPointOffset(0,0);
2264        double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2265        // Get the views
2266        DataArrayView view_1 = tmp_1->getDefaultValue();
2267        DataArrayView view_2 = tmp_2->getDefaultValue();
2268        // Get the pointers to the actual data
2269        double *ptr_1 = &((view_1.getData())[0]);
2270        double *ptr_2 = &((view_2.getData())[0]);
2271        // Compute an MVP for the default
2272        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2273        // Compute an MVP for each tag
2274        const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2275        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2276        for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2277          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2278          DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2279          DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2280          double *ptr_1 = &view_1.getData(0);
2281          double *ptr_2 = &view_2.getData(0);
2282          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2283        }
2284    
2285      }
2286      else if (arg_0_Z.isConstant()   && arg_1_Z.isExpanded()) {
2287    
2288        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2289        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2290        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2291        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2292        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2293        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2294        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2295        int sampleNo_1,dataPointNo_1;
2296        int numSamples_1 = arg_1_Z.getNumSamples();
2297        int numDataPointsPerSample_1 = arg_1_Z.getNumDataPointsPerSample();
2298        int offset_0 = tmp_0->getPointOffset(0,0);
2299        #pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)
2300        for (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {
2301          for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {
2302            int offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);
2303            int offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);
2304            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2305            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2306            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2307            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2308          }
2309        }
2310    
2311      }
2312      else if (arg_0_Z.isTagged()     && arg_1_Z.isConstant()) {
2313    
2314        // Borrow DataTagged input from Data object
2315        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2316        if (tmp_0==0) { throw DataException("GTP_0 Programming error - casting to DataTagged."); }
2317    
2318        // Prepare the DataConstant input
2319        DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2320        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2321    
2322        // Prepare a DataTagged output 2
2323        res = Data(0.0, shape2, arg_0_Z.getFunctionSpace());    // DataTagged output
2324        res.tag();
2325        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2326        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2327    
2328        // Prepare offset into DataConstant
2329        int offset_1 = tmp_1->getPointOffset(0,0);
2330        double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2331        // Get the views
2332        DataArrayView view_0 = tmp_0->getDefaultValue();
2333        DataArrayView view_2 = tmp_2->getDefaultValue();
2334        // Get the pointers to the actual data
2335        double *ptr_0 = &((view_0.getData())[0]);
2336        double *ptr_2 = &((view_2.getData())[0]);
2337        // Compute an MVP for the default
2338        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2339        // Compute an MVP for each tag
2340        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2341        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2342        for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2343          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2344          DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2345          DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2346          double *ptr_0 = &view_0.getData(0);
2347          double *ptr_2 = &view_2.getData(0);
2348          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2349        }
2350    
2351      }
2352      else if (arg_0_Z.isTagged()     && arg_1_Z.isTagged()) {
2353    
2354        // Borrow DataTagged input from Data object
2355        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2356        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2357    
2358        // Borrow DataTagged input from Data object
2359        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2360        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2361    
2362        // Prepare a DataTagged output 2
2363        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());
2364        res.tag();  // DataTagged output
2365        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2366        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2367    
2368        // Get the views
2369        DataArrayView view_0 = tmp_0->getDefaultValue();
2370        DataArrayView view_1 = tmp_1->getDefaultValue();
2371        DataArrayView view_2 = tmp_2->getDefaultValue();
2372        // Get the pointers to the actual data
2373        double *ptr_0 = &((view_0.getData())[0]);
2374        double *ptr_1 = &((view_1.getData())[0]);
2375        double *ptr_2 = &((view_2.getData())[0]);
2376        // Compute an MVP for the default
2377        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2378        // Merge the tags
2379        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2380        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2381        const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2382        for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2383          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue()); // use tmp_2 to get correct shape
2384        }
2385        for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2386          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2387        }
2388        // Compute an MVP for each tag
2389        const DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();
2390        for (i=lookup_2.begin();i!=lookup_2.end();i++) {
2391          DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2392          DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2393          DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2394          double *ptr_0 = &view_0.getData(0);
2395          double *ptr_1 = &view_1.getData(0);
2396          double *ptr_2 = &view_2.getData(0);
2397          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2398        }
2399    
2400      }
2401      else if (arg_0_Z.isTagged()     && arg_1_Z.isExpanded()) {
2402    
2403        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2404        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2405        DataTagged*   tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2406        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2407        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2408        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2409        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2410        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2411        int sampleNo_0,dataPointNo_0;
2412        int numSamples_0 = arg_0_Z.getNumSamples();
2413        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2414        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2415        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2416          int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0
2417          double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2418          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2419            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2420            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2421            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2422            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2423            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2424          }
2425        }
2426    
2427      }
2428      else if (arg_0_Z.isExpanded()   && arg_1_Z.isConstant()) {
2429    
2430        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2431        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2432        DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2433        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2434        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2435        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2436        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2437        int sampleNo_0,dataPointNo_0;
2438        int numSamples_0 = arg_0_Z.getNumSamples();
2439        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2440        int offset_1 = tmp_1->getPointOffset(0,0);
2441        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2442        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2443          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2444            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2445            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2446            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2447            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2448            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2449            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2450          }
2451        }
2452    
2453    
2454      }
2455      else if (arg_0_Z.isExpanded()   && arg_1_Z.isTagged()) {
2456    
2457        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2458        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2459        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2460        DataTagged*   tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2461        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2462        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2463        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2464        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2465        int sampleNo_0,dataPointNo_0;
2466        int numSamples_0 = arg_0_Z.getNumSamples();
2467        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2468        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2469        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2470          int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);
2471          double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2472          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2473            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2474            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2475            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2476            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2477            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2478          }
2479        }
2480    
2481      }
2482      else if (arg_0_Z.isExpanded()   && arg_1_Z.isExpanded()) {
2483    
2484        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2485        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2486        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2487        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2488        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2489        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2490        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2491        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2492        int sampleNo_0,dataPointNo_0;
2493        int numSamples_0 = arg_0_Z.getNumSamples();
2494        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2495        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2496        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2497          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2498            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2499            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2500            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2501            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2502            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2503            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2504            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2505          }
2506        }
2507    
2508      }
2509      else {
2510        throw DataException("Error - C_GeneralTensorProduct: unknown combination of inputs");
2511      }
2512    
2513      return res;
2514    }
2515    
2516    DataAbstract*
2517    Data::borrowData() const
2518    {
2519      return m_data.get();
2520    }
2521    
2522    /* Member functions specific to the MPI implementation */
2523    
2524    void
2525    Data::print()
2526    {
2527      int i,j;
2528    
2529      printf( "Data is %dX%d\n", getNumSamples(), getNumDataPointsPerSample() );
2530      for( i=0; i<getNumSamples(); i++ )
2531      {
2532        printf( "[%6d]", i );
2533        for( j=0; j<getNumDataPointsPerSample(); j++ )
2534          printf( "\t%10.7g", (getSampleData(i))[j] );
2535        printf( "\n" );
2536      }
2537    }
2538    void
2539    Data::dump(const std::string fileName) const
2540    {
2541      try
2542         {
2543            return m_data->dump(fileName);
2544         }
2545         catch (exception& e)
2546         {
2547            cout << e.what() << endl;
2548         }
2549    }
2550    
2551    int
2552    Data::get_MPISize() const
2553    {
2554        int error, size;
2555    #ifdef PASO_MPI
2556        error = MPI_Comm_size( get_MPIComm(), &size );
2557    #else
2558        size = 1;
2559    #endif
2560        return size;
2561    }
2562    
2563    int
2564    Data::get_MPIRank() const
2565    {
2566        int error, rank;
2567    #ifdef PASO_MPI
2568        error = MPI_Comm_rank( get_MPIComm(), &rank );
2569    #else
2570        rank = 0;
2571    #endif
2572        return rank;
2573    }
2574    
2575    MPI_Comm
2576    Data::get_MPIComm() const
2577    {
2578    #ifdef PASO_MPI
2579        return MPI_COMM_WORLD;
2580    #else
2581        return -1;
2582    #endif
2583    }
2584    

Legend:
Removed from v.122  
changed lines
  Added in v.1387

  ViewVC Help
Powered by ViewVC 1.1.26