/[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 121 by jgs, Fri May 6 04:26:16 2005 UTC trunk/escript/src/Data.cpp revision 1327 by matt, Fri Oct 12 07:10:40 2007 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/DataAlgorithm.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 52  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 63  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 72  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 90  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 99  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 111  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 122  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 132  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 139  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 147  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(temp_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 204  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 257  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 303  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 344  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 escript::unaryOp(*this,bind1st(divides<double>(),1.));
431  }  }
432    
433  Data  Data
# Line 375  Data::whereNonPositive() const Line 455  Data::whereNonPositive() const
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 escript::unaryOp(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 escript::unaryOp(dataAbs,bind2nd(greater<double>(),tol));
469  }  }
470    
471  Data  Data
# Line 410  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 443  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 463  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 490  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 697  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 770  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 784  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 796  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 827  Data::tan() const Line 920  Data::tan() const
920  }  }
921    
922  Data  Data
923  Data::log() const  Data::asin() const
924    {
925      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::asin);
926    }
927    
928    Data
929    Data::acos() const
930    {
931      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::acos);
932    }
933    
934    
935    Data
936    Data::atan() const
937    {
938      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::atan);
939    }
940    
941    Data
942    Data::sinh() const
943    {
944      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sinh);
945    }
946    
947    Data
948    Data::cosh() const
949    {
950      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::cosh);
951    }
952    
953    Data
954    Data::tanh() const
955    {
956      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::tanh);
957    }
958    
959    
960    Data
961    Data::erf() const
962    {
963    #ifdef _WIN32
964      throw DataException("Error - Data:: erf function is not supported on _WIN32 platforms.");
965    #else
966      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::erf);
967    #endif
968    }
969    
970    Data
971    Data::asinh() const
972    {
973    #ifdef _WIN32
974      return escript::unaryOp(*this,escript::asinh_substitute);
975    #else
976      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::asinh);
977    #endif
978    }
979    
980    Data
981    Data::acosh() const
982    {
983    #ifdef _WIN32
984      return escript::unaryOp(*this,escript::acosh_substitute);
985    #else
986      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::acosh);
987    #endif
988    }
989    
990    Data
991    Data::atanh() const
992    {
993    #ifdef _WIN32
994      return escript::unaryOp(*this,escript::atanh_substitute);
995    #else
996      return escript::unaryOp(*this,(Data::UnaryDFunPtr)::atanh);
997    #endif
998    }
999    
1000    Data
1001    Data::log10() const
1002  {  {
1003    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log10);    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log10);
1004  }  }
1005    
1006  Data  Data
1007  Data::ln() const  Data::log() const
1008  {  {
1009    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log);    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log);
1010  }  }
# Line 859  Data::neg() const Line 1030  Data::neg() const
1030  Data  Data
1031  Data::pos() const  Data::pos() const
1032  {  {
1033    return (*this);    Data result;
1034      // perform a deep copy
1035      result.copy(*this);
1036      return result;
1037  }  }
1038    
1039  Data  Data
# Line 877  Data::sqrt() const Line 1051  Data::sqrt() const
1051  double  double
1052  Data::Lsup() const  Data::Lsup() const
1053  {  {
1054      double localValue, globalValue;
1055    //    //
1056    // set the initial absolute maximum value to zero    // set the initial absolute maximum value to zero
   return algorithm(DataAlgorithmAdapter<AbsMax>(0));  
 }  
1057    
1058  double    AbsMax abs_max_func;
1059  Data::Linf() const    localValue = algorithm(abs_max_func,0);
1060  {  #ifdef PASO_MPI
1061    //    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1062    // set the initial absolute minimum value to max double    return globalValue;
1063    return algorithm(DataAlgorithmAdapter<AbsMin>(numeric_limits<double>::max()));  #else
1064      return localValue;
1065    #endif
1066  }  }
1067    
1068  double  double
1069  Data::sup() const  Data::sup() const
1070  {  {
1071      double localValue, globalValue;
1072    //    //
1073    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1074    return algorithm(DataAlgorithmAdapter<FMax>(numeric_limits<double>::max()*-1));    FMax fmax_func;
1075      localValue = algorithm(fmax_func,numeric_limits<double>::max()*-1);
1076    #ifdef PASO_MPI
1077      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1078      return globalValue;
1079    #else
1080      return localValue;
1081    #endif
1082  }  }
1083    
1084  double  double
1085  Data::inf() const  Data::inf() const
1086  {  {
1087      double localValue, globalValue;
1088    //    //
1089    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1090    return algorithm(DataAlgorithmAdapter<FMin>(numeric_limits<double>::max()));    FMin fmin_func;
1091      localValue = algorithm(fmin_func,numeric_limits<double>::max());
1092    #ifdef PASO_MPI
1093      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD );
1094      return globalValue;
1095    #else
1096      return localValue;
1097    #endif
1098  }  }
1099    
1100    /* TODO */
1101    /* global reduction */
1102  Data  Data
1103  Data::maxval() const  Data::maxval() const
1104  {  {
1105    //    //
1106    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1107    return dp_algorithm(DataAlgorithmAdapter<FMax>(numeric_limits<double>::max()*-1));    FMax fmax_func;
1108      return dp_algorithm(fmax_func,numeric_limits<double>::max()*-1);
1109  }  }
1110    
1111  Data  Data
# Line 919  Data::minval() const Line 1113  Data::minval() const
1113  {  {
1114    //    //
1115    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1116    return dp_algorithm(DataAlgorithmAdapter<FMin>(numeric_limits<double>::max()));    FMin fmin_func;
1117      return dp_algorithm(fmin_func,numeric_limits<double>::max());
1118  }  }
1119    
1120  const boost::python::tuple  Data
1121  Data::mindp() const  Data::swapaxes(const int axis0, const int axis1) const
1122  {  {
1123    Data temp=minval();       int axis0_tmp,axis1_tmp;
1124         DataArrayView::ShapeType s=getDataPointShape();
1125    int numSamples=temp.getNumSamples();       DataArrayView::ShapeType ev_shape;
1126    int numDPPSample=temp.getNumDataPointsPerSample();       // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1127         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1128    int i,j,lowi=0,lowj=0;       int rank=getDataPointRank();
1129    double min=numeric_limits<double>::max();       if (rank<2) {
1130            throw DataException("Error - Data::swapaxes argument must have at least rank 2.");
1131    for (i=0; i<numSamples; i++) {       }
1132      for (j=0; j<numDPPSample; j++) {       if (axis0<0 || axis0>rank-1) {
1133        double next=temp.getDataPoint(i,j)();          throw DataException("Error - Data::swapaxes: axis0 must be between 0 and rank-1=" + rank-1);
1134        if (next<min) {       }
1135          min=next;       if (axis1<0 || axis1>rank-1) {
1136          lowi=i;           throw DataException("Error - Data::swapaxes: axis1 must be between 0 and rank-1=" + rank-1);
1137          lowj=j;       }
1138        }       if (axis0 == axis1) {
1139      }           throw DataException("Error - Data::swapaxes: axis indices must be different.");
1140    }       }
1141         if (axis0 > axis1) {
1142             axis0_tmp=axis1;
1143             axis1_tmp=axis0;
1144         } else {
1145             axis0_tmp=axis0;
1146             axis1_tmp=axis1;
1147         }
1148         for (int i=0; i<rank; i++) {
1149           if (i == axis0_tmp) {
1150              ev_shape.push_back(s[axis1_tmp]);
1151           } else if (i == axis1_tmp) {
1152              ev_shape.push_back(s[axis0_tmp]);
1153           } else {
1154              ev_shape.push_back(s[i]);
1155           }
1156         }
1157         Data ev(0.,ev_shape,getFunctionSpace());
1158         ev.typeMatchRight(*this);
1159         m_data->swapaxes(ev.m_data.get(), axis0_tmp, axis1_tmp);
1160         return ev;
1161    
1162    }
1163    
1164    Data
1165    Data::symmetric() const
1166    {
1167         // check input
1168         DataArrayView::ShapeType s=getDataPointShape();
1169         if (getDataPointRank()==2) {
1170            if(s[0] != s[1])
1171               throw DataException("Error - Data::symmetric can only be calculated for rank 2 object with equal first and second dimension.");
1172         }
1173         else if (getDataPointRank()==4) {
1174            if(!(s[0] == s[2] && s[1] == s[3]))
1175               throw DataException("Error - Data::symmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1176         }
1177         else {
1178            throw DataException("Error - Data::symmetric can only be calculated for rank 2 or 4 object.");
1179         }
1180         Data ev(0.,getDataPointShape(),getFunctionSpace());
1181         ev.typeMatchRight(*this);
1182         m_data->symmetric(ev.m_data.get());
1183         return ev;
1184    }
1185    
1186    Data
1187    Data::nonsymmetric() const
1188    {
1189         // check input
1190         DataArrayView::ShapeType s=getDataPointShape();
1191         if (getDataPointRank()==2) {
1192            if(s[0] != s[1])
1193               throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 object with equal first and second dimension.");
1194            DataArrayView::ShapeType ev_shape;
1195            ev_shape.push_back(s[0]);
1196            ev_shape.push_back(s[1]);
1197            Data ev(0.,ev_shape,getFunctionSpace());
1198            ev.typeMatchRight(*this);
1199            m_data->nonsymmetric(ev.m_data.get());
1200            return ev;
1201         }
1202         else if (getDataPointRank()==4) {
1203            if(!(s[0] == s[2] && s[1] == s[3]))
1204               throw DataException("Error - Data::nonsymmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1205            DataArrayView::ShapeType ev_shape;
1206            ev_shape.push_back(s[0]);
1207            ev_shape.push_back(s[1]);
1208            ev_shape.push_back(s[2]);
1209            ev_shape.push_back(s[3]);
1210            Data ev(0.,ev_shape,getFunctionSpace());
1211            ev.typeMatchRight(*this);
1212            m_data->nonsymmetric(ev.m_data.get());
1213            return ev;
1214         }
1215         else {
1216            throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 or 4 object.");
1217         }
1218    }
1219    
1220    Data
1221    Data::trace(int axis_offset) const
1222    {
1223         DataArrayView::ShapeType s=getDataPointShape();
1224         if (getDataPointRank()==2) {
1225            DataArrayView::ShapeType ev_shape;
1226            Data ev(0.,ev_shape,getFunctionSpace());
1227            ev.typeMatchRight(*this);
1228            m_data->trace(ev.m_data.get(), axis_offset);
1229            return ev;
1230         }
1231         if (getDataPointRank()==3) {
1232            DataArrayView::ShapeType ev_shape;
1233            if (axis_offset==0) {
1234              int s2=s[2];
1235              ev_shape.push_back(s2);
1236            }
1237            else if (axis_offset==1) {
1238              int s0=s[0];
1239              ev_shape.push_back(s0);
1240            }
1241            Data ev(0.,ev_shape,getFunctionSpace());
1242            ev.typeMatchRight(*this);
1243            m_data->trace(ev.m_data.get(), axis_offset);
1244            return ev;
1245         }
1246         if (getDataPointRank()==4) {
1247            DataArrayView::ShapeType ev_shape;
1248            if (axis_offset==0) {
1249              ev_shape.push_back(s[2]);
1250              ev_shape.push_back(s[3]);
1251            }
1252            else if (axis_offset==1) {
1253              ev_shape.push_back(s[0]);
1254              ev_shape.push_back(s[3]);
1255            }
1256        else if (axis_offset==2) {
1257          ev_shape.push_back(s[0]);
1258          ev_shape.push_back(s[1]);
1259        }
1260            Data ev(0.,ev_shape,getFunctionSpace());
1261            ev.typeMatchRight(*this);
1262        m_data->trace(ev.m_data.get(), axis_offset);
1263            return ev;
1264         }
1265         else {
1266            throw DataException("Error - Data::trace can only be calculated for rank 2, 3 or 4 object.");
1267         }
1268    }
1269    
1270    return make_tuple(lowi,lowj);  Data
1271    Data::transpose(int axis_offset) const
1272    {
1273         DataArrayView::ShapeType s=getDataPointShape();
1274         DataArrayView::ShapeType ev_shape;
1275         // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1276         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1277         int rank=getDataPointRank();
1278         if (axis_offset<0 || axis_offset>rank) {
1279            throw DataException("Error - Data::transpose must have 0 <= axis_offset <= rank=" + rank);
1280         }
1281         for (int i=0; i<rank; i++) {
1282           int index = (axis_offset+i)%rank;
1283           ev_shape.push_back(s[index]); // Append to new shape
1284         }
1285         Data ev(0.,ev_shape,getFunctionSpace());
1286         ev.typeMatchRight(*this);
1287         m_data->transpose(ev.m_data.get(), axis_offset);
1288         return ev;
1289  }  }
1290    
1291  Data  Data
1292  Data::length() const  Data::eigenvalues() const
1293    {
1294         // check input
1295         DataArrayView::ShapeType s=getDataPointShape();
1296         if (getDataPointRank()!=2)
1297            throw DataException("Error - Data::eigenvalues can only be calculated for rank 2 object.");
1298         if(s[0] != s[1])
1299            throw DataException("Error - Data::eigenvalues can only be calculated for object with equal first and second dimension.");
1300         // create return
1301         DataArrayView::ShapeType ev_shape(1,s[0]);
1302         Data ev(0.,ev_shape,getFunctionSpace());
1303         ev.typeMatchRight(*this);
1304         m_data->eigenvalues(ev.m_data.get());
1305         return ev;
1306    }
1307    
1308    const boost::python::tuple
1309    Data::eigenvalues_and_eigenvectors(const double tol) const
1310  {  {
1311    return dp_algorithm(DataAlgorithmAdapter<Length>(0));       DataArrayView::ShapeType s=getDataPointShape();
1312         if (getDataPointRank()!=2)
1313            throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for rank 2 object.");
1314         if(s[0] != s[1])
1315            throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for object with equal first and second dimension.");
1316         // create return
1317         DataArrayView::ShapeType ev_shape(1,s[0]);
1318         Data ev(0.,ev_shape,getFunctionSpace());
1319         ev.typeMatchRight(*this);
1320         DataArrayView::ShapeType V_shape(2,s[0]);
1321         Data V(0.,V_shape,getFunctionSpace());
1322         V.typeMatchRight(*this);
1323         m_data->eigenvalues_and_eigenvectors(ev.m_data.get(),V.m_data.get(),tol);
1324         return make_tuple(boost::python::object(ev),boost::python::object(V));
1325  }  }
1326    
1327  Data  const boost::python::tuple
1328  Data::trace() const  Data::minGlobalDataPoint() const
1329  {  {
1330    return dp_algorithm(DataAlgorithmAdapter<Trace>(0));    // NB: calc_minGlobalDataPoint( had to be split off from minGlobalDataPoint( as boost::make_tuple causes an
1331      // abort (for unknown reasons) if there are openmp directives with it in the
1332      // surrounding function
1333    
1334      int DataPointNo;
1335      int ProcNo;
1336      calc_minGlobalDataPoint(ProcNo,DataPointNo);
1337      return make_tuple(ProcNo,DataPointNo);
1338  }  }
1339    
1340  Data  void
1341  Data::transpose(int axis) const  Data::calc_minGlobalDataPoint(int& ProcNo,
1342                            int& DataPointNo) const
1343  {  {
1344    // not implemented    int i,j;
1345    throw DataException("Error - Data::transpose not implemented yet.");    int lowi=0,lowj=0;
1346    return Data();    double min=numeric_limits<double>::max();
1347    
1348      Data temp=minval();
1349    
1350      int numSamples=temp.getNumSamples();
1351      int numDPPSample=temp.getNumDataPointsPerSample();
1352    
1353      double next,local_min;
1354      int local_lowi,local_lowj;
1355    
1356      #pragma omp parallel private(next,local_min,local_lowi,local_lowj)
1357      {
1358        local_min=min;
1359        #pragma omp for private(i,j) schedule(static)
1360        for (i=0; i<numSamples; i++) {
1361          for (j=0; j<numDPPSample; j++) {
1362            next=temp.getDataPoint(i,j)();
1363            if (next<local_min) {
1364              local_min=next;
1365              local_lowi=i;
1366              local_lowj=j;
1367            }
1368          }
1369        }
1370        #pragma omp critical
1371        if (local_min<min) {
1372          min=local_min;
1373          lowi=local_lowi;
1374          lowj=local_lowj;
1375        }
1376      }
1377    
1378    #ifdef PASO_MPI
1379        // determine the processor on which the minimum occurs
1380        next = temp.getDataPoint(lowi,lowj)();
1381        int lowProc = 0;
1382        double *globalMins = new double[get_MPISize()+1];
1383        int error = MPI_Gather ( &next, 1, MPI_DOUBLE, globalMins, 1, MPI_DOUBLE, 0, get_MPIComm() );
1384    
1385        if( get_MPIRank()==0 ){
1386            next = globalMins[lowProc];
1387            for( i=1; i<get_MPISize(); i++ )
1388                if( next>globalMins[i] ){
1389                    lowProc = i;
1390                    next = globalMins[i];
1391                }
1392        }
1393        MPI_Bcast( &lowProc, 1, MPI_DOUBLE, 0, get_MPIComm() );
1394    
1395        delete [] globalMins;
1396        ProcNo = lowProc;
1397    #else
1398        ProcNo = 0;
1399    #endif
1400      DataPointNo = lowj + lowi * numDPPSample;
1401  }  }
1402    
1403  void  void
1404  Data::saveDX(std::string fileName) const  Data::saveDX(std::string fileName) const
1405  {  {
1406    getDomain().saveDX(fileName,*this);    boost::python::dict args;
1407      args["data"]=boost::python::object(this);
1408      getDomain().saveDX(fileName,args);
1409    return;    return;
1410  }  }
1411    
1412  void  void
1413  Data::saveVTK(std::string fileName) const  Data::saveVTK(std::string fileName) const
1414  {  {
1415    getDomain().saveVTK(fileName,*this);    boost::python::dict args;
1416      args["data"]=boost::python::object(this);
1417      getDomain().saveVTK(fileName,args);
1418    return;    return;
1419  }  }
1420    
1421  Data&  Data&
1422  Data::operator+=(const Data& right)  Data::operator+=(const Data& right)
1423  {  {
1424      if (isProtected()) {
1425            throw DataException("Error - attempt to update protected Data object.");
1426      }
1427    binaryOp(right,plus<double>());    binaryOp(right,plus<double>());
1428    return (*this);    return (*this);
1429  }  }
# Line 991  Data::operator+=(const Data& right) Line 1431  Data::operator+=(const Data& right)
1431  Data&  Data&
1432  Data::operator+=(const boost::python::object& right)  Data::operator+=(const boost::python::object& right)
1433  {  {
1434    binaryOp(right,plus<double>());    Data tmp(right,getFunctionSpace(),false);
1435      binaryOp(tmp,plus<double>());
1436      return (*this);
1437    }
1438    Data&
1439    Data::operator=(const Data& other)
1440    {
1441      copy(other);
1442    return (*this);    return (*this);
1443  }  }
1444    
1445  Data&  Data&
1446  Data::operator-=(const Data& right)  Data::operator-=(const Data& right)
1447  {  {
1448      if (isProtected()) {
1449            throw DataException("Error - attempt to update protected Data object.");
1450      }
1451    binaryOp(right,minus<double>());    binaryOp(right,minus<double>());
1452    return (*this);    return (*this);
1453  }  }
# Line 1005  Data::operator-=(const Data& right) Line 1455  Data::operator-=(const Data& right)
1455  Data&  Data&
1456  Data::operator-=(const boost::python::object& right)  Data::operator-=(const boost::python::object& right)
1457  {  {
1458    binaryOp(right,minus<double>());    Data tmp(right,getFunctionSpace(),false);
1459      binaryOp(tmp,minus<double>());
1460    return (*this);    return (*this);
1461  }  }
1462    
1463  Data&  Data&
1464  Data::operator*=(const Data& right)  Data::operator*=(const Data& right)
1465  {  {
1466      if (isProtected()) {
1467            throw DataException("Error - attempt to update protected Data object.");
1468      }
1469    binaryOp(right,multiplies<double>());    binaryOp(right,multiplies<double>());
1470    return (*this);    return (*this);
1471  }  }
# Line 1019  Data::operator*=(const Data& right) Line 1473  Data::operator*=(const Data& right)
1473  Data&  Data&
1474  Data::operator*=(const boost::python::object& right)  Data::operator*=(const boost::python::object& right)
1475  {  {
1476    binaryOp(right,multiplies<double>());    Data tmp(right,getFunctionSpace(),false);
1477      binaryOp(tmp,multiplies<double>());
1478    return (*this);    return (*this);
1479  }  }
1480    
1481  Data&  Data&
1482  Data::operator/=(const Data& right)  Data::operator/=(const Data& right)
1483  {  {
1484      if (isProtected()) {
1485            throw DataException("Error - attempt to update protected Data object.");
1486      }
1487    binaryOp(right,divides<double>());    binaryOp(right,divides<double>());
1488    return (*this);    return (*this);
1489  }  }
# Line 1033  Data::operator/=(const Data& right) Line 1491  Data::operator/=(const Data& right)
1491  Data&  Data&
1492  Data::operator/=(const boost::python::object& right)  Data::operator/=(const boost::python::object& right)
1493  {  {
1494    binaryOp(right,divides<double>());    Data tmp(right,getFunctionSpace(),false);
1495      binaryOp(tmp,divides<double>());
1496    return (*this);    return (*this);
1497  }  }
1498    
1499  Data  Data
1500    Data::rpowO(const boost::python::object& left) const
1501    {
1502      Data left_d(left,*this);
1503      return left_d.powD(*this);
1504    }
1505    
1506    Data
1507  Data::powO(const boost::python::object& right) const  Data::powO(const boost::python::object& right) const
1508  {  {
1509    Data result;    Data tmp(right,getFunctionSpace(),false);
1510    result.copy(*this);    return powD(tmp);
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1511  }  }
1512    
1513  Data  Data
1514  Data::powD(const Data& right) const  Data::powD(const Data& right) const
1515  {  {
1516    Data result;    Data result;
1517    result.copy(*this);    if (getDataPointRank()<right.getDataPointRank()) {
1518    result.binaryOp(right,(Data::BinaryDFunPtr)::pow);       result.copy(right);
1519         result.binaryOp(*this,escript::rpow);
1520      } else {
1521         result.copy(*this);
1522         result.binaryOp(right,(Data::BinaryDFunPtr)::pow);
1523      }
1524    return result;    return result;
1525  }  }
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, plus<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, minus<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, multiplies<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 Data& right)  escript::operator/(const Data& left, const Data& right)
1556  {  {
1557    Data result;    return C_TensorBinaryOperation(left, right, divides<double>());
   //  
   // 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 Data& left, const boost::python::object& right)  escript::operator/(const Data& left, const boost::python::object& right)
1588  {  {
1589    //    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;  
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  //  //
1617  // NOTE: It is essential to specify the namepsace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1618  Data  Data
1619  escript::operator/(const boost::python::object& left, const Data& right)  escript::operator/(const boost::python::object& left, const Data& right)
1620  {  {
1621    //    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;  
1622  }  }
1623    
1624  //  //
 // NOTE: It is essential to specify the namepsace this operator belongs to  
1625  //bool escript::operator==(const Data& left, const Data& right)  //bool escript::operator==(const Data& left, const Data& right)
1626  //{  //{
1627  //  /*  //  /*
# Line 1269  escript::operator/(const boost::python:: Line 1666  escript::operator/(const boost::python::
1666  //  return ret;  //  return ret;
1667  //}  //}
1668    
1669    /* TODO */
1670    /* global reduction */
1671  Data  Data
1672  Data::getItem(const boost::python::object& key) const  Data::getItem(const boost::python::object& key) const
1673  {  {
1674    const DataArrayView& view=getPointDataView();    const DataArrayView& view=getPointDataView();
1675    
# Line 1283  Data::getItem(const boost::python::objec Line 1682  Data::getItem(const boost::python::objec
1682    return getSlice(slice_region);    return getSlice(slice_region);
1683  }  }
1684    
1685    /* TODO */
1686    /* global reduction */
1687  Data  Data
1688  Data::getSlice(const DataArrayView::RegionType& region) const  Data::getSlice(const DataArrayView::RegionType& region) const
1689  {  {
1690    return Data(*this,region);    return Data(*this,region);
1691  }  }
1692    
1693    /* TODO */
1694    /* global reduction */
1695  void  void
1696  Data::setItemO(const boost::python::object& key,  Data::setItemO(const boost::python::object& key,
1697                 const boost::python::object& value)                 const boost::python::object& value)
# Line 1302  Data::setItemD(const boost::python::obje Line 1705  Data::setItemD(const boost::python::obje
1705                 const Data& value)                 const Data& value)
1706  {  {
1707    const DataArrayView& view=getPointDataView();    const DataArrayView& view=getPointDataView();
1708    
1709    DataArrayView::RegionType slice_region=view.getSliceRegion(key);    DataArrayView::RegionType slice_region=view.getSliceRegion(key);
1710    if (slice_region.size()!=view.getRank()) {    if (slice_region.size()!=view.getRank()) {
1711      throw DataException("Error - slice size does not match Data rank.");      throw DataException("Error - slice size does not match Data rank.");
# Line 1317  void Line 1721  void
1721  Data::setSlice(const Data& value,  Data::setSlice(const Data& value,
1722                 const DataArrayView::RegionType& region)                 const DataArrayView::RegionType& region)
1723  {  {
1724      if (isProtected()) {
1725            throw DataException("Error - attempt to update protected Data object.");
1726      }
1727    Data tempValue(value);    Data tempValue(value);
1728    typeMatchLeft(tempValue);    typeMatchLeft(tempValue);
1729    typeMatchRight(tempValue);    typeMatchRight(tempValue);
# Line 1352  Data::typeMatchRight(const Data& right) Line 1759  Data::typeMatchRight(const Data& right)
1759  }  }
1760    
1761  void  void
1762    Data::setTaggedValueByName(std::string name,
1763                               const boost::python::object& value)
1764    {
1765         if (getFunctionSpace().getDomain().isValidTagName(name)) {
1766            int tagKey=getFunctionSpace().getDomain().getTag(name);
1767            setTaggedValue(tagKey,value);
1768         }
1769    }
1770    void
1771  Data::setTaggedValue(int tagKey,  Data::setTaggedValue(int tagKey,
1772                       const boost::python::object& value)                       const boost::python::object& value)
1773  {  {
1774      if (isProtected()) {
1775            throw DataException("Error - attempt to update protected Data object.");
1776      }
1777    //    //
1778    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
1779    tag();    tag();
# Line 1363  Data::setTaggedValue(int tagKey, Line 1782  Data::setTaggedValue(int tagKey,
1782      throw DataException("Error - DataTagged conversion failed!!");      throw DataException("Error - DataTagged conversion failed!!");
1783    }    }
1784    
1785    //    numeric::array asNumArray(value);
1786    // Construct DataArray from boost::python::object input value  
1787    DataArray valueDataArray(value);  
1788      // extract the shape of the numarray
1789      DataArrayView::ShapeType tempShape;
1790      for (int i=0; i < asNumArray.getrank(); i++) {
1791        tempShape.push_back(extract<int>(asNumArray.getshape()[i]));
1792      }
1793    
1794      // get the space for the data vector
1795      int len = DataArrayView::noValues(tempShape);
1796      DataVector temp_data(len, 0.0, len);
1797      DataArrayView temp_dataView(temp_data, tempShape);
1798      temp_dataView.copy(asNumArray);
1799    
1800    //    //
1801    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
1802    m_data->setTaggedValue(tagKey,valueDataArray.getView());    m_data->setTaggedValue(tagKey,temp_dataView);
1803  }  }
1804    
1805  void  void
1806  Data::setTaggedValueFromCPP(int tagKey,  Data::setTaggedValueFromCPP(int tagKey,
1807                              const DataArrayView& value)                              const DataArrayView& value)
1808  {  {
1809      if (isProtected()) {
1810            throw DataException("Error - attempt to update protected Data object.");
1811      }
1812    //    //
1813    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
1814    tag();    tag();
# Line 1383  Data::setTaggedValueFromCPP(int tagKey, Line 1816  Data::setTaggedValueFromCPP(int tagKey,
1816    if (!isTagged()) {    if (!isTagged()) {
1817      throw DataException("Error - DataTagged conversion failed!!");      throw DataException("Error - DataTagged conversion failed!!");
1818    }    }
1819                                                                                                                  
1820    //    //
1821    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
1822    m_data->setTaggedValue(tagKey,value);    m_data->setTaggedValue(tagKey,value);
1823  }  }
1824    
1825  void  int
1826  Data::setRefValue(int ref,  Data::getTagNumber(int dpno)
                   const boost::python::numeric::array& value)  
1827  {  {
1828    //    return m_data->getTagNumber(dpno);
   // 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)  
 {  
   //  
   // 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.");  
   }  
   
1829  }  }
1830    
1831  void  void
# Line 1472  Data::archiveData(const std::string file Line 1853  Data::archiveData(const std::string file
1853      dataType = 3;      dataType = 3;
1854      cout << "\tdataType: DataExpanded" << endl;      cout << "\tdataType: DataExpanded" << endl;
1855    }    }
1856    
1857    if (dataType == -1) {    if (dataType == -1) {
1858      throw DataException("archiveData Error: undefined dataType");      throw DataException("archiveData Error: undefined dataType");
1859    }    }
# Line 1485  Data::archiveData(const std::string file Line 1867  Data::archiveData(const std::string file
1867    int dataPointSize = getDataPointSize();    int dataPointSize = getDataPointSize();
1868    int dataLength = getLength();    int dataLength = getLength();
1869    DataArrayView::ShapeType dataPointShape = getDataPointShape();    DataArrayView::ShapeType dataPointShape = getDataPointShape();
1870    int referenceNumbers[noSamples];    vector<int> referenceNumbers(noSamples);
1871    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
1872      referenceNumbers[sampleNo] = getFunctionSpace().getReferenceNoFromSampleNo(sampleNo);      referenceNumbers[sampleNo] = getFunctionSpace().getReferenceIDOfSample(sampleNo);
1873    }    }
1874    int tagNumbers[noSamples];    vector<int> tagNumbers(noSamples);
1875    if (isTagged()) {    if (isTagged()) {
1876      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
1877        tagNumbers[sampleNo] = getFunctionSpace().getTagFromSampleNo(sampleNo);        tagNumbers[sampleNo] = getFunctionSpace().getTagFromSampleNo(sampleNo);
# Line 1511  Data::archiveData(const std::string file Line 1893  Data::archiveData(const std::string file
1893    cout << ">" << endl;    cout << ">" << endl;
1894    
1895    //    //
1896    // Write common data items to archive file    // Open archive file
1897    ofstream archiveFile;    ofstream archiveFile;
1898    archiveFile.open(fileName.data(), ios::out);    archiveFile.open(fileName.data(), ios::out);
1899    
# Line 1519  Data::archiveData(const std::string file Line 1901  Data::archiveData(const std::string file
1901      throw DataException("archiveData Error: problem opening archive file");      throw DataException("archiveData Error: problem opening archive file");
1902    }    }
1903    
1904      //
1905      // Write common data items to archive file
1906    archiveFile.write(reinterpret_cast<char *>(&dataType),sizeof(int));    archiveFile.write(reinterpret_cast<char *>(&dataType),sizeof(int));
1907    archiveFile.write(reinterpret_cast<char *>(&noSamples),sizeof(int));    archiveFile.write(reinterpret_cast<char *>(&noSamples),sizeof(int));
1908    archiveFile.write(reinterpret_cast<char *>(&noDPPSample),sizeof(int));    archiveFile.write(reinterpret_cast<char *>(&noDPPSample),sizeof(int));
# Line 1542  Data::archiveData(const std::string file Line 1926  Data::archiveData(const std::string file
1926      throw DataException("archiveData Error: problem writing to archive file");      throw DataException("archiveData Error: problem writing to archive file");
1927    }    }
1928    
   archiveFile.close();  
   
   if (!archiveFile.good()) {  
     throw DataException("archiveData Error: problem closing archive file");  
   }  
   
1929    //    //
1930    // Collect and archive underlying data values for each Data type    // Archive underlying data values for each Data type
1931      int noValues;
1932    switch (dataType) {    switch (dataType) {
1933      case 0:      case 0:
1934        // DataEmpty        // DataEmpty
1935          noValues = 0;
1936          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1937          cout << "\tnoValues: " << noValues << endl;
1938        break;        break;
1939      case 1:      case 1:
1940        // DataConstant        // DataConstant
1941          noValues = m_data->getLength();
1942          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1943          cout << "\tnoValues: " << noValues << endl;
1944          if (m_data->archiveData(archiveFile,noValues)) {
1945            throw DataException("archiveData Error: problem writing data to archive file");
1946          }
1947        break;        break;
1948      case 2:      case 2:
1949        // DataTagged        // DataTagged
1950          noValues = m_data->getLength();
1951          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1952          cout << "\tnoValues: " << noValues << endl;
1953          if (m_data->archiveData(archiveFile,noValues)) {
1954            throw DataException("archiveData Error: problem writing data to archive file");
1955          }
1956        break;        break;
1957      case 3:      case 3:
1958        // DataExpanded        // DataExpanded
1959          noValues = m_data->getLength();
1960          archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));
1961          cout << "\tnoValues: " << noValues << endl;
1962          if (m_data->archiveData(archiveFile,noValues)) {
1963            throw DataException("archiveData Error: problem writing data to archive file");
1964          }
1965        break;        break;
1966    }    }
1967    
1968      if (!archiveFile.good()) {
1969        throw DataException("archiveData Error: problem writing data to archive file");
1970      }
1971    
1972      //
1973      // Close archive file
1974      archiveFile.close();
1975    
1976      if (!archiveFile.good()) {
1977        throw DataException("archiveData Error: problem closing archive file");
1978      }
1979    
1980  }  }
1981    
1982  void  void
# Line 1590  Data::extractData(const std::string file Line 2002  Data::extractData(const std::string file
2002    int flatShape[4];    int flatShape[4];
2003    
2004    //    //
2005    // Open the archive file and read common data items    // Open the archive file
2006    ifstream archiveFile;    ifstream archiveFile;
2007    archiveFile.open(fileName.data(), ios::in);    archiveFile.open(fileName.data(), ios::in);
2008    
# Line 1598  Data::extractData(const std::string file Line 2010  Data::extractData(const std::string file
2010      throw DataException("extractData Error: problem opening archive file");      throw DataException("extractData Error: problem opening archive file");
2011    }    }
2012    
2013      //
2014      // Read common data items from archive file
2015    archiveFile.read(reinterpret_cast<char *>(&dataType),sizeof(int));    archiveFile.read(reinterpret_cast<char *>(&dataType),sizeof(int));
2016    archiveFile.read(reinterpret_cast<char *>(&noSamples),sizeof(int));    archiveFile.read(reinterpret_cast<char *>(&noSamples),sizeof(int));
2017    archiveFile.read(reinterpret_cast<char *>(&noDPPSample),sizeof(int));    archiveFile.read(reinterpret_cast<char *>(&noDPPSample),sizeof(int));
# Line 1611  Data::extractData(const std::string file Line 2025  Data::extractData(const std::string file
2025        dataPointShape.push_back(flatShape[dim]);        dataPointShape.push_back(flatShape[dim]);
2026      }      }
2027    }    }
2028    int referenceNumbers[noSamples];    vector<int> referenceNumbers(noSamples);
2029    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
2030      archiveFile.read(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));      archiveFile.read(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));
2031    }    }
2032    int tagNumbers[noSamples];    vector<int> tagNumbers(noSamples);
2033    if (dataType==2) {    if (dataType==2) {
2034      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
2035        archiveFile.read(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));        archiveFile.read(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));
# Line 1626  Data::extractData(const std::string file Line 2040  Data::extractData(const std::string file
2040      throw DataException("extractData Error: problem reading from archive file");      throw DataException("extractData Error: problem reading from archive file");
2041    }    }
2042    
2043    archiveFile.close();    //
2044      // Verify the values just read from the archive file
   if (!archiveFile.good()) {  
     throw DataException("extractData Error: problem closing archive file");  
   }  
   
2045    switch (dataType) {    switch (dataType) {
2046      case 0:      case 0:
2047        cout << "\tdataType: DataEmpty" << endl;        cout << "\tdataType: DataEmpty" << endl;
# Line 1668  Data::extractData(const std::string file Line 2078  Data::extractData(const std::string file
2078      throw DataException("extractData Error: incompatible FunctionSpace");      throw DataException("extractData Error: incompatible FunctionSpace");
2079    }    }
2080    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {
2081      if (referenceNumbers[sampleNo] != fspace.getReferenceNoFromSampleNo(sampleNo)) {      if (referenceNumbers[sampleNo] != fspace.getReferenceIDOfSample(sampleNo)) {
2082        throw DataException("extractData Error: incompatible FunctionSpace");        throw DataException("extractData Error: incompatible FunctionSpace");
2083      }      }
2084    }    }
# Line 1686  Data::extractData(const std::string file Line 2096  Data::extractData(const std::string file
2096    
2097    //    //
2098    // Load this DataVector with the appropriate values    // Load this DataVector with the appropriate values
2099      int noValues;
2100      archiveFile.read(reinterpret_cast<char *>(&noValues),sizeof(int));
2101      cout << "\tnoValues: " << noValues << endl;
2102    switch (dataType) {    switch (dataType) {
2103      case 0:      case 0:
2104        // DataEmpty        // DataEmpty
2105          if (noValues != 0) {
2106            throw DataException("extractData Error: problem reading data from archive file");
2107          }
2108        break;        break;
2109      case 1:      case 1:
2110        // DataConstant        // DataConstant
2111          if (dataVec.extractData(archiveFile,noValues)) {
2112            throw DataException("extractData Error: problem reading data from archive file");
2113          }
2114        break;        break;
2115      case 2:      case 2:
2116        // DataTagged        // DataTagged
2117          if (dataVec.extractData(archiveFile,noValues)) {
2118            throw DataException("extractData Error: problem reading data from archive file");
2119          }
2120        break;        break;
2121      case 3:      case 3:
2122        // DataExpanded        // DataExpanded
2123          if (dataVec.extractData(archiveFile,noValues)) {
2124            throw DataException("extractData Error: problem reading data from archive file");
2125          }
2126        break;        break;
2127    }    }
2128    
2129      if (!archiveFile.good()) {
2130        throw DataException("extractData Error: problem reading from archive file");
2131      }
2132    
2133      //
2134      // Close archive file
2135      archiveFile.close();
2136    
2137      if (!archiveFile.good()) {
2138        throw DataException("extractData Error: problem closing archive file");
2139      }
2140    
2141    //    //
2142    // Construct an appropriate Data object    // Construct an appropriate Data object
2143    DataAbstract* tempData;    DataAbstract* tempData;
# Line 1724  Data::extractData(const std::string file Line 2161  Data::extractData(const std::string file
2161    }    }
2162    shared_ptr<DataAbstract> temp_data(tempData);    shared_ptr<DataAbstract> temp_data(tempData);
2163    m_data=temp_data;    m_data=temp_data;
   
2164  }  }
2165    
2166  ostream& escript::operator<<(ostream& o, const Data& data)  ostream& escript::operator<<(ostream& o, const Data& data)
# Line 1732  ostream& escript::operator<<(ostream& o, Line 2168  ostream& escript::operator<<(ostream& o,
2168    o << data.toString();    o << data.toString();
2169    return o;    return o;
2170  }  }
2171    
2172    Data
2173    escript::C_GeneralTensorProduct(Data& arg_0,
2174                         Data& arg_1,
2175                         int axis_offset,
2176                         int transpose)
2177    {
2178      // General tensor product: res(SL x SR) = arg_0(SL x SM) * arg_1(SM x SR)
2179      // SM is the product of the last axis_offset entries in arg_0.getShape().
2180    
2181      // Interpolate if necessary and find an appropriate function space
2182      Data arg_0_Z, arg_1_Z;
2183      if (arg_0.getFunctionSpace()!=arg_1.getFunctionSpace()) {
2184        if (arg_0.probeInterpolation(arg_1.getFunctionSpace())) {
2185          arg_0_Z = arg_0.interpolate(arg_1.getFunctionSpace());
2186          arg_1_Z = Data(arg_1);
2187        }
2188        else if (arg_1.probeInterpolation(arg_0.getFunctionSpace())) {
2189          arg_1_Z=arg_1.interpolate(arg_0.getFunctionSpace());
2190          arg_0_Z =Data(arg_0);
2191        }
2192        else {
2193          throw DataException("Error - C_GeneralTensorProduct: arguments have incompatible function spaces.");
2194        }
2195      } else {
2196          arg_0_Z = Data(arg_0);
2197          arg_1_Z = Data(arg_1);
2198      }
2199      // Get rank and shape of inputs
2200      int rank0 = arg_0_Z.getDataPointRank();
2201      int rank1 = arg_1_Z.getDataPointRank();
2202      DataArrayView::ShapeType shape0 = arg_0_Z.getDataPointShape();
2203      DataArrayView::ShapeType shape1 = arg_1_Z.getDataPointShape();
2204    
2205      // Prepare for the loops of the product and verify compatibility of shapes
2206      int start0=0, start1=0;
2207      if (transpose == 0)       {}
2208      else if (transpose == 1)  { start0 = axis_offset; }
2209      else if (transpose == 2)  { start1 = rank1-axis_offset; }
2210      else              { throw DataException("C_GeneralTensorProduct: Error - transpose should be 0, 1 or 2"); }
2211    
2212      // Adjust the shapes for transpose
2213      DataArrayView::ShapeType tmpShape0;
2214      DataArrayView::ShapeType tmpShape1;
2215      for (int i=0; i<rank0; i++)   { tmpShape0.push_back( shape0[(i+start0)%rank0] ); }
2216      for (int i=0; i<rank1; i++)   { tmpShape1.push_back( shape1[(i+start1)%rank1] ); }
2217    
2218    #if 0
2219      // For debugging: show shape after transpose
2220      char tmp[100];
2221      std::string shapeStr;
2222      shapeStr = "(";
2223      for (int i=0; i<rank0; i++)   { sprintf(tmp, "%d,", tmpShape0[i]); shapeStr += tmp; }
2224      shapeStr += ")";
2225      cout << "C_GeneralTensorProduct: Shape of arg0 is " << shapeStr << endl;
2226      shapeStr = "(";
2227      for (int i=0; i<rank1; i++)   { sprintf(tmp, "%d,", tmpShape1[i]); shapeStr += tmp; }
2228      shapeStr += ")";
2229      cout << "C_GeneralTensorProduct: Shape of arg1 is " << shapeStr << endl;
2230    #endif
2231    
2232      // Prepare for the loops of the product
2233      int SL=1, SM=1, SR=1;
2234      for (int i=0; i<rank0-axis_offset; i++)   {
2235        SL *= tmpShape0[i];
2236      }
2237      for (int i=rank0-axis_offset; i<rank0; i++)   {
2238        if (tmpShape0[i] != tmpShape1[i-(rank0-axis_offset)]) {
2239          throw DataException("C_GeneralTensorProduct: Error - incompatible shapes");
2240        }
2241        SM *= tmpShape0[i];
2242      }
2243      for (int i=axis_offset; i<rank1; i++)     {
2244        SR *= tmpShape1[i];
2245      }
2246    
2247      // Define the shape of the output
2248      DataArrayView::ShapeType shape2;
2249      for (int i=0; i<rank0-axis_offset; i++) { shape2.push_back(tmpShape0[i]); } // First part of arg_0_Z
2250      for (int i=axis_offset; i<rank1; i++)   { shape2.push_back(tmpShape1[i]); } // Last part of arg_1_Z
2251    
2252      // Declare output Data object
2253      Data res;
2254    
2255      if      (arg_0_Z.isConstant()   && arg_1_Z.isConstant()) {
2256        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataConstant output
2257        double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[0]);
2258        double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[0]);
2259        double *ptr_2 = &((res.getPointDataView().getData())[0]);
2260        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2261      }
2262      else if (arg_0_Z.isConstant()   && arg_1_Z.isTagged()) {
2263    
2264        // Prepare the DataConstant input
2265        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2266        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2267    
2268        // Borrow DataTagged input from Data object
2269        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2270        if (tmp_1==0) { throw DataException("GTP_1 Programming error - casting to DataTagged."); }
2271    
2272        // Prepare a DataTagged output 2
2273        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataTagged output
2274        res.tag();
2275        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2276        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2277    
2278        // Prepare offset into DataConstant
2279        int offset_0 = tmp_0->getPointOffset(0,0);
2280        double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2281        // Get the views
2282        DataArrayView view_1 = tmp_1->getDefaultValue();
2283        DataArrayView view_2 = tmp_2->getDefaultValue();
2284        // Get the pointers to the actual data
2285        double *ptr_1 = &((view_1.getData())[0]);
2286        double *ptr_2 = &((view_2.getData())[0]);
2287        // Compute an MVP for the default
2288        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2289        // Compute an MVP for each tag
2290        const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2291        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2292        for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2293          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2294          DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2295          DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2296          double *ptr_1 = &view_1.getData(0);
2297          double *ptr_2 = &view_2.getData(0);
2298          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2299        }
2300    
2301      }
2302      else if (arg_0_Z.isConstant()   && arg_1_Z.isExpanded()) {
2303    
2304        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2305        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2306        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2307        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2308        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2309        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2310        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2311        int sampleNo_1,dataPointNo_1;
2312        int numSamples_1 = arg_1_Z.getNumSamples();
2313        int numDataPointsPerSample_1 = arg_1_Z.getNumDataPointsPerSample();
2314        int offset_0 = tmp_0->getPointOffset(0,0);
2315        #pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)
2316        for (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {
2317          for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {
2318            int offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);
2319            int offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);
2320            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2321            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2322            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2323            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2324          }
2325        }
2326    
2327      }
2328      else if (arg_0_Z.isTagged()     && arg_1_Z.isConstant()) {
2329    
2330        // Borrow DataTagged input from Data object
2331        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2332        if (tmp_0==0) { throw DataException("GTP_0 Programming error - casting to DataTagged."); }
2333    
2334        // Prepare the DataConstant input
2335        DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2336        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2337    
2338        // Prepare a DataTagged output 2
2339        res = Data(0.0, shape2, arg_0_Z.getFunctionSpace());    // DataTagged output
2340        res.tag();
2341        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2342        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2343    
2344        // Prepare offset into DataConstant
2345        int offset_1 = tmp_1->getPointOffset(0,0);
2346        double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2347        // Get the views
2348        DataArrayView view_0 = tmp_0->getDefaultValue();
2349        DataArrayView view_2 = tmp_2->getDefaultValue();
2350        // Get the pointers to the actual data
2351        double *ptr_0 = &((view_0.getData())[0]);
2352        double *ptr_2 = &((view_2.getData())[0]);
2353        // Compute an MVP for the default
2354        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2355        // Compute an MVP for each tag
2356        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2357        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2358        for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2359          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2360          DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2361          DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2362          double *ptr_0 = &view_0.getData(0);
2363          double *ptr_2 = &view_2.getData(0);
2364          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2365        }
2366    
2367      }
2368      else if (arg_0_Z.isTagged()     && arg_1_Z.isTagged()) {
2369    
2370        // Borrow DataTagged input from Data object
2371        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2372        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2373    
2374        // Borrow DataTagged input from Data object
2375        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2376        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2377    
2378        // Prepare a DataTagged output 2
2379        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());
2380        res.tag();  // DataTagged output
2381        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2382        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2383    
2384        // Get the views
2385        DataArrayView view_0 = tmp_0->getDefaultValue();
2386        DataArrayView view_1 = tmp_1->getDefaultValue();
2387        DataArrayView view_2 = tmp_2->getDefaultValue();
2388        // Get the pointers to the actual data
2389        double *ptr_0 = &((view_0.getData())[0]);
2390        double *ptr_1 = &((view_1.getData())[0]);
2391        double *ptr_2 = &((view_2.getData())[0]);
2392        // Compute an MVP for the default
2393        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2394        // Merge the tags
2395        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2396        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2397        const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2398        for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2399          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue()); // use tmp_2 to get correct shape
2400        }
2401        for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2402          tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2403        }
2404        // Compute an MVP for each tag
2405        const DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();
2406        for (i=lookup_2.begin();i!=lookup_2.end();i++) {
2407          DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2408          DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2409          DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2410          double *ptr_0 = &view_0.getData(0);
2411          double *ptr_1 = &view_1.getData(0);
2412          double *ptr_2 = &view_2.getData(0);
2413          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2414        }
2415    
2416      }
2417      else if (arg_0_Z.isTagged()     && arg_1_Z.isExpanded()) {
2418    
2419        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2420        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2421        DataTagged*   tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2422        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2423        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2424        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2425        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2426        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2427        int sampleNo_0,dataPointNo_0;
2428        int numSamples_0 = arg_0_Z.getNumSamples();
2429        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2430        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2431        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2432          int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0
2433          double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2434          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2435            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2436            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2437            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2438            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2439            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2440          }
2441        }
2442    
2443      }
2444      else if (arg_0_Z.isExpanded()   && arg_1_Z.isConstant()) {
2445    
2446        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2447        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2448        DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2449        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2450        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2451        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2452        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2453        int sampleNo_0,dataPointNo_0;
2454        int numSamples_0 = arg_0_Z.getNumSamples();
2455        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2456        int offset_1 = tmp_1->getPointOffset(0,0);
2457        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2458        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2459          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2460            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2461            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2462            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2463            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2464            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2465            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2466          }
2467        }
2468    
2469    
2470      }
2471      else if (arg_0_Z.isExpanded()   && arg_1_Z.isTagged()) {
2472    
2473        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2474        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2475        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2476        DataTagged*   tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2477        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2478        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2479        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2480        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2481        int sampleNo_0,dataPointNo_0;
2482        int numSamples_0 = arg_0_Z.getNumSamples();
2483        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2484        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2485        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2486          int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);
2487          double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2488          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2489            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2490            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2491            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2492            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2493            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2494          }
2495        }
2496    
2497      }
2498      else if (arg_0_Z.isExpanded()   && arg_1_Z.isExpanded()) {
2499    
2500        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2501        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2502        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2503        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2504        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2505        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2506        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2507        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2508        int sampleNo_0,dataPointNo_0;
2509        int numSamples_0 = arg_0_Z.getNumSamples();
2510        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2511        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2512        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2513          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2514            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2515            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2516            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2517            double *ptr_0 = &((arg_0_Z.getPointDataView().getData())[offset_0]);
2518            double *ptr_1 = &((arg_1_Z.getPointDataView().getData())[offset_1]);
2519            double *ptr_2 = &((res.getPointDataView().getData())[offset_2]);
2520            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2521          }
2522        }
2523    
2524      }
2525      else {
2526        throw DataException("Error - C_GeneralTensorProduct: unknown combination of inputs");
2527      }
2528    
2529      return res;
2530    }
2531    
2532    DataAbstract*
2533    Data::borrowData() const
2534    {
2535      return m_data.get();
2536    }
2537    
2538    /* Member functions specific to the MPI implementation */
2539    
2540    void
2541    Data::print()
2542    {
2543      int i,j;
2544    
2545      printf( "Data is %dX%d\n", getNumSamples(), getNumDataPointsPerSample() );
2546      for( i=0; i<getNumSamples(); i++ )
2547      {
2548        printf( "[%6d]", i );
2549        for( j=0; j<getNumDataPointsPerSample(); j++ )
2550          printf( "\t%10.7g", (getSampleData(i))[j] );
2551        printf( "\n" );
2552      }
2553    }
2554    void
2555    Data::dump(const std::string fileName) const
2556    {
2557      try
2558         {
2559            return m_data->dump(fileName);
2560         }
2561         catch (exception& e)
2562         {
2563            cout << e.what() << endl;
2564         }
2565    }
2566    
2567    int
2568    Data::get_MPISize() const
2569    {
2570        int error, size;
2571    #ifdef PASO_MPI
2572        error = MPI_Comm_size( get_MPIComm(), &size );
2573    #else
2574        size = 1;
2575    #endif
2576        return size;
2577    }
2578    
2579    int
2580    Data::get_MPIRank() const
2581    {
2582        int error, rank;
2583    #ifdef PASO_MPI
2584        error = MPI_Comm_rank( get_MPIComm(), &rank );
2585    #else
2586        rank = 0;
2587    #endif
2588        return rank;
2589    }
2590    
2591    MPI_Comm
2592    Data::get_MPIComm() const
2593    {
2594    #ifdef PASO_MPI
2595        return MPI_COMM_WORLD;
2596    #else
2597        return -1;
2598    #endif
2599    }
2600    

Legend:
Removed from v.121  
changed lines
  Added in v.1327

  ViewVC Help
Powered by ViewVC 1.1.26