/[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

revision 790 by bcumming, Wed Jul 26 23:12:34 2006 UTC revision 2146 by jfenwick, Wed Dec 10 02:59:46 2008 UTC
# Line 1  Line 1 
 // $Id$  
1    
2  /*  /*******************************************************
3   ************************************************************  *
4   *          Copyright 2006 by ACcESS MNRF                   *  * Copyright (c) 2003-2008 by University of Queensland
5   *                                                          *  * Earth Systems Science Computational Center (ESSCC)
6   *              http://www.access.edu.au                    *  * http://www.uq.edu.au/esscc
7   *       Primary Business: Queensland, Australia            *  *
8   *  Licensed under the Open Software License version 3.0    *  * Primary Business: Queensland, Australia
9   *     http://www.opensource.org/licenses/osl-3.0.php       *  * Licensed under the Open Software License version 3.0
10   *                                                          *  * http://www.opensource.org/licenses/osl-3.0.php
11   ************************************************************  *
12  */  *******************************************************/
13    
14    
15  #include "Data.h"  #include "Data.h"
16    
17  #include "DataExpanded.h"  #include "DataExpanded.h"
18  #include "DataConstant.h"  #include "DataConstant.h"
19  #include "DataTagged.h"  #include "DataTagged.h"
20  #include "DataEmpty.h"  #include "DataEmpty.h"
21  #include "DataArray.h"  #include "DataLazy.h"
 #include "DataArrayView.h"  
 #include "DataProf.h"  
22  #include "FunctionSpaceFactory.h"  #include "FunctionSpaceFactory.h"
23  #include "AbstractContinuousDomain.h"  #include "AbstractContinuousDomain.h"
24  #include "UnaryFuncs.h"  #include "UnaryFuncs.h"
25    #include "FunctionSpaceException.h"
26    #include "EscriptParams.h"
27    
28    extern "C" {
29    #include "esysUtils/blocktimer.h"
30    }
31    
32  #include <fstream>  #include <fstream>
33  #include <algorithm>  #include <algorithm>
34  #include <vector>  #include <vector>
35  #include <functional>  #include <functional>
36    #include <sstream>  // so we can throw messages about ranks
37    
38  #include <boost/python/dict.hpp>  #include <boost/python/dict.hpp>
39  #include <boost/python/extract.hpp>  #include <boost/python/extract.hpp>
# Line 38  using namespace boost::python; Line 44  using namespace boost::python;
44  using namespace boost;  using namespace boost;
45  using namespace escript;  using namespace escript;
46    
47  #if defined DOPROF  // ensure the current object is not a DataLazy
48  //  // The idea was that we could add an optional warning whenever a resolve is forced
49  // global table of profiling data for all Data objects  #define FORCERESOLVE if (isLazy()) {resolve();}
50  DataProf dataProfTable;  #define AUTOLAZYON escriptParams.getAUTOLAZY()
51  #endif  #define MAKELAZYOP(X)   if (isLazy() || (AUTOLAZYON && m_data->isExpanded())) \
52      {\
53        DataLazy* c=new DataLazy(borrowDataPtr(),X);\
54        return Data(c);\
55      }
56    #define MAKELAZYOPOFF(X,Y) if (isLazy() || (AUTOLAZYON && m_data->isExpanded())) \
57      {\
58        DataLazy* c=new DataLazy(borrowDataPtr(),X,Y);\
59        return Data(c);\
60      }
61    
62    #define MAKELAZYBINSELF(R,X)   if (isLazy() || R.isLazy() || (AUTOLAZYON && (isExpanded() || R.isExpanded()))) \
63      {\
64        DataLazy* c=new DataLazy(m_data,R.borrowDataPtr(),X);\
65            m_data=c->getPtr();\
66        return (*this);\
67      }
68    
69    // like the above but returns a new data rather than *this
70    #define MAKELAZYBIN(R,X)   if (isLazy() || R.isLazy() || (AUTOLAZYON && (isExpanded() || R.isExpanded()))) \
71      {\
72        DataLazy* c=new DataLazy(m_data,R.borrowDataPtr(),X);\
73        return Data(c);\
74      }
75    
76    #define MAKELAZYBIN2(L,R,X)   if (L.isLazy() || R.isLazy() || (AUTOLAZYON && (L.isExpanded() || R.isExpanded()))) \
77      {\
78        DataLazy* c=new DataLazy(L.borrowDataPtr(),R.borrowDataPtr(),X);\
79        return Data(c);\
80      }
81    
82  Data::Data()  Data::Data()
83  {  {
84    //    //
85    // Default data is type DataEmpty    // Default data is type DataEmpty
86    DataAbstract* temp=new DataEmpty();    DataAbstract* temp=new DataEmpty();
87    shared_ptr<DataAbstract> temp_data(temp);    m_data=temp->getPtr();
   m_data=temp_data;  
88    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
89  }  }
90    
91  Data::Data(double value,  Data::Data(double value,
# Line 63  Data::Data(double value, Line 93  Data::Data(double value,
93             const FunctionSpace& what,             const FunctionSpace& what,
94             bool expanded)             bool expanded)
95  {  {
96    DataArrayView::ShapeType dataPointShape;    DataTypes::ShapeType dataPointShape;
97    for (int i = 0; i < shape.attr("__len__")(); ++i) {    for (int i = 0; i < shape.attr("__len__")(); ++i) {
98      dataPointShape.push_back(extract<const int>(shape[i]));      dataPointShape.push_back(extract<const int>(shape[i]));
99    }    }
100    DataArray temp(dataPointShape,value);  
101    initialise(temp.getView(),what,expanded);    int len = DataTypes::noValues(dataPointShape);
102      DataVector temp_data(len,value,len);
103      initialise(temp_data, dataPointShape, what, expanded);
104    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
105  }  }
106    
107  Data::Data(double value,  Data::Data(double value,
108         const DataArrayView::ShapeType& dataPointShape,         const DataTypes::ShapeType& dataPointShape,
109         const FunctionSpace& what,         const FunctionSpace& what,
110             bool expanded)             bool expanded)
111  {  {
112    DataArray temp(dataPointShape,value);    int len = DataTypes::noValues(dataPointShape);
113    pair<int,int> dataShape=what.getDataShape();  
114    initialise(temp.getView(),what,expanded);    DataVector temp_data(len,value,len);
115    //   DataArrayView temp_dataView(temp_data, dataPointShape);
116    
117    //   initialise(temp_dataView, what, expanded);
118      initialise(temp_data, dataPointShape, what, expanded);
119    
120    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
121  }  }
122    
123  Data::Data(const Data& inData)  Data::Data(const Data& inData)
124  {  {
125    m_data=inData.m_data;    m_data=inData.m_data;
126    m_protected=inData.isProtected();    m_protected=inData.isProtected();
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
127  }  }
128    
129    
130  Data::Data(const Data& inData,  Data::Data(const Data& inData,
131             const DataArrayView::RegionType& region)             const DataTypes::RegionType& region)
132  {  {
133      DataAbstract_ptr dat=inData.m_data;
134      if (inData.isLazy())
135      {
136        dat=inData.m_data->resolve();
137      }
138      else
139      {
140        dat=inData.m_data;
141      }
142    //    //
143    // Create Data which is a slice of another Data    // Create Data which is a slice of another Data
144    DataAbstract* tmp = inData.m_data->getSlice(region);    DataAbstract* tmp = dat->getSlice(region);
145    shared_ptr<DataAbstract> temp_data(tmp);    m_data=DataAbstract_ptr(tmp);
   m_data=temp_data;  
146    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
147  }  }
148    
149  Data::Data(const Data& inData,  Data::Data(const Data& inData,
150             const FunctionSpace& functionspace)             const FunctionSpace& functionspace)
151  {  {
152  #if defined DOPROF    if (inData.isEmpty())
153    // create entry in global profiling table for this object    {
154    profData = dataProfTable.newData();      throw DataException("Error - will not interpolate for instances of DataEmpty.");
155  #endif    }
156    if (inData.getFunctionSpace()==functionspace) {    if (inData.getFunctionSpace()==functionspace) {
157      m_data=inData.m_data;      m_data=inData.m_data;
158    } else {    }
159      #if defined DOPROF    else
160      profData->interpolate++;    {
161      #endif  
162      Data tmp(0,inData.getPointDataView().getShape(),functionspace,true);      if (inData.isConstant()) {  // for a constant function, we just need to use the new function space
163      // Note: Must use a reference or pointer to a derived object        if (!inData.probeInterpolation(functionspace))
164      // in order to get polymorphic behaviour. Shouldn't really        {           // Even though this is constant, we still need to check whether interpolation is allowed
165      // be able to create an instance of AbstractDomain but that was done      throw FunctionSpaceException("Cannot interpolate across to the domain of the specified FunctionSpace. (DataConstant)");
166      // as a boost:python work around which may no longer be required.        }
167      const AbstractDomain& inDataDomain=inData.getDomain();        // if the data is not lazy, this will just be a cast to DataReady
168      if  (inDataDomain==functionspace.getDomain()) {        DataReady_ptr dr=inData.m_data->resolve();
169        inDataDomain.interpolateOnDomain(tmp,inData);        DataConstant* dc=new DataConstant(functionspace,inData.m_data->getShape(),dr->getVector());  
170          m_data=DataAbstract_ptr(dc);
171      } else {      } else {
172        inDataDomain.interpolateACross(tmp,inData);        Data tmp(0,inData.getDataPointShape(),functionspace,true);
173          // Note: Must use a reference or pointer to a derived object
174          // in order to get polymorphic behaviour. Shouldn't really
175          // be able to create an instance of AbstractDomain but that was done
176          // as a boost:python work around which may no longer be required.
177          /*const AbstractDomain& inDataDomain=inData.getDomain();*/
178          const_Domain_ptr inDataDomain=inData.getDomain();
179          if  (inDataDomain==functionspace.getDomain()) {
180            inDataDomain->interpolateOnDomain(tmp,inData);
181          } else {
182            inDataDomain->interpolateACross(tmp,inData);
183          }
184          m_data=tmp.m_data;
185      }      }
     m_data=tmp.m_data;  
186    }    }
187    m_protected=false;    m_protected=false;
188  }  }
189    
190  Data::Data(const DataTagged::TagListType& tagKeys,  Data::Data(DataAbstract* underlyingdata)
            const DataTagged::ValueListType & values,  
            const DataArrayView& defaultValue,  
            const FunctionSpace& what,  
            bool expanded)  
191  {  {
192    DataAbstract* temp=new DataTagged(tagKeys,values,defaultValue,what);  //  m_data=shared_ptr<DataAbstract>(underlyingdata);
193    shared_ptr<DataAbstract> temp_data(temp);      m_data=underlyingdata->getPtr();
194    m_data=temp_data;      m_protected=false;
   m_protected=false;  
   if (expanded) {  
     expand();  
   }  
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
195  }  }
196    
197    Data::Data(DataAbstract_ptr underlyingdata)
198    {
199        m_data=underlyingdata;
200        m_protected=false;
201    }
202    
203    
204  Data::Data(const numeric::array& value,  Data::Data(const numeric::array& value,
205         const FunctionSpace& what,         const FunctionSpace& what,
206             bool expanded)             bool expanded)
207  {  {
208    initialise(value,what,expanded);    initialise(value,what,expanded);
209    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
210  }  }
211    
212  Data::Data(const DataArrayView& value,  Data::Data(const DataTypes::ValueType& value,
213         const FunctionSpace& what,           const DataTypes::ShapeType& shape,
214             bool expanded)                   const FunctionSpace& what,
215                     bool expanded)
216  {  {
217    initialise(value,what,expanded);     initialise(value,shape,what,expanded);
218    m_protected=false;     m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
219  }  }
220    
221    
222  Data::Data(const object& value,  Data::Data(const object& value,
223         const FunctionSpace& what,         const FunctionSpace& what,
224             bool expanded)             bool expanded)
# Line 195  Data::Data(const object& value, Line 226  Data::Data(const object& value,
226    numeric::array asNumArray(value);    numeric::array asNumArray(value);
227    initialise(asNumArray,what,expanded);    initialise(asNumArray,what,expanded);
228    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
229  }  }
230    
231    
232  Data::Data(const object& value,  Data::Data(const object& value,
233             const Data& other)             const Data& other)
234  {  {
235    //    numeric::array asNumArray(value);
236    // Create DataConstant using the given value and all other parameters  
237    // copied from other. If value is a rank 0 object this Data    // extract the shape of the numarray
238    // will assume the point data shape of other.    DataTypes::ShapeType tempShape=DataTypes::shapeFromNumArray(asNumArray);
239    DataArray temp(value);    if (DataTypes::getRank(tempShape)==0) {
240    if (temp.getView().getRank()==0) {  
241      //  
242      // Create a DataArray with the scalar value for all elements      // get the space for the data vector
243      DataArray temp2(other.getPointDataView().getShape(),temp.getView()());      int len1 = DataTypes::noValues(tempShape);
244      initialise(temp2.getView(),other.getFunctionSpace(),false);      DataVector temp_data(len1, 0.0, len1);
245        temp_data.copyFromNumArray(asNumArray,1);
246    
247        int len = DataTypes::noValues(other.getDataPointShape());
248    
249        DataVector temp2_data(len, temp_data[0]/*temp_dataView()*/, len);
250        DataConstant* t=new DataConstant(other.getFunctionSpace(),other.getDataPointShape(),temp2_data);
251        m_data=DataAbstract_ptr(t);
252    
253    } else {    } else {
254      //      //
255      // Create a DataConstant with the same sample shape as other      // Create a DataConstant with the same sample shape as other
256      initialise(temp.getView(),other.getFunctionSpace(),false);      DataConstant* t=new DataConstant(asNumArray,other.getFunctionSpace());
257    //     boost::shared_ptr<DataAbstract> sp(t);
258    //     m_data=sp;
259        m_data=DataAbstract_ptr(t);
260    }    }
261    m_protected=false;    m_protected=false;
 #if defined DOPROF  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
 #endif  
262  }  }
263    
264  Data::~Data()  Data::~Data()
# Line 231  Data::~Data() Line 266  Data::~Data()
266    
267  }  }
268    
269    
270    
271    void
272    Data::initialise(const boost::python::numeric::array& value,
273                     const FunctionSpace& what,
274                     bool expanded)
275    {
276      //
277      // Construct a Data object of the appropriate type.
278      // Construct the object first as there seems to be a bug which causes
279      // undefined behaviour if an exception is thrown during construction
280      // within the shared_ptr constructor.
281      if (expanded) {
282        DataAbstract* temp=new DataExpanded(value, what);
283    //     boost::shared_ptr<DataAbstract> temp_data(temp);
284    //     m_data=temp_data;
285        m_data=temp->getPtr();
286      } else {
287        DataAbstract* temp=new DataConstant(value, what);
288    //     boost::shared_ptr<DataAbstract> temp_data(temp);
289    //     m_data=temp_data;
290        m_data=temp->getPtr();
291      }
292    }
293    
294    
295    void
296    Data::initialise(const DataTypes::ValueType& value,
297             const DataTypes::ShapeType& shape,
298                     const FunctionSpace& what,
299                     bool expanded)
300    {
301      //
302      // Construct a Data object of the appropriate type.
303      // Construct the object first as there seems to be a bug which causes
304      // undefined behaviour if an exception is thrown during construction
305      // within the shared_ptr constructor.
306      if (expanded) {
307        DataAbstract* temp=new DataExpanded(what, shape, value);
308    //     boost::shared_ptr<DataAbstract> temp_data(temp);
309    //     m_data=temp_data;
310        m_data=temp->getPtr();
311      } else {
312        DataAbstract* temp=new DataConstant(what, shape, value);
313    //     boost::shared_ptr<DataAbstract> temp_data(temp);
314    //     m_data=temp_data;
315        m_data=temp->getPtr();
316      }
317    }
318    
319    
320    // void
321    // Data::CompareDebug(const Data& rd)
322    // {
323    //  using namespace std;
324    //  bool mismatch=false;
325    //  std::cout << "Comparing left and right" << endl;
326    //  const DataTagged* left=dynamic_cast<DataTagged*>(m_data.get());
327    //  const DataTagged* right=dynamic_cast<DataTagged*>(rd.m_data.get());
328    //  
329    //  if (left==0)
330    //  {
331    //      cout << "left arg is not a DataTagged\n";
332    //      return;
333    //  }
334    //  
335    //  if (right==0)
336    //  {
337    //      cout << "right arg is not a DataTagged\n";
338    //      return;
339    //  }
340    //  cout << "Num elements=" << left->getVector().size() << ":" << right->getVector().size() << std::endl;
341    //  cout << "Shapes ";
342    //  if (left->getShape()==right->getShape())
343    //  {
344    //      cout << "ok\n";
345    //  }
346    //  else
347    //  {
348    //      cout << "Problem: shapes do not match\n";
349    //      mismatch=true;
350    //  }
351    //  int lim=left->getVector().size();
352    //  if (right->getVector().size()) lim=right->getVector().size();
353    //  for (int i=0;i<lim;++i)
354    //  {
355    //      if (left->getVector()[i]!=right->getVector()[i])
356    //      {
357    //          cout << "[" << i << "] value mismatch " << left->getVector()[i] << ":" << right->getVector()[i] << endl;
358    //          mismatch=true;
359    //      }
360    //  }
361    //
362    //  // still need to check the tag map
363    //  // also need to watch what is happening to function spaces, are they copied or what?
364    //
365    //  const DataTagged::DataMapType& mapleft=left->getTagLookup();
366    //  const DataTagged::DataMapType& mapright=right->getTagLookup();
367    //
368    //  if (mapleft.size()!=mapright.size())
369    //  {
370    //      cout << "Maps are different sizes " << mapleft.size() << ":" << mapright.size() << endl;
371    //      mismatch=true;
372    //      cout << "Left map\n";
373    //      DataTagged::DataMapType::const_iterator i,j;
374    //      for (i=mapleft.begin();i!=mapleft.end();++i) {
375    //          cout << "(" << i->first << "=>" << i->second << ")\n";
376    //      }
377    //      cout << "Right map\n";
378    //      for (i=mapright.begin();i!=mapright.end();++i) {
379    //          cout << "(" << i->first << "=>" << i->second << ")\n";
380    //      }
381    //      cout << "End map\n";
382    //
383    //  }
384    //
385    //  DataTagged::DataMapType::const_iterator i,j;
386    //  for (i=mapleft.begin(),j=mapright.begin();i!=mapleft.end() && j!=mapright.end();++i,++j) {
387    //     if ((i->first!=j->first) || (i->second!=j->second))
388    //     {
389    //      cout << "(" << i->first << "=>" << i->second << ")";
390    //      cout << ":(" << j->first << "=>" << j->second << ") ";
391    //      mismatch=true;
392    //            }
393    //  }
394    //  if (mismatch)
395    //  {
396    //      cout << "#Mismatch\n";
397    //  }
398    // }
399    
400  escriptDataC  escriptDataC
401  Data::getDataC()  Data::getDataC()
402  {  {
# Line 250  Data::getDataC() const Line 416  Data::getDataC() const
416  const boost::python::tuple  const boost::python::tuple
417  Data::getShapeTuple() const  Data::getShapeTuple() const
418  {  {
419    const DataArrayView::ShapeType& shape=getDataPointShape();    const DataTypes::ShapeType& shape=getDataPointShape();
420    switch(getDataPointRank()) {    switch(getDataPointRank()) {
421       case 0:       case 0:
422          return make_tuple();          return make_tuple();
# Line 267  Data::getShapeTuple() const Line 433  Data::getShapeTuple() const
433    }    }
434  }  }
435    
436    
437    // The different name is needed because boost has trouble with overloaded functions.
438    // It can't work out what type the function is based soley on its name.
439    // There are ways to fix this involving creating function pointer variables for each form
440    // but there doesn't seem to be a need given that the methods have the same name from the python point of view
441    Data
442    Data::copySelf()
443    {
444       DataAbstract* temp=m_data->deepCopy();
445       return Data(temp);
446    }
447    
448  void  void
449  Data::copy(const Data& other)  Data::copy(const Data& other)
450  {  {
451    //    DataAbstract* temp=other.m_data->deepCopy();
452    // Perform a deep copy    DataAbstract_ptr p=temp->getPtr();
453    {    m_data=p;
454      DataExpanded* temp=dynamic_cast<DataExpanded*>(other.m_data.get());  }
455      if (temp!=0) {  
456        //  
457        // Construct a DataExpanded copy  Data
458        DataAbstract* newData=new DataExpanded(*temp);  Data::delay()
459        shared_ptr<DataAbstract> temp_data(newData);  {
460        m_data=temp_data;    DataLazy* dl=new DataLazy(m_data);
461        return;    return Data(dl);
462      }  }
463    }  
464    {  void
465      DataTagged* temp=dynamic_cast<DataTagged*>(other.m_data.get());  Data::delaySelf()
466      if (temp!=0) {  {
467        //    if (!isLazy())
       // Construct a DataTagged copy  
       DataAbstract* newData=new DataTagged(*temp);  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
       return;  
     }  
   }  
468    {    {
469      DataConstant* temp=dynamic_cast<DataConstant*>(other.m_data.get());      m_data=(new DataLazy(m_data))->getPtr();
     if (temp!=0) {  
       //  
       // Construct a DataConstant copy  
       DataAbstract* newData=new DataConstant(*temp);  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
       return;  
     }  
470    }    }
471    }
472    
473    void
474    Data::setToZero()
475    {
476      if (isEmpty())
477    {    {
478      DataEmpty* temp=dynamic_cast<DataEmpty*>(other.m_data.get());       throw DataException("Error - Operations not permitted on instances of DataEmpty.");
     if (temp!=0) {  
       //  
       // Construct a DataEmpty copy  
       DataAbstract* newData=new DataEmpty();  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
       return;  
     }  
479    }    }
480    throw DataException("Error - Copy not implemented for this Data type.");    m_data->setToZero();
481  }  }
482    
483  void  void
484  Data::copyWithMask(const Data& other,  Data::copyWithMask(const Data& other,
485                     const Data& mask)                     const Data& mask)
486  {  {
487    Data mask1;    // 1. Interpolate if required so all Datas use the same FS as this
488    Data mask2;    // 2. Tag or Expand so that all Data's are the same type
489      // 3. Iterate over the data vectors copying values where mask is >0
490      if (other.isEmpty() || mask.isEmpty())
491      {
492        throw DataException("Error - copyWithMask not permitted using instances of DataEmpty.");
493      }
494      Data other2(other);
495      Data mask2(mask);
496      other2.resolve();
497      mask2.resolve();
498      this->resolve();
499      FunctionSpace myFS=getFunctionSpace();
500      FunctionSpace oFS=other2.getFunctionSpace();
501      FunctionSpace mFS=mask2.getFunctionSpace();
502      if (oFS!=myFS)
503      {
504         if (other2.probeInterpolation(myFS))
505         {
506        other2=other2.interpolate(myFS);
507         }
508         else
509         {
510        throw DataException("Error - copyWithMask: other FunctionSpace is not compatible with this one.");
511         }
512      }
513      if (mFS!=myFS)
514      {
515         if (mask2.probeInterpolation(myFS))
516         {
517        mask2=mask2.interpolate(myFS);
518         }
519         else
520         {
521        throw DataException("Error - copyWithMask: mask FunctionSpace is not compatible with this one.");
522         }
523      }
524                // Ensure that all args have the same type
525      if (this->isExpanded() || mask2.isExpanded() || other2.isExpanded())
526      {
527        this->expand();
528        other2.expand();
529        mask2.expand();
530      }
531      else if (this->isTagged() || mask2.isTagged() || other2.isTagged())
532      {
533        this->tag();
534        other2.tag();
535        mask2.tag();
536      }
537      else if (this->isConstant() && mask2.isConstant() && other2.isConstant())
538      {
539      }
540      else
541      {
542        throw DataException("Error - Unknown DataAbstract passed to copyWithMask.");
543      }
544      // Now we iterate over the elements
545      DataVector& self=getReadyPtr()->getVector();
546      const DataVector& ovec=other2.getReadyPtr()->getVector();
547      const DataVector& mvec=mask2.getReadyPtr()->getVector();
548      if ((self.size()!=ovec.size()) || (self.size()!=mvec.size()))
549      {
550        throw DataException("Error - size mismatch in arguments to copyWithMask.");
551      }
552      size_t num_points=self.size();
553    
554    mask1 = mask.wherePositive();    // OPENMP 3.0 allows unsigned loop vars.
555    mask2.copy(mask1);  #if defined(_OPENMP) && (_OPENMP < 200805)
556      long i;
557    #else
558      size_t i;
559    #endif
560      #pragma omp parallel for private(i) schedule(static)
561      for (i=0;i<num_points;++i)
562      {
563        if (mvec[i]>0)
564        {
565           self[i]=ovec[i];
566        }
567      }
568    }
569    
   mask1 *= other;  
   mask2 *= *this;  
   mask2 = *this - mask2;  
570    
   *this = mask1 + mask2;  
 }  
571    
572  bool  bool
573  Data::isExpanded() const  Data::isExpanded() const
# Line 350  Data::isTagged() const Line 583  Data::isTagged() const
583    return (temp!=0);    return (temp!=0);
584  }  }
585    
 /* TODO */  
 /* global reduction -- the local data being empty does not imply that it is empty on other processers*/  
586  bool  bool
587  Data::isEmpty() const  Data::isEmpty() const
588  {  {
# Line 366  Data::isConstant() const Line 597  Data::isConstant() const
597    return (temp!=0);    return (temp!=0);
598  }  }
599    
600    bool
601    Data::isLazy() const
602    {
603      return m_data->isLazy();
604    }
605    
606    // at the moment this is synonymous with !isLazy() but that could change
607    bool
608    Data::isReady() const
609    {
610      return (dynamic_cast<DataReady*>(m_data.get())!=0);
611    }
612    
613    
614  void  void
615  Data::setProtection()  Data::setProtection()
616  {  {
617     m_protected=true;     m_protected=true;
618  }  }
619    
620  bool  bool
621  Data::isProtected() const  Data::isProtected() const
622  {  {
623     return m_protected;     return m_protected;
624  }  }
625    
# Line 386  Data::expand() Line 631  Data::expand()
631    if (isConstant()) {    if (isConstant()) {
632      DataConstant* tempDataConst=dynamic_cast<DataConstant*>(m_data.get());      DataConstant* tempDataConst=dynamic_cast<DataConstant*>(m_data.get());
633      DataAbstract* temp=new DataExpanded(*tempDataConst);      DataAbstract* temp=new DataExpanded(*tempDataConst);
634      shared_ptr<DataAbstract> temp_data(temp);  //     shared_ptr<DataAbstract> temp_data(temp);
635      m_data=temp_data;  //     m_data=temp_data;
636        m_data=temp->getPtr();
637    } else if (isTagged()) {    } else if (isTagged()) {
638      DataTagged* tempDataTag=dynamic_cast<DataTagged*>(m_data.get());      DataTagged* tempDataTag=dynamic_cast<DataTagged*>(m_data.get());
639      DataAbstract* temp=new DataExpanded(*tempDataTag);      DataAbstract* temp=new DataExpanded(*tempDataTag);
640      shared_ptr<DataAbstract> temp_data(temp);  //     shared_ptr<DataAbstract> temp_data(temp);
641      m_data=temp_data;  //     m_data=temp_data;
642        m_data=temp->getPtr();
643    } else if (isExpanded()) {    } else if (isExpanded()) {
644      //      //
645      // do nothing      // do nothing
646    } else if (isEmpty()) {    } else if (isEmpty()) {
647      throw DataException("Error - Expansion of DataEmpty not possible.");      throw DataException("Error - Expansion of DataEmpty not possible.");
648      } else if (isLazy()) {
649        resolve();
650        expand();       // resolve might not give us expanded data
651    } else {    } else {
652      throw DataException("Error - Expansion not implemented for this Data type.");      throw DataException("Error - Expansion not implemented for this Data type.");
653    }    }
# Line 409  Data::tag() Line 659  Data::tag()
659    if (isConstant()) {    if (isConstant()) {
660      DataConstant* tempDataConst=dynamic_cast<DataConstant*>(m_data.get());      DataConstant* tempDataConst=dynamic_cast<DataConstant*>(m_data.get());
661      DataAbstract* temp=new DataTagged(*tempDataConst);      DataAbstract* temp=new DataTagged(*tempDataConst);
662      shared_ptr<DataAbstract> temp_data(temp);  //     shared_ptr<DataAbstract> temp_data(temp);
663      m_data=temp_data;  //     m_data=temp_data;
664        m_data=temp->getPtr();
665    } else if (isTagged()) {    } else if (isTagged()) {
666      // do nothing      // do nothing
667    } else if (isExpanded()) {    } else if (isExpanded()) {
668      throw DataException("Error - Creating tag data from DataExpanded not possible.");      throw DataException("Error - Creating tag data from DataExpanded not possible.");
669    } else if (isEmpty()) {    } else if (isEmpty()) {
670      throw DataException("Error - Creating tag data from DataEmpty not possible.");      throw DataException("Error - Creating tag data from DataEmpty not possible.");
671      } else if (isLazy()) {
672         DataAbstract_ptr res=m_data->resolve();
673         if (m_data->isExpanded())
674         {
675        throw DataException("Error - data would resolve to DataExpanded, tagging is not possible.");
676         }
677         m_data=res;    
678         tag();
679    } else {    } else {
680      throw DataException("Error - Tagging not implemented for this Data type.");      throw DataException("Error - Tagging not implemented for this Data type.");
681    }    }
682  }  }
683    
684  void  void
685  Data::reshapeDataPoint(const DataArrayView::ShapeType& shape)  Data::resolve()
686    {
687      if (isLazy())
688      {
689         m_data=m_data->resolve();
690      }
691    }
692    
693    
694    Data
695    Data::oneOver() const
696  {  {
697    m_data->reshapeDataPoint(shape);    MAKELAZYOP(RECIP)
698      return C_TensorUnaryOperation(*this, bind1st(divides<double>(),1.));
699  }  }
700    
701  Data  Data
702  Data::wherePositive() const  Data::wherePositive() const
703  {  {
704  #if defined DOPROF    MAKELAZYOP(GZ)
705    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(greater<double>(),0.0));
 #endif  
   return escript::unaryOp(*this,bind2nd(greater<double>(),0.0));  
706  }  }
707    
708  Data  Data
709  Data::whereNegative() const  Data::whereNegative() const
710  {  {
711  #if defined DOPROF    MAKELAZYOP(LZ)
712    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(less<double>(),0.0));
 #endif  
   return escript::unaryOp(*this,bind2nd(less<double>(),0.0));  
713  }  }
714    
715  Data  Data
716  Data::whereNonNegative() const  Data::whereNonNegative() const
717  {  {
718  #if defined DOPROF    MAKELAZYOP(GEZ)
719    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(greater_equal<double>(),0.0));
 #endif  
   return escript::unaryOp(*this,bind2nd(greater_equal<double>(),0.0));  
720  }  }
721    
722  Data  Data
723  Data::whereNonPositive() const  Data::whereNonPositive() const
724  {  {
725  #if defined DOPROF    MAKELAZYOP(LEZ)
726    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(less_equal<double>(),0.0));
 #endif  
   return escript::unaryOp(*this,bind2nd(less_equal<double>(),0.0));  
727  }  }
728    
729  Data  Data
730  Data::whereZero(double tol) const  Data::whereZero(double tol) const
731  {  {
 #if defined DOPROF  
   profData->where++;  
 #endif  
732    Data dataAbs=abs();    Data dataAbs=abs();
733    return escript::unaryOp(dataAbs,bind2nd(less_equal<double>(),tol));    return C_TensorUnaryOperation(dataAbs, bind2nd(less_equal<double>(),tol));
734  }  }
735    
736  Data  Data
737  Data::whereNonZero(double tol) const  Data::whereNonZero(double tol) const
738  {  {
 #if defined DOPROF  
   profData->where++;  
 #endif  
739    Data dataAbs=abs();    Data dataAbs=abs();
740    return escript::unaryOp(dataAbs,bind2nd(greater<double>(),tol));    return C_TensorUnaryOperation(dataAbs, bind2nd(greater<double>(),tol));
741  }  }
742    
743  Data  Data
744  Data::interpolate(const FunctionSpace& functionspace) const  Data::interpolate(const FunctionSpace& functionspace) const
745  {  {
 #if defined DOPROF  
   profData->interpolate++;  
 #endif  
746    return Data(*this,functionspace);    return Data(*this,functionspace);
747  }  }
748    
749  bool  bool
750  Data::probeInterpolation(const FunctionSpace& functionspace) const  Data::probeInterpolation(const FunctionSpace& functionspace) const
751  {  {
752    if (getFunctionSpace()==functionspace) {    return getFunctionSpace().probeInterpolation(functionspace);
     return true;  
   } else {  
     const AbstractDomain& domain=getDomain();  
     if  (domain==functionspace.getDomain()) {  
       return domain.probeInterpolationOnDomain(getFunctionSpace().getTypeCode(),functionspace.getTypeCode());  
     } else {  
       return domain.probeInterpolationACross(getFunctionSpace().getTypeCode(),functionspace.getDomain(),functionspace.getTypeCode());  
     }  
   }  
753  }  }
754    
755  Data  Data
756  Data::gradOn(const FunctionSpace& functionspace) const  Data::gradOn(const FunctionSpace& functionspace) const
757  {  {
758  #if defined DOPROF    if (isEmpty())
759    profData->grad++;    {
760  #endif      throw DataException("Error - operation not permitted on instances of DataEmpty.");
761      }
762      double blocktimer_start = blocktimer_time();
763    if (functionspace.getDomain()!=getDomain())    if (functionspace.getDomain()!=getDomain())
764      throw DataException("Error - gradient cannot be calculated on different domains.");      throw DataException("Error - gradient cannot be calculated on different domains.");
765    DataArrayView::ShapeType grad_shape=getPointDataView().getShape();    DataTypes::ShapeType grad_shape=getDataPointShape();
766    grad_shape.push_back(functionspace.getDim());    grad_shape.push_back(functionspace.getDim());
767    Data out(0.0,grad_shape,functionspace,true);    Data out(0.0,grad_shape,functionspace,true);
768    getDomain().setToGradient(out,*this);    getDomain()->setToGradient(out,*this);
769      blocktimer_increment("grad()", blocktimer_start);
770    return out;    return out;
771  }  }
772    
773  Data  Data
774  Data::grad() const  Data::grad() const
775  {  {
776    return gradOn(escript::function(getDomain()));    if (isEmpty())
777      {
778        throw DataException("Error - operation not permitted on instances of DataEmpty.");
779      }
780      return gradOn(escript::function(*getDomain()));
781  }  }
782    
783  int  int
784  Data::getDataPointSize() const  Data::getDataPointSize() const
785  {  {
786    return getPointDataView().noValues();    return m_data->getNoValues();
787  }  }
788    
789  DataArrayView::ValueType::size_type  DataTypes::ValueType::size_type
790  Data::getLength() const  Data::getLength() const
791  {  {
792    return m_data->getLength();    return m_data->getLength();
793  }  }
794    
 const DataArrayView::ShapeType&  
 Data::getDataPointShape() const  
 {  
   return getPointDataView().getShape();  
 }  
   
 void  
 Data::fillFromNumArray(const boost::python::numeric::array num_array)  
 {  
   if (isProtected()) {  
         throw DataException("Error - attempt to update protected Data object.");  
   }  
   //  
   // check rank  
   if (num_array.getrank()<getDataPointRank())  
       throw DataException("Rank of numarray does not match Data object rank");  
   
   //  
   // check shape of num_array  
   for (int i=0; i<getDataPointRank(); i++) {  
     if (extract<int>(num_array.getshape()[i+1])!=getDataPointShape()[i])  
        throw DataException("Shape of numarray does not match Data object rank");  
   }  
   
   //  
   // make sure data is expanded:  
   if (!isExpanded()) {  
     expand();  
   }  
   
   //  
   // and copy over  
   m_data->copyAll(num_array);  
 }  
   
795  const  const
796  boost::python::numeric::array  boost::python::numeric::array
797  Data::convertToNumArray()  Data:: getValueOfDataPoint(int dataPointNo)
798  {  {
799    //    int i, j, k, l;
800    // determine the total number of data points  
801    int numSamples = getNumSamples();    FORCERESOLVE;
   int numDataPointsPerSample = getNumDataPointsPerSample();  
   int numDataPoints = numSamples * numDataPointsPerSample;  
802    
803    //    //
804    // determine the rank and shape of each data point    // determine the rank and shape of each data point
805    int dataPointRank = getDataPointRank();    int dataPointRank = getDataPointRank();
806    DataArrayView::ShapeType dataPointShape = getDataPointShape();    const DataTypes::ShapeType& dataPointShape = getDataPointShape();
807    
808    //    //
809    // create the numeric array to be returned    // create the numeric array to be returned
810    boost::python::numeric::array numArray(0.0);    boost::python::numeric::array numArray(0.0);
811    
812    //    //
813    // the rank of the returned numeric array will be the rank of    // the shape of the returned numeric array will be the same
814    // the data points, plus one. Where the rank of the array is n,    // as that of the data point
815    // the last n-1 dimensions will be equal to the shape of the    int arrayRank = dataPointRank;
816    // data points, whilst the first dimension will be equal to the    const DataTypes::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]);  
   }  
817    
818    //    //
819    // resize the numeric array to the shape just calculated    // resize the numeric array to the shape just calculated
820      if (arrayRank==0) {
821        numArray.resize(1);
822      }
823    if (arrayRank==1) {    if (arrayRank==1) {
824      numArray.resize(arrayShape[0]);      numArray.resize(arrayShape[0]);
825    }    }
# Line 623  Data::convertToNumArray() Line 832  Data::convertToNumArray()
832    if (arrayRank==4) {    if (arrayRank==4) {
833      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);
834    }    }
   if (arrayRank==5) {  
     numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3],arrayShape[4]);  
   }  
835    
836    //    if (getNumDataPointsPerSample()>0) {
837    // loop through each data point in turn, loading the values for that data point         int sampleNo = dataPointNo/getNumDataPointsPerSample();
838    // into the numeric array.         int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
839    int dataPoint = 0;         //
840    for (int sampleNo = 0; sampleNo < numSamples; sampleNo++) {         // Check a valid sample number has been supplied
841      for (int dataPointNo = 0; dataPointNo < numDataPointsPerSample; dataPointNo++) {         if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {
842        DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNo);             throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");
843        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);  
               }  
             }  
           }  
         }  
       }  
       dataPoint++;  
     }  
   }  
844    
845           //
846           // Check a valid data point number has been supplied
847           if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {
848               throw DataException("Error - Data::convertToNumArray: invalid dataPointNoInSample.");
849           }
850           // TODO: global error handling
851           // create a view of the data if it is stored locally
852    //       DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNoInSample);
853           DataTypes::ValueType::size_type offset=getDataOffset(sampleNo, dataPointNoInSample);
854    
855    
856           switch( dataPointRank ){
857                case 0 :
858                    numArray[0] = getDataAtOffset(offset);
859                    break;
860                case 1 :
861                    for( i=0; i<dataPointShape[0]; i++ )
862                        numArray[i]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i));
863                    break;
864                case 2 :
865                    for( i=0; i<dataPointShape[0]; i++ )
866                        for( j=0; j<dataPointShape[1]; j++)
867                            numArray[make_tuple(i,j)]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j));
868                    break;
869                case 3 :
870                    for( i=0; i<dataPointShape[0]; i++ )
871                        for( j=0; j<dataPointShape[1]; j++ )
872                            for( k=0; k<dataPointShape[2]; k++)
873                                numArray[make_tuple(i,j,k)]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k));
874                    break;
875                case 4 :
876                    for( i=0; i<dataPointShape[0]; i++ )
877                        for( j=0; j<dataPointShape[1]; j++ )
878                            for( k=0; k<dataPointShape[2]; k++ )
879                                for( l=0; l<dataPointShape[3]; l++)
880                                    numArray[make_tuple(i,j,k,l)]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k,l));
881                    break;
882        }
883      }
884    //    //
885    // return the loaded array    // return the array
886    return numArray;    return numArray;
887  }  }
888    
889  const  void
890  boost::python::numeric::array  Data::setValueOfDataPointToPyObject(int dataPointNo, const boost::python::object& py_object)
 Data::convertToNumArrayFromSampleNo(int sampleNo)  
891  {  {
892    //      // this will throw if the value cannot be represented
893    // Check a valid sample number has been supplied      boost::python::numeric::array num_array(py_object);
894    if (sampleNo >= getNumSamples()) {      setValueOfDataPointToArray(dataPointNo,num_array);
895      throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");  }
   }  
   
   //  
   // determine the number of data points per sample  
   int numDataPointsPerSample = getNumDataPointsPerSample();  
   
   //  
   // determine the rank and shape of each data point  
   int dataPointRank = getDataPointRank();  
   DataArrayView::ShapeType dataPointShape = getDataPointShape();  
896    
897    void
898    Data::setValueOfDataPointToArray(int dataPointNo, const boost::python::numeric::array& num_array)
899    {
900      if (isProtected()) {
901            throw DataException("Error - attempt to update protected Data object.");
902      }
903      FORCERESOLVE;
904    //    //
905    // create the numeric array to be returned    // check rank
906    boost::python::numeric::array numArray(0.0);    if (static_cast<unsigned int>(num_array.getrank())<getDataPointRank())
907          throw DataException("Rank of numarray does not match Data object rank");
908    
909    //    //
910    // the rank of the returned numeric array will be the rank of    // check shape of num_array
911    // the data points, plus one. Where the rank of the array is n,    for (unsigned int i=0; i<getDataPointRank(); i++) {
912    // the last n-1 dimensions will be equal to the shape of the      if (extract<int>(num_array.getshape()[i])!=getDataPointShape()[i])
913    // 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]);  
914    }    }
   
915    //    //
916    // resize the numeric array to the shape just calculated    // make sure data is expanded:
917    if (arrayRank==1) {    //
918      numArray.resize(arrayShape[0]);    if (!isExpanded()) {
919    }      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]);  
920    }    }
921    if (arrayRank==5) {    if (getNumDataPointsPerSample()>0) {
922      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3],arrayShape[4]);         int sampleNo = dataPointNo/getNumDataPointsPerSample();
923           int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
924           m_data->copyToDataPoint(sampleNo, dataPointNoInSample,num_array);
925      } else {
926           m_data->copyToDataPoint(-1, 0,num_array);
927    }    }
928    }
929    
930    //  void
931    // loop through each data point in turn, loading the values for that data point  Data::setValueOfDataPoint(int dataPointNo, const double value)
932    // into the numeric array.  {
933    for (int dataPoint = 0; dataPoint < numDataPointsPerSample; dataPoint++) {    if (isProtected()) {
934      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);  
             }  
           }  
         }  
       }  
     }  
935    }    }
   
936    //    //
937    // return the loaded array    // make sure data is expanded:
938    return numArray;    FORCERESOLVE;
939      if (!isExpanded()) {
940        expand();
941      }
942      if (getNumDataPointsPerSample()>0) {
943           int sampleNo = dataPointNo/getNumDataPointsPerSample();
944           int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
945           m_data->copyToDataPoint(sampleNo, dataPointNoInSample,value);
946      } else {
947           m_data->copyToDataPoint(-1, 0,value);
948      }
949  }  }
950    
951  const  const
952  boost::python::numeric::array  boost::python::numeric::array
953  Data::convertToNumArrayFromDPNo(int procNo,  Data::getValueOfGlobalDataPoint(int procNo, int dataPointNo)
                                 int sampleNo,  
                                                                 int dataPointNo)  
   
954  {  {
955      size_t length=0;    size_t length=0;
956      int i, j, k, l, pos;    int i, j, k, l, pos;
957      FORCERESOLVE;
   //  
   // Check a valid sample number has been supplied  
   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.");  
   }  
   
958    //    //
959    // determine the rank and shape of each data point    // determine the rank and shape of each data point
960    int dataPointRank = getDataPointRank();    int dataPointRank = getDataPointRank();
961    DataArrayView::ShapeType dataPointShape = getDataPointShape();    const DataTypes::ShapeType& dataPointShape = getDataPointShape();
962    
963    //    //
964    // create the numeric array to be returned    // create the numeric array to be returned
# Line 815  Data::convertToNumArrayFromDPNo(int proc Line 968  Data::convertToNumArrayFromDPNo(int proc
968    // the shape of the returned numeric array will be the same    // the shape of the returned numeric array will be the same
969    // as that of the data point    // as that of the data point
970    int arrayRank = dataPointRank;    int arrayRank = dataPointRank;
971    DataArrayView::ShapeType arrayShape = dataPointShape;    const DataTypes::ShapeType& arrayShape = dataPointShape;
972    
973    //    //
974    // resize the numeric array to the shape just calculated    // resize the numeric array to the shape just calculated
# Line 835  Data::convertToNumArrayFromDPNo(int proc Line 988  Data::convertToNumArrayFromDPNo(int proc
988      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);
989    }    }
990    
991      // added for the MPI communication    // added for the MPI communication
992      length=1;    length=1;
993      for( i=0; i<arrayRank; i++ )    for( i=0; i<arrayRank; i++ ) length *= arrayShape[i];
994          length *= arrayShape[i];    double *tmpData = new double[length];
     double *tmpData = new double[length];  
995    
996    //    //
997    // load the values for the data point into the numeric array.    // load the values for the data point into the numeric array.
998    
999      // updated for the MPI case      // updated for the MPI case
1000      if( get_MPIRank()==procNo ){      if( get_MPIRank()==procNo ){
1001                 if (getNumDataPointsPerSample()>0) {
1002                    int sampleNo = dataPointNo/getNumDataPointsPerSample();
1003                    int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
1004                    //
1005                    // Check a valid sample number has been supplied
1006                    if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {
1007                      throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");
1008                    }
1009    
1010                    //
1011                    // Check a valid data point number has been supplied
1012                    if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {
1013                      throw DataException("Error - Data::convertToNumArray: invalid dataPointNoInSample.");
1014                    }
1015                    // TODO: global error handling
1016          // create a view of the data if it is stored locally          // create a view of the data if it is stored locally
1017          DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNo);          //DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNoInSample);
1018                    DataTypes::ValueType::size_type offset=getDataOffset(sampleNo, dataPointNoInSample);
1019    
1020          // pack the data from the view into tmpData for MPI communication          // pack the data from the view into tmpData for MPI communication
1021          pos=0;          pos=0;
1022          switch( dataPointRank ){          switch( dataPointRank ){
1023              case 0 :              case 0 :
1024                  tmpData[0] = dataPointView();                  tmpData[0] = getDataAtOffset(offset);
1025                  break;                  break;
1026              case 1 :                      case 1 :
1027                  for( i=0; i<dataPointShape[0]; i++ )                  for( i=0; i<dataPointShape[0]; i++ )
1028                      tmpData[i]=dataPointView(i);                      tmpData[i]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i));
1029                  break;                  break;
1030              case 2 :                      case 2 :
1031                  for( i=0; i<dataPointShape[0]; i++ )                  for( i=0; i<dataPointShape[0]; i++ )
1032                      for( j=0; j<dataPointShape[1]; j++, pos++ )                      for( j=0; j<dataPointShape[1]; j++, pos++ )
1033                          tmpData[pos]=dataPointView(i,j);                          tmpData[pos]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j));
1034                  break;                  break;
1035              case 3 :                      case 3 :
1036                  for( i=0; i<dataPointShape[0]; i++ )                  for( i=0; i<dataPointShape[0]; i++ )
1037                      for( j=0; j<dataPointShape[1]; j++ )                      for( j=0; j<dataPointShape[1]; j++ )
1038                          for( k=0; k<dataPointShape[2]; k++, pos++ )                          for( k=0; k<dataPointShape[2]; k++, pos++ )
1039                              tmpData[pos]=dataPointView(i,j,k);                              tmpData[pos]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k));
1040                  break;                  break;
1041              case 4 :              case 4 :
1042                  for( i=0; i<dataPointShape[0]; i++ )                  for( i=0; i<dataPointShape[0]; i++ )
1043                      for( j=0; j<dataPointShape[1]; j++ )                      for( j=0; j<dataPointShape[1]; j++ )
1044                          for( k=0; k<dataPointShape[2]; k++ )                          for( k=0; k<dataPointShape[2]; k++ )
1045                              for( l=0; l<dataPointShape[3]; l++, pos++ )                              for( l=0; l<dataPointShape[3]; l++, pos++ )
1046                                  tmpData[pos]=dataPointView(i,j,k,l);                                  tmpData[pos]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k,l));
1047                  break;                  break;
1048          }          }
1049                }
1050      }      }
1051  #ifdef PASO_MPI          #ifdef PASO_MPI
1052          // broadcast the data to all other processes          // broadcast the data to all other processes
1053          MPI_Bcast( tmpData, length, MPI_DOUBLE, procNo, get_MPIComm() );      MPI_Bcast( tmpData, length, MPI_DOUBLE, procNo, get_MPIComm() );
1054  #endif          #endif
1055    
1056      // unpack the data      // unpack the data
1057      switch( dataPointRank ){      switch( dataPointRank ){
1058          case 0 :          case 0 :
1059              numArray[i]=tmpData[0];              numArray[0]=tmpData[0];
1060              break;              break;
1061          case 1 :                  case 1 :
1062              for( i=0; i<dataPointShape[0]; i++ )              for( i=0; i<dataPointShape[0]; i++ )
1063                  numArray[i]=tmpData[i];                  numArray[i]=tmpData[i];
1064              break;              break;
1065          case 2 :                  case 2 :
1066              for( i=0; i<dataPointShape[0]; i++ )              for( i=0; i<dataPointShape[0]; i++ )
1067                  for( j=0; j<dataPointShape[1]; j++ )                  for( j=0; j<dataPointShape[1]; j++ )
1068                      tmpData[i+j*dataPointShape[0]];                     numArray[make_tuple(i,j)]=tmpData[i+j*dataPointShape[0]];
1069              break;              break;
1070          case 3 :                  case 3 :
1071              for( i=0; i<dataPointShape[0]; i++ )              for( i=0; i<dataPointShape[0]; i++ )
1072                  for( j=0; j<dataPointShape[1]; j++ )                  for( j=0; j<dataPointShape[1]; j++ )
1073                      for( k=0; k<dataPointShape[2]; k++ )                      for( k=0; k<dataPointShape[2]; k++ )
1074                          tmpData[i+dataPointShape[0]*(j*+k*dataPointShape[1])];                          numArray[make_tuple(i,j,k)]=tmpData[i+dataPointShape[0]*(j*+k*dataPointShape[1])];
1075              break;              break;
1076          case 4 :          case 4 :
1077              for( i=0; i<dataPointShape[0]; i++ )              for( i=0; i<dataPointShape[0]; i++ )
1078                  for( j=0; j<dataPointShape[1]; j++ )                  for( j=0; j<dataPointShape[1]; j++ )
1079                      for( k=0; k<dataPointShape[2]; k++ )                      for( k=0; k<dataPointShape[2]; k++ )
1080                          for( l=0; l<dataPointShape[3]; l++ )                          for( l=0; l<dataPointShape[3]; l++ )
1081                              tmpData[i+dataPointShape[0]*(j*+dataPointShape[1]*(k+l*dataPointShape[2]))];                                  numArray[make_tuple(i,j,k,l)]=tmpData[i+dataPointShape[0]*(j*+dataPointShape[1]*(k+l*dataPointShape[2]))];
1082              break;              break;
1083      }      }
1084    
1085      delete [] tmpData;        delete [] tmpData;
 /*  
   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);  
           }  
         }  
       }  
     }  
   }  
 */  
   
1086    //    //
1087    // return the loaded array    // return the loaded array
1088    return numArray;    return numArray;
1089  }  }
1090    
1091    
1092    boost::python::numeric::array
1093    Data::integrate_const() const
1094    {
1095      if (isLazy())
1096      {
1097        throw DataException("Error - cannot integrate for constant lazy data.");
1098      }
1099      return integrateWorker();
1100    }
1101    
1102    boost::python::numeric::array
1103    Data::integrate()
1104    {
1105      if (isLazy())
1106      {
1107        expand();
1108      }
1109      return integrateWorker();
1110    }
1111    
1112    
1113    
1114  boost::python::numeric::array  boost::python::numeric::array
1115  Data::integrate() const  Data::integrateWorker() const
1116  {  {
1117    int index;    int index;
1118    int rank = getDataPointRank();    int rank = getDataPointRank();
1119    DataArrayView::ShapeType shape = getDataPointShape();    DataTypes::ShapeType shape = getDataPointShape();
1120      int dataPointSize = getDataPointSize();
 #if defined DOPROF  
   profData->integrate++;  
 #endif  
1121    
1122    //    //
1123    // calculate the integral values    // calculate the integral values
1124    vector<double> integrals(getDataPointSize());    vector<double> integrals(dataPointSize);
1125    AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals,*this);    vector<double> integrals_local(dataPointSize);
1126      const AbstractContinuousDomain* dom=dynamic_cast<const AbstractContinuousDomain*>(getDomain().get());
1127      if (dom==0)
1128      {            
1129        throw DataException("Can not integrate over non-continuous domains.");
1130      }
1131    #ifdef PASO_MPI
1132      dom->setToIntegrals(integrals_local,*this);
1133      // Global sum: use an array instead of a vector because elements of array are guaranteed to be contiguous in memory
1134      double *tmp = new double[dataPointSize];
1135      double *tmp_local = new double[dataPointSize];
1136      for (int i=0; i<dataPointSize; i++) { tmp_local[i] = integrals_local[i]; }
1137      MPI_Allreduce( &tmp_local[0], &tmp[0], dataPointSize, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
1138      for (int i=0; i<dataPointSize; i++) { integrals[i] = tmp[i]; }
1139      delete[] tmp;
1140      delete[] tmp_local;
1141    #else
1142      dom->setToIntegrals(integrals,*this);
1143    #endif
1144    
1145    //    //
1146    // create the numeric array to be returned    // create the numeric array to be returned
# Line 1031  Data::integrate() const Line 1200  Data::integrate() const
1200  Data  Data
1201  Data::sin() const  Data::sin() const
1202  {  {
1203  #if defined DOPROF    MAKELAZYOP(SIN)
1204    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sin);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sin);  
1205  }  }
1206    
1207  Data  Data
1208  Data::cos() const  Data::cos() const
1209  {  {
1210  #if defined DOPROF    MAKELAZYOP(COS)
1211    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::cos);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::cos);  
1212  }  }
1213    
1214  Data  Data
1215  Data::tan() const  Data::tan() const
1216  {  {
1217  #if defined DOPROF    MAKELAZYOP(TAN)
1218    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::tan);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::tan);  
1219  }  }
1220    
1221  Data  Data
1222  Data::asin() const  Data::asin() const
1223  {  {
1224  #if defined DOPROF    MAKELAZYOP(ASIN)
1225    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::asin);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::asin);  
1226  }  }
1227    
1228  Data  Data
1229  Data::acos() const  Data::acos() const
1230  {  {
1231  #if defined DOPROF    MAKELAZYOP(ACOS)
1232    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::acos);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::acos);  
1233  }  }
1234    
1235    
1236  Data  Data
1237  Data::atan() const  Data::atan() const
1238  {  {
1239  #if defined DOPROF    MAKELAZYOP(ATAN)
1240    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::atan);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::atan);  
1241  }  }
1242    
1243  Data  Data
1244  Data::sinh() const  Data::sinh() const
1245  {  {
1246  #if defined DOPROF    MAKELAZYOP(SINH)
1247    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sinh);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sinh);  
1248  }  }
1249    
1250  Data  Data
1251  Data::cosh() const  Data::cosh() const
1252  {  {
1253  #if defined DOPROF    MAKELAZYOP(COSH)
1254    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::cosh);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::cosh);  
1255  }  }
1256    
1257  Data  Data
1258  Data::tanh() const  Data::tanh() const
1259  {  {
1260  #if defined DOPROF    MAKELAZYOP(TANH)
1261    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::tanh);
1262    }
1263    
1264    
1265    Data
1266    Data::erf() const
1267    {
1268    #if defined (_WIN32) && !defined(__INTEL_COMPILER)
1269      throw DataException("Error - Data:: erf function is not supported on _WIN32 platforms.");
1270    #else
1271      MAKELAZYOP(ERF)
1272      return C_TensorUnaryOperation(*this, ::erf);
1273  #endif  #endif
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::tanh);  
1274  }  }
1275    
1276  Data  Data
1277  Data::asinh() const  Data::asinh() const
1278  {  {
1279  #if defined DOPROF    MAKELAZYOP(ASINH)
1280    profData->unary++;  #if defined (_WIN32) && !defined(__INTEL_COMPILER)
1281      return C_TensorUnaryOperation(*this, escript::asinh_substitute);
1282    #else
1283      return C_TensorUnaryOperation(*this, ::asinh);
1284  #endif  #endif
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::asinh);  
1285  }  }
1286    
1287  Data  Data
1288  Data::acosh() const  Data::acosh() const
1289  {  {
1290  #if defined DOPROF    MAKELAZYOP(ACOSH)
1291    profData->unary++;  #if defined (_WIN32) && !defined(__INTEL_COMPILER)
1292      return C_TensorUnaryOperation(*this, escript::acosh_substitute);
1293    #else
1294      return C_TensorUnaryOperation(*this, ::acosh);
1295  #endif  #endif
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::acosh);  
1296  }  }
1297    
1298  Data  Data
1299  Data::atanh() const  Data::atanh() const
1300  {  {
1301  #if defined DOPROF    MAKELAZYOP(ATANH)
1302    profData->unary++;  #if defined (_WIN32) && !defined(__INTEL_COMPILER)
1303      return C_TensorUnaryOperation(*this, escript::atanh_substitute);
1304    #else
1305      return C_TensorUnaryOperation(*this, ::atanh);
1306  #endif  #endif
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::atanh);  
1307  }  }
1308    
1309  Data  Data
1310  Data::log10() const  Data::log10() const
1311  {  {
1312  #if defined DOPROF    MAKELAZYOP(LOG10)
1313    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::log10);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log10);  
1314  }  }
1315    
1316  Data  Data
1317  Data::log() const  Data::log() const
1318  {  {
1319  #if defined DOPROF    MAKELAZYOP(LOG)
1320    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::log);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log);  
1321  }  }
1322    
1323  Data  Data
1324  Data::sign() const  Data::sign() const
1325  {  {
1326  #if defined DOPROF    MAKELAZYOP(SIGN)
1327    profData->unary++;    return C_TensorUnaryOperation(*this, escript::fsign);
 #endif  
   return escript::unaryOp(*this,escript::fsign);  
1328  }  }
1329    
1330  Data  Data
1331  Data::abs() const  Data::abs() const
1332  {  {
1333  #if defined DOPROF    MAKELAZYOP(ABS)
1334    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::fabs);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::fabs);  
1335  }  }
1336    
1337  Data  Data
1338  Data::neg() const  Data::neg() const
1339  {  {
1340  #if defined DOPROF    MAKELAZYOP(NEG)
1341    profData->unary++;    return C_TensorUnaryOperation(*this, negate<double>());
 #endif  
   return escript::unaryOp(*this,negate<double>());  
1342  }  }
1343    
1344  Data  Data
1345  Data::pos() const  Data::pos() const
1346  {  {
1347  #if defined DOPROF      // not doing lazy check here is deliberate.
1348    profData->unary++;      // since a deep copy of lazy data should be cheap, I'll just let it happen now
 #endif  
1349    Data result;    Data result;
1350    // perform a deep copy    // perform a deep copy
1351    result.copy(*this);    result.copy(*this);
# Line 1196  Data::pos() const Line 1355  Data::pos() const
1355  Data  Data
1356  Data::exp() const  Data::exp() const
1357  {  {
1358  #if defined DOPROF    MAKELAZYOP(EXP)
1359    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::exp);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::exp);  
1360  }  }
1361    
1362  Data  Data
1363  Data::sqrt() const  Data::sqrt() const
1364  {  {
1365  #if defined DOPROF    MAKELAZYOP(SQRT)
1366    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sqrt);
 #endif  
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sqrt);  
1367  }  }
1368    
1369  double  double
1370  Data::Lsup() const  Data::Lsup_const() const
1371  {  {
1372    double localValue, globalValue;     if (isLazy())
1373  #if defined DOPROF     {
1374    profData->reduction1++;      throw DataException("Error - cannot compute Lsup for constant lazy data.");
1375  #endif     }
1376    //     return LsupWorker();
1377    // set the initial absolute maximum value to zero  }
1378    
1379    AbsMax abs_max_func;  double
1380    localValue = algorithm(abs_max_func,0);  Data::Lsup()
1381  #ifdef PASO_MPI  {
1382    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );     if (isLazy())
1383    return globalValue;     {
1384  #else      resolve();
1385    return localValue;     }
1386  #endif     return LsupWorker();
1387  }  }
1388    
1389  double  double
1390  Data::Linf() const  Data::sup_const() const
1391  {  {
1392    double localValue, globalValue;     if (isLazy())
1393  #if defined DOPROF     {
1394    profData->reduction1++;      throw DataException("Error - cannot compute sup for constant lazy data.");
1395  #endif     }
1396       return supWorker();
1397    }
1398    
1399    double
1400    Data::sup()
1401    {
1402       if (isLazy())
1403       {
1404        resolve();
1405       }
1406       return supWorker();
1407    }
1408    
1409    double
1410    Data::inf_const() const
1411    {
1412       if (isLazy())
1413       {
1414        throw DataException("Error - cannot compute inf for constant lazy data.");
1415       }
1416       return infWorker();
1417    }
1418    
1419    double
1420    Data::inf()
1421    {
1422       if (isLazy())
1423       {
1424        resolve();
1425       }
1426       return infWorker();
1427    }
1428    
1429    double
1430    Data::LsupWorker() const
1431    {
1432      double localValue;
1433    //    //
1434    // set the initial absolute minimum value to max double    // set the initial absolute maximum value to zero
   AbsMin abs_min_func;  
   localValue = algorithm(abs_min_func,numeric_limits<double>::max());  
1435    
1436      AbsMax abs_max_func;
1437      localValue = algorithm(abs_max_func,0);
1438  #ifdef PASO_MPI  #ifdef PASO_MPI
1439    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD );    double globalValue;
1440      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1441    return globalValue;    return globalValue;
1442  #else  #else
1443    return localValue;    return localValue;
# Line 1252  Data::Linf() const Line 1445  Data::Linf() const
1445  }  }
1446    
1447  double  double
1448  Data::sup() const  Data::supWorker() const
1449  {  {
1450    double localValue, globalValue;    double localValue;
 #if defined DOPROF  
   profData->reduction1++;  
 #endif  
1451    //    //
1452    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1453    FMax fmax_func;    FMax fmax_func;
1454    localValue = algorithm(fmax_func,numeric_limits<double>::max()*-1);    localValue = algorithm(fmax_func,numeric_limits<double>::max()*-1);
1455  #ifdef PASO_MPI  #ifdef PASO_MPI
1456      double globalValue;
1457    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1458    return globalValue;    return globalValue;
1459  #else  #else
# Line 1271  Data::sup() const Line 1462  Data::sup() const
1462  }  }
1463    
1464  double  double
1465  Data::inf() const  Data::infWorker() const
1466  {  {
1467    double localValue, globalValue;    double localValue;
 #if defined DOPROF  
   profData->reduction1++;  
 #endif  
1468    //    //
1469    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1470    FMin fmin_func;    FMin fmin_func;
1471    localValue = algorithm(fmin_func,numeric_limits<double>::max());    localValue = algorithm(fmin_func,numeric_limits<double>::max());
1472  #ifdef PASO_MPI  #ifdef PASO_MPI
1473      double globalValue;
1474    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD );    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD );
1475    return globalValue;    return globalValue;
1476  #else  #else
# Line 1294  Data::inf() const Line 1483  Data::inf() const
1483  Data  Data
1484  Data::maxval() const  Data::maxval() const
1485  {  {
1486  #if defined DOPROF    if (isLazy())
1487    profData->reduction2++;    {
1488  #endif      Data temp(*this);   // to get around the fact that you can't resolve a const Data
1489        temp.resolve();
1490        return temp.maxval();
1491      }
1492    //    //
1493    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1494    FMax fmax_func;    FMax fmax_func;
# Line 1306  Data::maxval() const Line 1498  Data::maxval() const
1498  Data  Data
1499  Data::minval() const  Data::minval() const
1500  {  {
1501  #if defined DOPROF    if (isLazy())
1502    profData->reduction2++;    {
1503  #endif      Data temp(*this);   // to get around the fact that you can't resolve a const Data
1504        temp.resolve();
1505        return temp.minval();
1506      }
1507    //    //
1508    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1509    FMin fmin_func;    FMin fmin_func;
# Line 1316  Data::minval() const Line 1511  Data::minval() const
1511  }  }
1512    
1513  Data  Data
1514  Data::trace() const  Data::swapaxes(const int axis0, const int axis1) const
1515  {  {
1516  #if defined DOPROF       if (isLazy())
1517    profData->reduction2++;       {
1518  #endif      Data temp(*this);
1519    Trace trace_func;      temp.resolve();
1520    return dp_algorithm(trace_func,0);      return temp.swapaxes(axis0,axis1);
1521         }
1522         int axis0_tmp,axis1_tmp;
1523         DataTypes::ShapeType s=getDataPointShape();
1524         DataTypes::ShapeType ev_shape;
1525         // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1526         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1527         int rank=getDataPointRank();
1528         if (rank<2) {
1529            throw DataException("Error - Data::swapaxes argument must have at least rank 2.");
1530         }
1531         if (axis0<0 || axis0>rank-1) {
1532            throw DataException("Error - Data::swapaxes: axis0 must be between 0 and rank-1=" + rank-1);
1533         }
1534         if (axis1<0 || axis1>rank-1) {
1535             throw DataException("Error - Data::swapaxes: axis1 must be between 0 and rank-1=" + rank-1);
1536         }
1537         if (axis0 == axis1) {
1538             throw DataException("Error - Data::swapaxes: axis indices must be different.");
1539         }
1540         if (axis0 > axis1) {
1541             axis0_tmp=axis1;
1542             axis1_tmp=axis0;
1543         } else {
1544             axis0_tmp=axis0;
1545             axis1_tmp=axis1;
1546         }
1547         for (int i=0; i<rank; i++) {
1548           if (i == axis0_tmp) {
1549              ev_shape.push_back(s[axis1_tmp]);
1550           } else if (i == axis1_tmp) {
1551              ev_shape.push_back(s[axis0_tmp]);
1552           } else {
1553              ev_shape.push_back(s[i]);
1554           }
1555         }
1556         Data ev(0.,ev_shape,getFunctionSpace());
1557         ev.typeMatchRight(*this);
1558         m_data->swapaxes(ev.m_data.get(), axis0_tmp, axis1_tmp);
1559         return ev;
1560    
1561  }  }
1562    
1563  Data  Data
1564  Data::symmetric() const  Data::symmetric() const
1565  {  {
      #if defined DOPROF  
         profData->unary++;  
      #endif  
1566       // check input       // check input
1567       DataArrayView::ShapeType s=getDataPointShape();       DataTypes::ShapeType s=getDataPointShape();
1568       if (getDataPointRank()==2) {       if (getDataPointRank()==2) {
1569          if(s[0] != s[1])          if(s[0] != s[1])
1570             throw DataException("Error - Data::symmetric can only be calculated for rank 2 object with equal first and second dimension.");             throw DataException("Error - Data::symmetric can only be calculated for rank 2 object with equal first and second dimension.");
1571       }       }
1572       else if (getDataPointRank()==4) {       else if (getDataPointRank()==4) {
# Line 1344  Data::symmetric() const Line 1576  Data::symmetric() const
1576       else {       else {
1577          throw DataException("Error - Data::symmetric can only be calculated for rank 2 or 4 object.");          throw DataException("Error - Data::symmetric can only be calculated for rank 2 or 4 object.");
1578       }       }
1579         MAKELAZYOP(SYM)
1580       Data ev(0.,getDataPointShape(),getFunctionSpace());       Data ev(0.,getDataPointShape(),getFunctionSpace());
1581       ev.typeMatchRight(*this);       ev.typeMatchRight(*this);
1582       m_data->symmetric(ev.m_data.get());       m_data->symmetric(ev.m_data.get());
# Line 1353  Data::symmetric() const Line 1586  Data::symmetric() const
1586  Data  Data
1587  Data::nonsymmetric() const  Data::nonsymmetric() const
1588  {  {
1589       #if defined DOPROF       MAKELAZYOP(NSYM)
         profData->unary++;  
      #endif  
1590       // check input       // check input
1591       DataArrayView::ShapeType s=getDataPointShape();       DataTypes::ShapeType s=getDataPointShape();
1592       if (getDataPointRank()==2) {       if (getDataPointRank()==2) {
1593          if(s[0] != s[1])          if(s[0] != s[1])
1594             throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 object with equal first and second dimension.");             throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 object with equal first and second dimension.");
1595          DataArrayView::ShapeType ev_shape;          DataTypes::ShapeType ev_shape;
1596          ev_shape.push_back(s[0]);          ev_shape.push_back(s[0]);
1597          ev_shape.push_back(s[1]);          ev_shape.push_back(s[1]);
1598          Data ev(0.,ev_shape,getFunctionSpace());          Data ev(0.,ev_shape,getFunctionSpace());
# Line 1372  Data::nonsymmetric() const Line 1603  Data::nonsymmetric() const
1603       else if (getDataPointRank()==4) {       else if (getDataPointRank()==4) {
1604          if(!(s[0] == s[2] && s[1] == s[3]))          if(!(s[0] == s[2] && s[1] == s[3]))
1605             throw DataException("Error - Data::nonsymmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");             throw DataException("Error - Data::nonsymmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1606          DataArrayView::ShapeType ev_shape;          DataTypes::ShapeType ev_shape;
1607          ev_shape.push_back(s[0]);          ev_shape.push_back(s[0]);
1608          ev_shape.push_back(s[1]);          ev_shape.push_back(s[1]);
1609          ev_shape.push_back(s[2]);          ev_shape.push_back(s[2]);
# Line 1388  Data::nonsymmetric() const Line 1619  Data::nonsymmetric() const
1619  }  }
1620    
1621  Data  Data
1622  Data::matrixtrace(int axis_offset) const  Data::trace(int axis_offset) const
1623  {  {    
1624       #if defined DOPROF       MAKELAZYOPOFF(TRACE,axis_offset)
1625          profData->unary++;       DataTypes::ShapeType s=getDataPointShape();
      #endif  
      DataArrayView::ShapeType s=getDataPointShape();  
1626       if (getDataPointRank()==2) {       if (getDataPointRank()==2) {
1627          DataArrayView::ShapeType ev_shape;          DataTypes::ShapeType ev_shape;
1628          Data ev(0.,ev_shape,getFunctionSpace());          Data ev(0.,ev_shape,getFunctionSpace());
1629          ev.typeMatchRight(*this);          ev.typeMatchRight(*this);
1630          m_data->matrixtrace(ev.m_data.get(), axis_offset);          m_data->trace(ev.m_data.get(), axis_offset);
1631          return ev;          return ev;
1632       }       }
1633       if (getDataPointRank()==3) {       if (getDataPointRank()==3) {
1634          DataArrayView::ShapeType ev_shape;          DataTypes::ShapeType ev_shape;
1635          if (axis_offset==0) {          if (axis_offset==0) {
1636            int s2=s[2];            int s2=s[2];
1637            ev_shape.push_back(s2);            ev_shape.push_back(s2);
# Line 1413  Data::matrixtrace(int axis_offset) const Line 1642  Data::matrixtrace(int axis_offset) const
1642          }          }
1643          Data ev(0.,ev_shape,getFunctionSpace());          Data ev(0.,ev_shape,getFunctionSpace());
1644          ev.typeMatchRight(*this);          ev.typeMatchRight(*this);
1645          m_data->matrixtrace(ev.m_data.get(), axis_offset);          m_data->trace(ev.m_data.get(), axis_offset);
1646          return ev;          return ev;
1647       }       }
1648       if (getDataPointRank()==4) {       if (getDataPointRank()==4) {
1649          DataArrayView::ShapeType ev_shape;          DataTypes::ShapeType ev_shape;
1650          if (axis_offset==0) {          if (axis_offset==0) {
1651            ev_shape.push_back(s[2]);            ev_shape.push_back(s[2]);
1652            ev_shape.push_back(s[3]);            ev_shape.push_back(s[3]);
# Line 1432  Data::matrixtrace(int axis_offset) const Line 1661  Data::matrixtrace(int axis_offset) const
1661      }      }
1662          Data ev(0.,ev_shape,getFunctionSpace());          Data ev(0.,ev_shape,getFunctionSpace());
1663          ev.typeMatchRight(*this);          ev.typeMatchRight(*this);
1664      m_data->matrixtrace(ev.m_data.get(), axis_offset);      m_data->trace(ev.m_data.get(), axis_offset);
1665          return ev;          return ev;
1666       }       }
1667       else {       else {
1668          throw DataException("Error - Data::matrixtrace can only be calculated for rank 2, 3 or 4 object.");          throw DataException("Error - Data::trace can only be calculated for rank 2, 3 or 4 object.");
1669       }       }
1670  }  }
1671    
1672  Data  Data
1673  Data::transpose(int axis_offset) const  Data::transpose(int axis_offset) const
1674  {  {    
1675  #if defined DOPROF       MAKELAZYOPOFF(TRANS,axis_offset)
1676       profData->reduction2++;       DataTypes::ShapeType s=getDataPointShape();
1677  #endif       DataTypes::ShapeType ev_shape;
      DataArrayView::ShapeType s=getDataPointShape();  
      DataArrayView::ShapeType ev_shape;  
1678       // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]       // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1679       // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)       // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1680       int rank=getDataPointRank();       int rank=getDataPointRank();
# Line 1467  Data::transpose(int axis_offset) const Line 1694  Data::transpose(int axis_offset) const
1694  Data  Data
1695  Data::eigenvalues() const  Data::eigenvalues() const
1696  {  {
1697       #if defined DOPROF       if (isLazy())
1698          profData->unary++;       {
1699       #endif      Data temp(*this);   // to get around the fact that you can't resolve a const Data
1700        temp.resolve();
1701        return temp.eigenvalues();
1702         }
1703       // check input       // check input
1704       DataArrayView::ShapeType s=getDataPointShape();       DataTypes::ShapeType s=getDataPointShape();
1705       if (getDataPointRank()!=2)       if (getDataPointRank()!=2)
1706          throw DataException("Error - Data::eigenvalues can only be calculated for rank 2 object.");          throw DataException("Error - Data::eigenvalues can only be calculated for rank 2 object.");
1707       if(s[0] != s[1])       if(s[0] != s[1])
1708          throw DataException("Error - Data::eigenvalues can only be calculated for object with equal first and second dimension.");          throw DataException("Error - Data::eigenvalues can only be calculated for object with equal first and second dimension.");
1709       // create return       // create return
1710       DataArrayView::ShapeType ev_shape(1,s[0]);       DataTypes::ShapeType ev_shape(1,s[0]);
1711       Data ev(0.,ev_shape,getFunctionSpace());       Data ev(0.,ev_shape,getFunctionSpace());
1712       ev.typeMatchRight(*this);       ev.typeMatchRight(*this);
1713       m_data->eigenvalues(ev.m_data.get());       m_data->eigenvalues(ev.m_data.get());
# Line 1487  Data::eigenvalues() const Line 1717  Data::eigenvalues() const
1717  const boost::python::tuple  const boost::python::tuple
1718  Data::eigenvalues_and_eigenvectors(const double tol) const  Data::eigenvalues_and_eigenvectors(const double tol) const
1719  {  {
1720       #if defined DOPROF       if (isLazy())
1721          profData->unary++;       {
1722       #endif      Data temp(*this);   // to get around the fact that you can't resolve a const Data
1723       DataArrayView::ShapeType s=getDataPointShape();      temp.resolve();
1724       if (getDataPointRank()!=2)      return temp.eigenvalues_and_eigenvectors(tol);
1725         }
1726         DataTypes::ShapeType s=getDataPointShape();
1727         if (getDataPointRank()!=2)
1728          throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for rank 2 object.");          throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for rank 2 object.");
1729       if(s[0] != s[1])       if(s[0] != s[1])
1730          throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for object with equal first and second dimension.");          throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for object with equal first and second dimension.");
1731       // create return       // create return
1732       DataArrayView::ShapeType ev_shape(1,s[0]);       DataTypes::ShapeType ev_shape(1,s[0]);
1733       Data ev(0.,ev_shape,getFunctionSpace());       Data ev(0.,ev_shape,getFunctionSpace());
1734       ev.typeMatchRight(*this);       ev.typeMatchRight(*this);
1735       DataArrayView::ShapeType V_shape(2,s[0]);       DataTypes::ShapeType V_shape(2,s[0]);
1736       Data V(0.,V_shape,getFunctionSpace());       Data V(0.,V_shape,getFunctionSpace());
1737       V.typeMatchRight(*this);       V.typeMatchRight(*this);
1738       m_data->eigenvalues_and_eigenvectors(ev.m_data.get(),V.m_data.get(),tol);       m_data->eigenvalues_and_eigenvectors(ev.m_data.get(),V.m_data.get(),tol);
# Line 1507  Data::eigenvalues_and_eigenvectors(const Line 1740  Data::eigenvalues_and_eigenvectors(const
1740  }  }
1741    
1742  const boost::python::tuple  const boost::python::tuple
1743  Data::mindp() const  Data::minGlobalDataPoint() const
1744  {  {
1745    // NB: calc_mindp had to be split off from mindp as boost::make_tuple causes an    // NB: calc_minGlobalDataPoint( had to be split off from minGlobalDataPoint( as boost::make_tuple causes an
1746    // abort (for unknown reasons) if there are openmp directives with it in the    // abort (for unknown reasons) if there are openmp directives with it in the
1747    // surrounding function    // surrounding function
1748    
   int SampleNo;  
1749    int DataPointNo;    int DataPointNo;
1750      int ProcNo;    int ProcNo;
1751    calc_mindp(ProcNo,SampleNo,DataPointNo);    calc_minGlobalDataPoint(ProcNo,DataPointNo);
1752    return make_tuple(ProcNo,SampleNo,DataPointNo);    return make_tuple(ProcNo,DataPointNo);
1753  }  }
1754    
1755  void  void
1756  Data::calc_mindp(   int& ProcNo,  Data::calc_minGlobalDataPoint(int& ProcNo,
1757                  int& SampleNo,                          int& DataPointNo) const
         int& DataPointNo) const  
1758  {  {
1759      if (isLazy())
1760      {
1761        Data temp(*this);   // to get around the fact that you can't resolve a const Data
1762        temp.resolve();
1763        return temp.calc_minGlobalDataPoint(ProcNo,DataPointNo);
1764      }
1765    int i,j;    int i,j;
1766    int lowi=0,lowj=0;    int lowi=0,lowj=0;
1767    double min=numeric_limits<double>::max();    double min=numeric_limits<double>::max();
# Line 1535  Data::calc_mindp(  int& ProcNo, Line 1772  Data::calc_mindp(  int& ProcNo,
1772    int numDPPSample=temp.getNumDataPointsPerSample();    int numDPPSample=temp.getNumDataPointsPerSample();
1773    
1774    double next,local_min;    double next,local_min;
1775    int local_lowi,local_lowj;    int local_lowi=0,local_lowj=0;    
1776    
1777    #pragma omp parallel private(next,local_min,local_lowi,local_lowj)    #pragma omp parallel firstprivate(local_lowi,local_lowj) private(next,local_min)
1778    {    {
1779      local_min=min;      local_min=min;
1780      #pragma omp for private(i,j) schedule(static)      #pragma omp for private(i,j) schedule(static)
1781      for (i=0; i<numSamples; i++) {      for (i=0; i<numSamples; i++) {
1782        for (j=0; j<numDPPSample; j++) {        for (j=0; j<numDPPSample; j++) {
1783          next=temp.getDataPoint(i,j)();          next=temp.getDataAtOffset(temp.getDataOffset(i,j));
1784          if (next<local_min) {          if (next<local_min) {
1785            local_min=next;            local_min=next;
1786            local_lowi=i;            local_lowi=i;
# Line 1561  Data::calc_mindp(  int& ProcNo, Line 1798  Data::calc_mindp(  int& ProcNo,
1798    
1799  #ifdef PASO_MPI  #ifdef PASO_MPI
1800      // determine the processor on which the minimum occurs      // determine the processor on which the minimum occurs
1801      next = temp.getDataPoint(lowi,lowj)();      next = temp.getDataPoint(lowi,lowj);
1802      int lowProc = 0;      int lowProc = 0;
1803      double *globalMins = new double[get_MPISize()+1];      double *globalMins = new double[get_MPISize()+1];
1804      int error = MPI_Gather ( &next, 1, MPI_DOUBLE, globalMins, 1, MPI_DOUBLE, 0, get_MPIComm() );      int error;
1805            error = MPI_Gather ( &next, 1, MPI_DOUBLE, globalMins, 1, MPI_DOUBLE, 0, get_MPIComm() );
1806    
1807      if( get_MPIRank()==0 ){      if( get_MPIRank()==0 ){
1808          next = globalMins[lowProc];          next = globalMins[lowProc];
1809          for( i=1; i<get_MPISize(); i++ )          for( i=1; i<get_MPISize(); i++ )
# Line 1581  Data::calc_mindp(  int& ProcNo, Line 1819  Data::calc_mindp(  int& ProcNo,
1819  #else  #else
1820      ProcNo = 0;      ProcNo = 0;
1821  #endif  #endif
1822    SampleNo = lowi;    DataPointNo = lowj + lowi * numDPPSample;
   DataPointNo = lowj;  
1823  }  }
1824    
1825  void  void
1826  Data::saveDX(std::string fileName) const  Data::saveDX(std::string fileName) const
1827  {  {
1828      if (isEmpty())
1829      {
1830        throw DataException("Error - Operations not permitted on instances of DataEmpty.");
1831      }
1832      if (isLazy())
1833      {
1834         Data temp(*this);  // to get around the fact that you can't resolve a const Data
1835         temp.resolve();
1836         temp.saveDX(fileName);
1837         return;
1838      }
1839    boost::python::dict args;    boost::python::dict args;
1840    args["data"]=boost::python::object(this);    args["data"]=boost::python::object(this);
1841    getDomain().saveDX(fileName,args);    getDomain()->saveDX(fileName,args);
1842    return;    return;
1843  }  }
1844    
1845  void  void
1846  Data::saveVTK(std::string fileName) const  Data::saveVTK(std::string fileName) const
1847  {  {
1848      if (isEmpty())
1849      {
1850        throw DataException("Error - Operations not permitted on instances of DataEmpty.");
1851      }
1852      if (isLazy())
1853      {
1854         Data temp(*this);  // to get around the fact that you can't resolve a const Data
1855         temp.resolve();
1856         temp.saveVTK(fileName);
1857         return;
1858      }
1859    boost::python::dict args;    boost::python::dict args;
1860    args["data"]=boost::python::object(this);    args["data"]=boost::python::object(this);
1861    getDomain().saveVTK(fileName,args);    getDomain()->saveVTK(fileName,args);
1862    return;    return;
1863  }  }
1864    
# Line 1609  Data::operator+=(const Data& right) Line 1868  Data::operator+=(const Data& right)
1868    if (isProtected()) {    if (isProtected()) {
1869          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1870    }    }
1871  #if defined DOPROF    MAKELAZYBINSELF(right,ADD)    // for lazy + is equivalent to +=
   profData->binary++;  
 #endif  
1872    binaryOp(right,plus<double>());    binaryOp(right,plus<double>());
1873    return (*this);    return (*this);
1874  }  }
# Line 1622  Data::operator+=(const boost::python::ob Line 1879  Data::operator+=(const boost::python::ob
1879    if (isProtected()) {    if (isProtected()) {
1880          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1881    }    }
1882  #if defined DOPROF    Data tmp(right,getFunctionSpace(),false);
1883    profData->binary++;    MAKELAZYBINSELF(tmp,ADD)
1884  #endif    binaryOp(tmp,plus<double>());
1885    binaryOp(right,plus<double>());    return (*this);
1886    }
1887    
1888    // Hmmm, operator= makes a deep copy but the copy constructor does not?
1889    Data&
1890    Data::operator=(const Data& other)
1891    {
1892      copy(other);
1893    return (*this);    return (*this);
1894  }  }
1895    
# Line 1635  Data::operator-=(const Data& right) Line 1899  Data::operator-=(const Data& right)
1899    if (isProtected()) {    if (isProtected()) {
1900          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1901    }    }
1902  #if defined DOPROF    MAKELAZYBINSELF(right,SUB)
   profData->binary++;  
 #endif  
1903    binaryOp(right,minus<double>());    binaryOp(right,minus<double>());
1904    return (*this);    return (*this);
1905  }  }
# Line 1648  Data::operator-=(const boost::python::ob Line 1910  Data::operator-=(const boost::python::ob
1910    if (isProtected()) {    if (isProtected()) {
1911          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1912    }    }
1913  #if defined DOPROF    Data tmp(right,getFunctionSpace(),false);
1914    profData->binary++;    MAKELAZYBINSELF(tmp,SUB)
1915  #endif    binaryOp(tmp,minus<double>());
   binaryOp(right,minus<double>());  
1916    return (*this);    return (*this);
1917  }  }
1918    
# Line 1661  Data::operator*=(const Data& right) Line 1922  Data::operator*=(const Data& right)
1922    if (isProtected()) {    if (isProtected()) {
1923          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1924    }    }
1925  #if defined DOPROF    MAKELAZYBINSELF(right,MUL)
   profData->binary++;  
 #endif  
1926    binaryOp(right,multiplies<double>());    binaryOp(right,multiplies<double>());
1927    return (*this);    return (*this);
1928  }  }
1929    
1930  Data&  Data&
1931  Data::operator*=(const boost::python::object& right)  Data::operator*=(const boost::python::object& right)
1932  {  {  
1933    if (isProtected()) {    if (isProtected()) {
1934          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1935    }    }
1936  #if defined DOPROF    Data tmp(right,getFunctionSpace(),false);
1937    profData->binary++;    MAKELAZYBINSELF(tmp,MUL)
1938  #endif    binaryOp(tmp,multiplies<double>());
   binaryOp(right,multiplies<double>());  
1939    return (*this);    return (*this);
1940  }  }
1941    
# Line 1687  Data::operator/=(const Data& right) Line 1945  Data::operator/=(const Data& right)
1945    if (isProtected()) {    if (isProtected()) {
1946          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1947    }    }
1948  #if defined DOPROF    MAKELAZYBINSELF(right,DIV)
   profData->binary++;  
 #endif  
1949    binaryOp(right,divides<double>());    binaryOp(right,divides<double>());
1950    return (*this);    return (*this);
1951  }  }
# Line 1700  Data::operator/=(const boost::python::ob Line 1956  Data::operator/=(const boost::python::ob
1956    if (isProtected()) {    if (isProtected()) {
1957          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
1958    }    }
1959  #if defined DOPROF    Data tmp(right,getFunctionSpace(),false);
1960    profData->binary++;    MAKELAZYBINSELF(tmp,DIV)
1961  #endif    binaryOp(tmp,divides<double>());
   binaryOp(right,divides<double>());  
1962    return (*this);    return (*this);
1963  }  }
1964    
1965  Data  Data
1966  Data::rpowO(const boost::python::object& left) const  Data::rpowO(const boost::python::object& left) const
1967  {  {
   if (isProtected()) {  
         throw DataException("Error - attempt to update protected Data object.");  
   }  
 #if defined DOPROF  
   profData->binary++;  
 #endif  
1968    Data left_d(left,*this);    Data left_d(left,*this);
1969    return left_d.powD(*this);    return left_d.powD(*this);
1970  }  }
# Line 1723  Data::rpowO(const boost::python::object& Line 1972  Data::rpowO(const boost::python::object&
1972  Data  Data
1973  Data::powO(const boost::python::object& right) const  Data::powO(const boost::python::object& right) const
1974  {  {
1975  #if defined DOPROF    Data tmp(right,getFunctionSpace(),false);
1976    profData->binary++;    return powD(tmp);
 #endif  
   Data result;  
   result.copy(*this);  
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1977  }  }
1978    
1979  Data  Data
1980  Data::powD(const Data& right) const  Data::powD(const Data& right) const
1981  {  {
1982  #if defined DOPROF    MAKELAZYBIN(right,POW)
1983    profData->binary++;    return C_TensorBinaryOperation<double (*)(double, double)>(*this, right, ::pow);
 #endif  
   Data result;  
   result.copy(*this);  
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1984  }  }
1985    
   
1986  //  //
1987  // NOTE: It is essential to specify the namespace this operator belongs to  // NOTE: It is essential to specify the namespace this operator belongs to
1988  Data  Data
1989  escript::operator+(const Data& left, const Data& right)  escript::operator+(const Data& left, const Data& right)
1990  {  {
1991    Data result;    MAKELAZYBIN2(left,right,ADD)
1992    //    return C_TensorBinaryOperation(left, right, plus<double>());
   // perform a deep copy  
   result.copy(left);  
   result+=right;  
   return result;  
1993  }  }
1994    
1995  //  //
# Line 1763  escript::operator+(const Data& left, con Line 1997  escript::operator+(const Data& left, con
1997  Data  Data
1998  escript::operator-(const Data& left, const Data& right)  escript::operator-(const Data& left, const Data& right)
1999  {  {
2000    Data result;    MAKELAZYBIN2(left,right,SUB)
2001    //    return C_TensorBinaryOperation(left, right, minus<double>());
   // perform a deep copy  
   result.copy(left);  
   result-=right;  
   return result;  
2002  }  }
2003    
2004  //  //
# Line 1776  escript::operator-(const Data& left, con Line 2006  escript::operator-(const Data& left, con
2006  Data  Data
2007  escript::operator*(const Data& left, const Data& right)  escript::operator*(const Data& left, const Data& right)
2008  {  {
2009    Data result;    MAKELAZYBIN2(left,right,MUL)
2010    //    return C_TensorBinaryOperation(left, right, multiplies<double>());
   // perform a deep copy  
   result.copy(left);  
   result*=right;  
   return result;  
2011  }  }
2012    
2013  //  //
# Line 1789  escript::operator*(const Data& left, con Line 2015  escript::operator*(const Data& left, con
2015  Data  Data
2016  escript::operator/(const Data& left, const Data& right)  escript::operator/(const Data& left, const Data& right)
2017  {  {
2018    Data result;    MAKELAZYBIN2(left,right,DIV)
2019    //    return C_TensorBinaryOperation(left, right, divides<double>());
   // perform a deep copy  
   result.copy(left);  
   result/=right;  
   return result;  
2020  }  }
2021    
2022  //  //
# Line 1802  escript::operator/(const Data& left, con Line 2024  escript::operator/(const Data& left, con
2024  Data  Data
2025  escript::operator+(const Data& left, const boost::python::object& right)  escript::operator+(const Data& left, const boost::python::object& right)
2026  {  {
2027    //    Data tmp(right,left.getFunctionSpace(),false);
2028    // Convert to DataArray format if possible    MAKELAZYBIN2(left,tmp,ADD)
2029    DataArray temp(right);    return left+tmp;
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result+=right;  
   return result;  
2030  }  }
2031    
2032  //  //
# Line 1818  escript::operator+(const Data& left, con Line 2034  escript::operator+(const Data& left, con
2034  Data  Data
2035  escript::operator-(const Data& left, const boost::python::object& right)  escript::operator-(const Data& left, const boost::python::object& right)
2036  {  {
2037    //    Data tmp(right,left.getFunctionSpace(),false);
2038    // Convert to DataArray format if possible    MAKELAZYBIN2(left,tmp,SUB)
2039    DataArray temp(right);    return left-tmp;
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result-=right;  
   return result;  
2040  }  }
2041    
2042  //  //
# Line 1834  escript::operator-(const Data& left, con Line 2044  escript::operator-(const Data& left, con
2044  Data  Data
2045  escript::operator*(const Data& left, const boost::python::object& right)  escript::operator*(const Data& left, const boost::python::object& right)
2046  {  {
2047    //    Data tmp(right,left.getFunctionSpace(),false);
2048    // Convert to DataArray format if possible    MAKELAZYBIN2(left,tmp,MUL)
2049    DataArray temp(right);    return left*tmp;
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result*=right;  
   return result;  
2050  }  }
2051    
2052  //  //
# Line 1850  escript::operator*(const Data& left, con Line 2054  escript::operator*(const Data& left, con
2054  Data  Data
2055  escript::operator/(const Data& left, const boost::python::object& right)  escript::operator/(const Data& left, const boost::python::object& right)
2056  {  {
2057    //    Data tmp(right,left.getFunctionSpace(),false);
2058    // Convert to DataArray format if possible    MAKELAZYBIN2(left,tmp,DIV)
2059    DataArray temp(right);    return left/tmp;
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result/=right;  
   return result;  
2060  }  }
2061    
2062  //  //
# Line 1866  escript::operator/(const Data& left, con Line 2064  escript::operator/(const Data& left, con
2064  Data  Data
2065  escript::operator+(const boost::python::object& left, const Data& right)  escript::operator+(const boost::python::object& left, const Data& right)
2066  {  {
2067    //    Data tmp(left,right.getFunctionSpace(),false);
2068    // Construct the result using the given value and the other parameters    MAKELAZYBIN2(tmp,right,ADD)
2069    // from right    return tmp+right;
   Data result(left,right);  
   result+=right;  
   return result;  
2070  }  }
2071    
2072  //  //
# Line 1879  escript::operator+(const boost::python:: Line 2074  escript::operator+(const boost::python::
2074  Data  Data
2075  escript::operator-(const boost::python::object& left, const Data& right)  escript::operator-(const boost::python::object& left, const Data& right)
2076  {  {
2077    //    Data tmp(left,right.getFunctionSpace(),false);
2078    // Construct the result using the given value and the other parameters    MAKELAZYBIN2(tmp,right,SUB)
2079    // from right    return tmp-right;
   Data result(left,right);  
   result-=right;  
   return result;  
2080  }  }
2081    
2082  //  //
# Line 1892  escript::operator-(const boost::python:: Line 2084  escript::operator-(const boost::python::
2084  Data  Data
2085  escript::operator*(const boost::python::object& left, const Data& right)  escript::operator*(const boost::python::object& left, const Data& right)
2086  {  {
2087    //    Data tmp(left,right.getFunctionSpace(),false);
2088    // Construct the result using the given value and the other parameters    MAKELAZYBIN2(tmp,right,MUL)
2089    // from right    return tmp*right;
   Data result(left,right);  
   result*=right;  
   return result;  
2090  }  }
2091    
2092  //  //
# Line 1905  escript::operator*(const boost::python:: Line 2094  escript::operator*(const boost::python::
2094  Data  Data
2095  escript::operator/(const boost::python::object& left, const Data& right)  escript::operator/(const boost::python::object& left, const Data& right)
2096  {  {
2097    //    Data tmp(left,right.getFunctionSpace(),false);
2098    // Construct the result using the given value and the other parameters    MAKELAZYBIN2(tmp,right,DIV)
2099    // from right    return tmp/right;
   Data result(left,right);  
   result/=right;  
   return result;  
2100  }  }
2101    
 //  
 //bool escript::operator==(const Data& left, const Data& right)  
 //{  
 //  /*  
 //  NB: this operator does very little at this point, and isn't to  
 //  be relied on. Requires further implementation.  
 //  */  
 //  
 //  bool ret;  
 //  
 //  if (left.isEmpty()) {  
 //    if(!right.isEmpty()) {  
 //      ret = false;  
 //    } else {  
 //      ret = true;  
 //    }  
 //  }  
 //  
 //  if (left.isConstant()) {  
 //    if(!right.isConstant()) {  
 //      ret = false;  
 //    } else {  
 //      ret = true;  
 //    }  
 // }  
 //  
 //  if (left.isTagged()) {  
 //   if(!right.isTagged()) {  
 //      ret = false;  
 //    } else {  
 //      ret = true;  
 //    }  
 //  }  
 //  
 //  if (left.isExpanded()) {  
 //    if(!right.isExpanded()) {  
 //      ret = false;  
 //    } else {  
 //      ret = true;  
 //    }  
 //  }  
 //  
 //  return ret;  
 //}  
2102    
2103  /* TODO */  /* TODO */
2104  /* global reduction */  /* global reduction */
2105  Data  Data
2106  Data::getItem(const boost::python::object& key) const  Data::getItem(const boost::python::object& key) const
2107  {  {
   const DataArrayView& view=getPointDataView();  
2108    
2109    DataArrayView::RegionType slice_region=view.getSliceRegion(key);    DataTypes::RegionType slice_region=DataTypes::getSliceRegion(getDataPointShape(),key);
2110    
2111    if (slice_region.size()!=view.getRank()) {    if (slice_region.size()!=getDataPointRank()) {
2112      throw DataException("Error - slice size does not match Data rank.");      throw DataException("Error - slice size does not match Data rank.");
2113    }    }
2114    
# Line 1977  Data::getItem(const boost::python::objec Line 2118  Data::getItem(const boost::python::objec
2118  /* TODO */  /* TODO */
2119  /* global reduction */  /* global reduction */
2120  Data  Data
2121  Data::getSlice(const DataArrayView::RegionType& region) const  Data::getSlice(const DataTypes::RegionType& region) const
2122  {  {
 #if defined DOPROF  
   profData->slicing++;  
 #endif  
2123    return Data(*this,region);    return Data(*this,region);
2124  }  }
2125    
# Line 1995  Data::setItemO(const boost::python::obje Line 2133  Data::setItemO(const boost::python::obje
2133    setItemD(key,tempData);    setItemD(key,tempData);
2134  }  }
2135    
 /* TODO */  
 /* global reduction */  
2136  void  void
2137  Data::setItemD(const boost::python::object& key,  Data::setItemD(const boost::python::object& key,
2138                 const Data& value)                 const Data& value)
2139  {  {
2140    const DataArrayView& view=getPointDataView();  //  const DataArrayView& view=getPointDataView();
2141    
2142    DataArrayView::RegionType slice_region=view.getSliceRegion(key);    DataTypes::RegionType slice_region=DataTypes::getSliceRegion(getDataPointShape(),key);
2143    if (slice_region.size()!=view.getRank()) {    if (slice_region.size()!=getDataPointRank()) {
2144      throw DataException("Error - slice size does not match Data rank.");      throw DataException("Error - slice size does not match Data rank.");
2145    }    }
2146    if (getFunctionSpace()!=value.getFunctionSpace()) {    if (getFunctionSpace()!=value.getFunctionSpace()) {
# Line 2014  Data::setItemD(const boost::python::obje Line 2150  Data::setItemD(const boost::python::obje
2150    }    }
2151  }  }
2152    
 /* TODO */  
 /* global reduction */  
2153  void  void
2154  Data::setSlice(const Data& value,  Data::setSlice(const Data& value,
2155                 const DataArrayView::RegionType& region)                 const DataTypes::RegionType& region)
2156  {  {
2157    if (isProtected()) {    if (isProtected()) {
2158          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
2159    }    }
2160  #if defined DOPROF    FORCERESOLVE;
2161    profData->slicing++;  /*  if (isLazy())
2162  #endif    {
2163        throw DataException("Error - setSlice not permitted on lazy data.");
2164      }*/
2165    Data tempValue(value);    Data tempValue(value);
2166    typeMatchLeft(tempValue);    typeMatchLeft(tempValue);
2167    typeMatchRight(tempValue);    typeMatchRight(tempValue);
2168    m_data->setSlice(tempValue.m_data.get(),region);    getReady()->setSlice(tempValue.m_data.get(),region);
2169  }  }
2170    
2171  void  void
2172  Data::typeMatchLeft(Data& right) const  Data::typeMatchLeft(Data& right) const
2173  {  {
2174      if (right.isLazy() && !isLazy())
2175      {
2176        right.resolve();
2177      }
2178    if (isExpanded()){    if (isExpanded()){
2179      right.expand();      right.expand();
2180    } else if (isTagged()) {    } else if (isTagged()) {
# Line 2047  Data::typeMatchLeft(Data& right) const Line 2187  Data::typeMatchLeft(Data& right) const
2187  void  void
2188  Data::typeMatchRight(const Data& right)  Data::typeMatchRight(const Data& right)
2189  {  {
2190      if (isLazy() && !right.isLazy())
2191      {
2192        resolve();
2193      }
2194    if (isTagged()) {    if (isTagged()) {
2195      if (right.isExpanded()) {      if (right.isExpanded()) {
2196        expand();        expand();
# Line 2060  Data::typeMatchRight(const Data& right) Line 2204  Data::typeMatchRight(const Data& right)
2204    }    }
2205  }  }
2206    
2207  /* TODO */  void
2208  /* global reduction */  Data::setTaggedValueByName(std::string name,
2209                               const boost::python::object& value)
2210    {
2211         if (getFunctionSpace().getDomain()->isValidTagName(name)) {
2212        FORCERESOLVE;
2213            int tagKey=getFunctionSpace().getDomain()->getTag(name);
2214            setTaggedValue(tagKey,value);
2215         }
2216    }
2217  void  void
2218  Data::setTaggedValue(int tagKey,  Data::setTaggedValue(int tagKey,
2219                       const boost::python::object& value)                       const boost::python::object& value)
# Line 2071  Data::setTaggedValue(int tagKey, Line 2223  Data::setTaggedValue(int tagKey,
2223    }    }
2224    //    //
2225    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
2226    tag();    FORCERESOLVE;
2227      if (isConstant()) tag();
2228      numeric::array asNumArray(value);
2229    
2230    if (!isTagged()) {    // extract the shape of the numarray
2231      throw DataException("Error - DataTagged conversion failed!!");    DataTypes::ShapeType tempShape;
2232      for (int i=0; i < asNumArray.getrank(); i++) {
2233        tempShape.push_back(extract<int>(asNumArray.getshape()[i]));
2234    }    }
2235    
2236    //    DataVector temp_data2;
2237    // Construct DataArray from boost::python::object input value    temp_data2.copyFromNumArray(asNumArray,1);
   DataArray valueDataArray(value);  
2238    
2239    //    m_data->setTaggedValue(tagKey,tempShape, temp_data2);
   // Call DataAbstract::setTaggedValue  
   m_data->setTaggedValue(tagKey,valueDataArray.getView());  
2240  }  }
2241    
2242  /* TODO */  
 /* global reduction */  
2243  void  void
2244  Data::setTaggedValueFromCPP(int tagKey,  Data::setTaggedValueFromCPP(int tagKey,
2245                              const DataArrayView& value)                  const DataTypes::ShapeType& pointshape,
2246                                const DataTypes::ValueType& value,
2247                    int dataOffset)
2248  {  {
2249    if (isProtected()) {    if (isProtected()) {
2250          throw DataException("Error - attempt to update protected Data object.");          throw DataException("Error - attempt to update protected Data object.");
2251    }    }
2252    //    //
2253    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
2254    tag();    FORCERESOLVE;
2255      if (isConstant()) tag();
   if (!isTagged()) {  
     throw DataException("Error - DataTagged conversion failed!!");  
   }  
                                                                                                                 
2256    //    //
2257    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
2258    m_data->setTaggedValue(tagKey,value);    m_data->setTaggedValue(tagKey,pointshape, value, dataOffset);
2259  }  }
2260    
 /* TODO */  
 /* global reduction */  
2261  int  int
2262  Data::getTagNumber(int dpno)  Data::getTagNumber(int dpno)
2263  {  {
2264    return m_data->getTagNumber(dpno);    if (isEmpty())
2265  }    {
2266        throw DataException("Error - operation not permitted on instances of DataEmpty.");
 /* TODO */  
 /* global reduction */  
 void  
 Data::setRefValue(int ref,  
                   const boost::python::numeric::array& value)  
 {  
   if (isProtected()) {  
         throw DataException("Error - attempt to update protected Data object.");  
2267    }    }
2268    //    return getFunctionSpace().getTagFromDataPointNo(dpno);
   // Construct DataArray from boost::python::object input value  
   DataArray valueDataArray(value);  
   
   //  
   // Call DataAbstract::setRefValue  
   m_data->setRefValue(ref,valueDataArray);  
2269  }  }
2270    
 /* TODO */  
 /* global reduction */  
 void  
 Data::getRefValue(int ref,  
                   boost::python::numeric::array& value)  
 {  
   //  
   // Construct DataArray for boost::python::object return value  
   DataArray valueDataArray(value);  
2271    
2272    //  ostream& escript::operator<<(ostream& o, const Data& data)
2273    // Load DataArray with values from data-points specified by ref  {
2274    m_data->getRefValue(ref,valueDataArray);    o << data.toString();
2275      return o;
2276    //  }
   // Load values from valueDataArray into return numarray  
2277    
2278    // extract the shape of the numarray  Data
2279    int rank = value.getrank();  escript::C_GeneralTensorProduct(Data& arg_0,
2280    DataArrayView::ShapeType shape;                       Data& arg_1,
2281    for (int i=0; i < rank; i++) {                       int axis_offset,
2282      shape.push_back(extract<int>(value.getshape()[i]));                       int transpose)
2283    {
2284      // General tensor product: res(SL x SR) = arg_0(SL x SM) * arg_1(SM x SR)
2285      // SM is the product of the last axis_offset entries in arg_0.getShape().
2286    
2287      // deal with any lazy data
2288    //   if (arg_0.isLazy()) {arg_0.resolve();}
2289    //   if (arg_1.isLazy()) {arg_1.resolve();}
2290      if (arg_0.isLazy() || arg_1.isLazy())
2291      {
2292        DataLazy* c=new DataLazy(arg_0.borrowDataPtr(), arg_1.borrowDataPtr(), PROD, axis_offset,transpose);
2293        return Data(c);
2294    }    }
2295    
2296    // and load the numarray with the data from the DataArray    // Interpolate if necessary and find an appropriate function space
2297    DataArrayView valueView = valueDataArray.getView();    Data arg_0_Z, arg_1_Z;
2298      if (arg_0.getFunctionSpace()!=arg_1.getFunctionSpace()) {
2299    if (rank==0) {      if (arg_0.probeInterpolation(arg_1.getFunctionSpace())) {
2300        boost::python::numeric::array temp_numArray(valueView());        arg_0_Z = arg_0.interpolate(arg_1.getFunctionSpace());
2301        value = temp_numArray;        arg_1_Z = Data(arg_1);
2302    }      }
2303    if (rank==1) {      else if (arg_1.probeInterpolation(arg_0.getFunctionSpace())) {
2304      for (int i=0; i < shape[0]; i++) {        arg_1_Z=arg_1.interpolate(arg_0.getFunctionSpace());
2305        value[i] = valueView(i);        arg_0_Z =Data(arg_0);
2306      }      }
2307    }      else {
2308    if (rank==2) {        throw DataException("Error - C_GeneralTensorProduct: arguments have incompatible function spaces.");
     for (int i=0; i < shape[0]; i++) {  
       for (int j=0; j < shape[1]; j++) {  
         value[i][j] = valueView(i,j);  
       }  
2309      }      }
2310      } else {
2311          arg_0_Z = Data(arg_0);
2312          arg_1_Z = Data(arg_1);
2313    }    }
2314    if (rank==3) {    // Get rank and shape of inputs
2315      for (int i=0; i < shape[0]; i++) {    int rank0 = arg_0_Z.getDataPointRank();
2316        for (int j=0; j < shape[1]; j++) {    int rank1 = arg_1_Z.getDataPointRank();
2317          for (int k=0; k < shape[2]; k++) {    const DataTypes::ShapeType& shape0 = arg_0_Z.getDataPointShape();
2318            value[i][j][k] = valueView(i,j,k);    const DataTypes::ShapeType& shape1 = arg_1_Z.getDataPointShape();
2319          }  
2320        }    // Prepare for the loops of the product and verify compatibility of shapes
2321      int start0=0, start1=0;
2322      if (transpose == 0)       {}
2323      else if (transpose == 1)  { start0 = axis_offset; }
2324      else if (transpose == 2)  { start1 = rank1-axis_offset; }
2325      else              { throw DataException("C_GeneralTensorProduct: Error - transpose should be 0, 1 or 2"); }
2326    
2327    
2328      // Adjust the shapes for transpose
2329      DataTypes::ShapeType tmpShape0(rank0);    // pre-sizing the vectors rather
2330      DataTypes::ShapeType tmpShape1(rank1);    // than using push_back
2331      for (int i=0; i<rank0; i++)   { tmpShape0[i]=shape0[(i+start0)%rank0]; }
2332      for (int i=0; i<rank1; i++)   { tmpShape1[i]=shape1[(i+start1)%rank1]; }
2333    
2334    #if 0
2335      // For debugging: show shape after transpose
2336      char tmp[100];
2337      std::string shapeStr;
2338      shapeStr = "(";
2339      for (int i=0; i<rank0; i++)   { sprintf(tmp, "%d,", tmpShape0[i]); shapeStr += tmp; }
2340      shapeStr += ")";
2341      cout << "C_GeneralTensorProduct: Shape of arg0 is " << shapeStr << endl;
2342      shapeStr = "(";
2343      for (int i=0; i<rank1; i++)   { sprintf(tmp, "%d,", tmpShape1[i]); shapeStr += tmp; }
2344      shapeStr += ")";
2345      cout << "C_GeneralTensorProduct: Shape of arg1 is " << shapeStr << endl;
2346    #endif
2347    
2348      // Prepare for the loops of the product
2349      int SL=1, SM=1, SR=1;
2350      for (int i=0; i<rank0-axis_offset; i++)   {
2351        SL *= tmpShape0[i];
2352      }
2353      for (int i=rank0-axis_offset; i<rank0; i++)   {
2354        if (tmpShape0[i] != tmpShape1[i-(rank0-axis_offset)]) {
2355          throw DataException("C_GeneralTensorProduct: Error - incompatible shapes");
2356        }
2357        SM *= tmpShape0[i];
2358      }
2359      for (int i=axis_offset; i<rank1; i++)     {
2360        SR *= tmpShape1[i];
2361      }
2362    
2363      // Define the shape of the output (rank of shape is the sum of the loop ranges below)
2364      DataTypes::ShapeType shape2(rank0+rank1-2*axis_offset);  
2365      {         // block to limit the scope of out_index
2366         int out_index=0;
2367         for (int i=0; i<rank0-axis_offset; i++, ++out_index) { shape2[out_index]=tmpShape0[i]; } // First part of arg_0_Z
2368         for (int i=axis_offset; i<rank1; i++, ++out_index)   { shape2[out_index]=tmpShape1[i]; } // Last part of arg_1_Z
2369      }
2370    
2371      if (shape2.size()>ESCRIPT_MAX_DATA_RANK)
2372      {
2373         ostringstream os;
2374         os << "C_GeneralTensorProduct: Error - Attempt to create a rank " << shape2.size() << " object. The maximum rank is " << ESCRIPT_MAX_DATA_RANK << ".";
2375         throw DataException(os.str());
2376      }
2377    
2378      // Declare output Data object
2379      Data res;
2380    
2381      if      (arg_0_Z.isConstant()   && arg_1_Z.isConstant()) {
2382        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataConstant output
2383        double *ptr_0 = &(arg_0_Z.getDataAtOffset(0));
2384        double *ptr_1 = &(arg_1_Z.getDataAtOffset(0));
2385        double *ptr_2 = &(res.getDataAtOffset(0));
2386        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2387      }
2388      else if (arg_0_Z.isConstant()   && arg_1_Z.isTagged()) {
2389    
2390        // Prepare the DataConstant input
2391        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2392        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2393    
2394        // Borrow DataTagged input from Data object
2395        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2396        if (tmp_1==0) { throw DataException("GTP_1 Programming error - casting to DataTagged."); }
2397    
2398        // Prepare a DataTagged output 2
2399        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataTagged output
2400        res.tag();
2401        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2402        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2403    
2404        // Prepare offset into DataConstant
2405        int offset_0 = tmp_0->getPointOffset(0,0);
2406        double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2407        // Get the views
2408    //     DataArrayView view_1 = tmp_1->getDefaultValue();
2409    //     DataArrayView view_2 = tmp_2->getDefaultValue();
2410    //     // Get the pointers to the actual data
2411    //     double *ptr_1 = &((view_1.getData())[0]);
2412    //     double *ptr_2 = &((view_2.getData())[0]);
2413    
2414        double *ptr_1 = &(tmp_1->getDefaultValue(0));
2415        double *ptr_2 = &(tmp_2->getDefaultValue(0));
2416    
2417    
2418        // Compute an MVP for the default
2419        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2420        // Compute an MVP for each tag
2421        const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2422        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2423        for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2424          tmp_2->addTag(i->first);
2425    //       DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2426    //       DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2427    //       double *ptr_1 = &view_1.getData(0);
2428    //       double *ptr_2 = &view_2.getData(0);
2429    
2430          double *ptr_1 = &(tmp_1->getDataByTag(i->first,0));
2431          double *ptr_2 = &(tmp_2->getDataByTag(i->first,0));
2432        
2433          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2434      }      }
2435    
2436    }    }
2437    if (rank==4) {    else if (arg_0_Z.isConstant()   && arg_1_Z.isExpanded()) {
2438      for (int i=0; i < shape[0]; i++) {  
2439        for (int j=0; j < shape[1]; j++) {      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2440          for (int k=0; k < shape[2]; k++) {      DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2441            for (int l=0; l < shape[3]; l++) {      DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2442              value[i][j][k][l] = valueView(i,j,k,l);      DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2443            }      if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2444          }      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2445        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2446        int sampleNo_1,dataPointNo_1;
2447        int numSamples_1 = arg_1_Z.getNumSamples();
2448        int numDataPointsPerSample_1 = arg_1_Z.getNumDataPointsPerSample();
2449        int offset_0 = tmp_0->getPointOffset(0,0);
2450        #pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)
2451        for (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {
2452          for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {
2453            int offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);
2454            int offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);
2455            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2456            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2457            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2458            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2459        }        }
2460      }      }
2461    
2462    }    }
2463      else if (arg_0_Z.isTagged()     && arg_1_Z.isConstant()) {
2464    
2465  }      // Borrow DataTagged input from Data object
2466        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2467        if (tmp_0==0) { throw DataException("GTP_0 Programming error - casting to DataTagged."); }
2468    
2469  void      // Prepare the DataConstant input
2470  Data::archiveData(const std::string fileName)      DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2471  {      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
   cout << "Archiving Data object to: " << fileName << endl;  
2472    
2473    //      // Prepare a DataTagged output 2
2474    // Determine type of this Data object      res = Data(0.0, shape2, arg_0_Z.getFunctionSpace());    // DataTagged output
2475    int dataType = -1;      res.tag();
2476        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2477        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2478    
2479    if (isEmpty()) {      // Prepare offset into DataConstant
2480      dataType = 0;      int offset_1 = tmp_1->getPointOffset(0,0);
2481      cout << "\tdataType: DataEmpty" << endl;      double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2482    }      // Get the views
2483    if (isConstant()) {  //     DataArrayView view_0 = tmp_0->getDefaultValue();
2484      dataType = 1;  //     DataArrayView view_2 = tmp_2->getDefaultValue();
2485      cout << "\tdataType: DataConstant" << endl;  //     // Get the pointers to the actual data
2486    }  //     double *ptr_0 = &((view_0.getData())[0]);
2487    if (isTagged()) {  //     double *ptr_2 = &((view_2.getData())[0]);
     dataType = 2;  
     cout << "\tdataType: DataTagged" << endl;  
   }  
   if (isExpanded()) {  
     dataType = 3;  
     cout << "\tdataType: DataExpanded" << endl;  
   }  
2488    
2489    if (dataType == -1) {      double *ptr_0 = &(tmp_0->getDefaultValue(0));
2490      throw DataException("archiveData Error: undefined dataType");      double *ptr_2 = &(tmp_2->getDefaultValue(0));
   }  
2491    
2492    //      // Compute an MVP for the default
2493    // Collect data items common to all Data types      matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2494    int noSamples = getNumSamples();      // Compute an MVP for each tag
2495    int noDPPSample = getNumDataPointsPerSample();      const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2496    int functionSpaceType = getFunctionSpace().getTypeCode();      DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2497    int dataPointRank = getDataPointRank();      for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2498    int dataPointSize = getDataPointSize();  //      tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2499    int dataLength = getLength();  //       DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2500    DataArrayView::ShapeType dataPointShape = getDataPointShape();  //       DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2501    vector<int> referenceNumbers(noSamples);  //       double *ptr_0 = &view_0.getData(0);
2502    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  //       double *ptr_2 = &view_2.getData(0);
2503      referenceNumbers[sampleNo] = getFunctionSpace().getReferenceNoFromSampleNo(sampleNo);  
2504    }        tmp_2->addTag(i->first);
2505    vector<int> tagNumbers(noSamples);        double *ptr_0 = &(tmp_0->getDataByTag(i->first,0));
2506    if (isTagged()) {        double *ptr_2 = &(tmp_2->getDataByTag(i->first,0));
2507      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
       tagNumbers[sampleNo] = getFunctionSpace().getTagFromSampleNo(sampleNo);  
2508      }      }
2509    
2510    }    }
2511      else if (arg_0_Z.isTagged()     && arg_1_Z.isTagged()) {
2512    
2513    cout << "\tnoSamples: " << noSamples << " noDPPSample: " << noDPPSample << endl;      // Borrow DataTagged input from Data object
2514    cout << "\tfunctionSpaceType: " << functionSpaceType << endl;      DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2515    cout << "\trank: " << dataPointRank << " size: " << dataPointSize << " length: " << dataLength << endl;      if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2516    
2517    //      // Borrow DataTagged input from Data object
2518    // Flatten Shape to an array of integers suitable for writing to file      DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2519    int flatShape[4] = {0,0,0,0};      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
   cout << "\tshape: < ";  
   for (int dim=0; dim<dataPointRank; dim++) {  
     flatShape[dim] = dataPointShape[dim];  
     cout << dataPointShape[dim] << " ";  
   }  
   cout << ">" << endl;  
2520    
2521    //      // Prepare a DataTagged output 2
2522    // Open archive file      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());
2523    ofstream archiveFile;      res.tag();  // DataTagged output
2524    archiveFile.open(fileName.data(), ios::out);      DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2525        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2526    
2527    if (!archiveFile.good()) {  //     // Get the views
2528      throw DataException("archiveData Error: problem opening archive file");  //     DataArrayView view_0 = tmp_0->getDefaultValue();
2529    }  //     DataArrayView view_1 = tmp_1->getDefaultValue();
2530    //     DataArrayView view_2 = tmp_2->getDefaultValue();
2531    //     // Get the pointers to the actual data
2532    //     double *ptr_0 = &((view_0.getData())[0]);
2533    //     double *ptr_1 = &((view_1.getData())[0]);
2534    //     double *ptr_2 = &((view_2.getData())[0]);
2535    
2536    //      double *ptr_0 = &(tmp_0->getDefaultValue(0));
2537    // Write common data items to archive file      double *ptr_1 = &(tmp_1->getDefaultValue(0));
2538    archiveFile.write(reinterpret_cast<char *>(&dataType),sizeof(int));      double *ptr_2 = &(tmp_2->getDefaultValue(0));
   archiveFile.write(reinterpret_cast<char *>(&noSamples),sizeof(int));  
   archiveFile.write(reinterpret_cast<char *>(&noDPPSample),sizeof(int));  
   archiveFile.write(reinterpret_cast<char *>(&functionSpaceType),sizeof(int));  
   archiveFile.write(reinterpret_cast<char *>(&dataPointRank),sizeof(int));  
   archiveFile.write(reinterpret_cast<char *>(&dataPointSize),sizeof(int));  
   archiveFile.write(reinterpret_cast<char *>(&dataLength),sizeof(int));  
   for (int dim = 0; dim < 4; dim++) {  
     archiveFile.write(reinterpret_cast<char *>(&flatShape[dim]),sizeof(int));  
   }  
   for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  
     archiveFile.write(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));  
   }  
   if (isTagged()) {  
     for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  
       archiveFile.write(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));  
     }  
   }  
2539    
   if (!archiveFile.good()) {  
     throw DataException("archiveData Error: problem writing to archive file");  
   }  
2540    
2541    //      // Compute an MVP for the default
2542    // Archive underlying data values for each Data type      matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2543    int noValues;      // Merge the tags
2544    switch (dataType) {      DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2545      case 0:      const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2546        // DataEmpty      const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2547        noValues = 0;      for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2548        archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));        tmp_2->addTag(i->first); // use tmp_2 to get correct shape
2549        cout << "\tnoValues: " << noValues << endl;      }
2550        break;      for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2551      case 1:        tmp_2->addTag(i->first);
2552        // DataConstant      }
2553        noValues = m_data->getLength();      // Compute an MVP for each tag
2554        archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));      const DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();
2555        cout << "\tnoValues: " << noValues << endl;      for (i=lookup_2.begin();i!=lookup_2.end();i++) {
2556        if (m_data->archiveData(archiveFile,noValues)) {  //       DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2557          throw DataException("archiveData Error: problem writing data to archive file");  //       DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2558        }  //       DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2559        break;  //       double *ptr_0 = &view_0.getData(0);
2560      case 2:  //       double *ptr_1 = &view_1.getData(0);
2561        // DataTagged  //       double *ptr_2 = &view_2.getData(0);
       noValues = m_data->getLength();  
       archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));  
       cout << "\tnoValues: " << noValues << endl;  
       if (m_data->archiveData(archiveFile,noValues)) {  
         throw DataException("archiveData Error: problem writing data to archive file");  
       }  
       break;  
     case 3:  
       // DataExpanded  
       noValues = m_data->getLength();  
       archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));  
       cout << "\tnoValues: " << noValues << endl;  
       if (m_data->archiveData(archiveFile,noValues)) {  
         throw DataException("archiveData Error: problem writing data to archive file");  
       }  
       break;  
   }  
2562    
2563    if (!archiveFile.good()) {        double *ptr_0 = &(tmp_0->getDataByTag(i->first,0));
2564      throw DataException("archiveData Error: problem writing data to archive file");        double *ptr_1 = &(tmp_1->getDataByTag(i->first,0));
2565    }        double *ptr_2 = &(tmp_2->getDataByTag(i->first,0));
2566    
2567    //        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2568    // Close archive file      }
   archiveFile.close();  
2569    
   if (!archiveFile.good()) {  
     throw DataException("archiveData Error: problem closing archive file");  
2570    }    }
2571      else if (arg_0_Z.isTagged()     && arg_1_Z.isExpanded()) {
2572    
2573  }      // After finding a common function space above the two inputs have the same numSamples and num DPPS
2574        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2575        DataTagged*   tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2576        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2577        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2578        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2579        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2580        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2581        int sampleNo_0,dataPointNo_0;
2582        int numSamples_0 = arg_0_Z.getNumSamples();
2583        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2584        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2585        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2586          int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0
2587          double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2588          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2589            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2590            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2591            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2592            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2593            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2594          }
2595        }
2596    
 void  
 Data::extractData(const std::string fileName,  
                   const FunctionSpace& fspace)  
 {  
   //  
   // Can only extract Data to an object which is initially DataEmpty  
   if (!isEmpty()) {  
     throw DataException("extractData Error: can only extract to DataEmpty object");  
2597    }    }
2598      else if (arg_0_Z.isExpanded()   && arg_1_Z.isConstant()) {
2599    
2600    cout << "Extracting Data object from: " << fileName << endl;      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2601        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2602    int dataType;      DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2603    int noSamples;      DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2604    int noDPPSample;      if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2605    int functionSpaceType;      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2606    int dataPointRank;      if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2607    int dataPointSize;      int sampleNo_0,dataPointNo_0;
2608    int dataLength;      int numSamples_0 = arg_0_Z.getNumSamples();
2609    DataArrayView::ShapeType dataPointShape;      int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2610    int flatShape[4];      int offset_1 = tmp_1->getPointOffset(0,0);
2611        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2612        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2613          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2614            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2615            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2616            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2617            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2618            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2619            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2620          }
2621        }
2622    
   //  
   // Open the archive file  
   ifstream archiveFile;  
   archiveFile.open(fileName.data(), ios::in);  
2623    
   if (!archiveFile.good()) {  
     throw DataException("extractData Error: problem opening archive file");  
2624    }    }
2625      else if (arg_0_Z.isExpanded()   && arg_1_Z.isTagged()) {
2626    
2627    //      // After finding a common function space above the two inputs have the same numSamples and num DPPS
2628    // Read common data items from archive file      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2629    archiveFile.read(reinterpret_cast<char *>(&dataType),sizeof(int));      DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2630    archiveFile.read(reinterpret_cast<char *>(&noSamples),sizeof(int));      DataTagged*   tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2631    archiveFile.read(reinterpret_cast<char *>(&noDPPSample),sizeof(int));      DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2632    archiveFile.read(reinterpret_cast<char *>(&functionSpaceType),sizeof(int));      if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2633    archiveFile.read(reinterpret_cast<char *>(&dataPointRank),sizeof(int));      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2634    archiveFile.read(reinterpret_cast<char *>(&dataPointSize),sizeof(int));      if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2635    archiveFile.read(reinterpret_cast<char *>(&dataLength),sizeof(int));      int sampleNo_0,dataPointNo_0;
2636    for (int dim = 0; dim < 4; dim++) {      int numSamples_0 = arg_0_Z.getNumSamples();
2637      archiveFile.read(reinterpret_cast<char *>(&flatShape[dim]),sizeof(int));      int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2638      if (flatShape[dim]>0) {      #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2639        dataPointShape.push_back(flatShape[dim]);      for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2640          int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);
2641          double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2642          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2643            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2644            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2645            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2646            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2647            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2648          }
2649      }      }
2650    
2651    }    }
2652    vector<int> referenceNumbers(noSamples);    else if (arg_0_Z.isExpanded()   && arg_1_Z.isExpanded()) {
2653    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  
2654      archiveFile.read(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));      // After finding a common function space above the two inputs have the same numSamples and num DPPS
2655    }      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2656    vector<int> tagNumbers(noSamples);      DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2657    if (dataType==2) {      DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2658      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2659        archiveFile.read(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));      if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2660        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2661        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2662        int sampleNo_0,dataPointNo_0;
2663        int numSamples_0 = arg_0_Z.getNumSamples();
2664        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2665        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2666        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2667          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2668            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2669            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2670            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2671            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2672            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2673            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2674            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2675          }
2676      }      }
   }  
2677    
   if (!archiveFile.good()) {  
     throw DataException("extractData Error: problem reading from archive file");  
2678    }    }
2679      else {
2680    //      throw DataException("Error - C_GeneralTensorProduct: unknown combination of inputs");
   // Verify the values just read from the archive file  
   switch (dataType) {  
     case 0:  
       cout << "\tdataType: DataEmpty" << endl;  
       break;  
     case 1:  
       cout << "\tdataType: DataConstant" << endl;  
       break;  
     case 2:  
       cout << "\tdataType: DataTagged" << endl;  
       break;  
     case 3:  
       cout << "\tdataType: DataExpanded" << endl;  
       break;  
     default:  
       throw DataException("extractData Error: undefined dataType read from archive file");  
       break;  
2681    }    }
2682    
2683    cout << "\tnoSamples: " << noSamples << " noDPPSample: " << noDPPSample << endl;    return res;
2684    cout << "\tfunctionSpaceType: " << functionSpaceType << endl;  }
   cout << "\trank: " << dataPointRank << " size: " << dataPointSize << " length: " << dataLength << endl;  
   cout << "\tshape: < ";  
   for (int dim = 0; dim < dataPointRank; dim++) {  
     cout << dataPointShape[dim] << " ";  
   }  
   cout << ">" << endl;  
2685    
2686    //  DataAbstract*
2687    // Verify that supplied FunctionSpace object is compatible with this Data object.  Data::borrowData() const
2688    if ( (fspace.getTypeCode()!=functionSpaceType) ||  {
2689         (fspace.getNumSamples()!=noSamples) ||    return m_data.get();
2690         (fspace.getNumDPPSample()!=noDPPSample)  }
2691       ) {  
2692      throw DataException("extractData Error: incompatible FunctionSpace");  // Not all that happy about returning a non-const from a const
2693    }  DataAbstract_ptr
2694    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  Data::borrowDataPtr() const
2695      if (referenceNumbers[sampleNo] != fspace.getReferenceNoFromSampleNo(sampleNo)) {  {
2696        throw DataException("extractData Error: incompatible FunctionSpace");    return m_data;
2697      }  }
2698    }  
2699    if (dataType==2) {  // Not all that happy about returning a non-const from a const
2700      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  DataReady_ptr
2701        if (tagNumbers[sampleNo] != fspace.getTagFromSampleNo(sampleNo)) {  Data::borrowReadyPtr() const
2702          throw DataException("extractData Error: incompatible FunctionSpace");  {
2703        }     DataReady_ptr dr=dynamic_pointer_cast<DataReady>(m_data);
2704       EsysAssert((dr!=0), "Error - casting to DataReady.");
2705       return dr;
2706    }
2707    
2708    std::string
2709    Data::toString() const
2710    {
2711        if (!m_data->isEmpty() &&
2712        !m_data->isLazy() &&
2713        getLength()>escriptParams.getInt("TOO_MANY_LINES"))
2714        {
2715        stringstream temp;
2716        temp << "Summary: inf="<< inf_const() << " sup=" << sup_const() << " data points=" << getNumDataPoints();
2717        return  temp.str();
2718      }      }
2719    }      return m_data->toString();
2720    }
2721    
   //  
   // Construct a DataVector to hold underlying data values  
   DataVector dataVec(dataLength);  
2722    
   //  
   // Load this DataVector with the appropriate values  
   int noValues;  
   archiveFile.read(reinterpret_cast<char *>(&noValues),sizeof(int));  
   cout << "\tnoValues: " << noValues << endl;  
   switch (dataType) {  
     case 0:  
       // DataEmpty  
       if (noValues != 0) {  
         throw DataException("extractData Error: problem reading data from archive file");  
       }  
       break;  
     case 1:  
       // DataConstant  
       if (dataVec.extractData(archiveFile,noValues)) {  
         throw DataException("extractData Error: problem reading data from archive file");  
       }  
       break;  
     case 2:  
       // DataTagged  
       if (dataVec.extractData(archiveFile,noValues)) {  
         throw DataException("extractData Error: problem reading data from archive file");  
       }  
       break;  
     case 3:  
       // DataExpanded  
       if (dataVec.extractData(archiveFile,noValues)) {  
         throw DataException("extractData Error: problem reading data from archive file");  
       }  
       break;  
   }  
2723    
2724    if (!archiveFile.good()) {  DataTypes::ValueType::const_reference
2725      throw DataException("extractData Error: problem reading from archive file");  Data::getDataAtOffset(DataTypes::ValueType::size_type i) const
2726    }  {
2727        if (isLazy())
2728        {
2729        throw DataException("Programmer error - getDataAtOffset not permitted on lazy data (object is const which prevents resolving).");
2730        }
2731        return getReady()->getDataAtOffset(i);
2732    }
2733    
   //  
   // Close archive file  
   archiveFile.close();  
2734    
2735    if (!archiveFile.good()) {  DataTypes::ValueType::reference
2736      throw DataException("extractData Error: problem closing archive file");  Data::getDataAtOffset(DataTypes::ValueType::size_type i)
2737    }  {
2738    //     if (isLazy())
2739    //     {
2740    //  throw DataException("getDataAtOffset not permitted on lazy data.");
2741    //     }
2742        FORCERESOLVE;
2743        return getReady()->getDataAtOffset(i);
2744    }
2745    
2746    //  DataTypes::ValueType::const_reference
2747    // Construct an appropriate Data object  Data::getDataPoint(int sampleNo, int dataPointNo) const
2748    DataAbstract* tempData;  {
2749    switch (dataType) {    if (!isReady())
2750      case 0:    {
2751        // DataEmpty      throw DataException("Programmer error - getDataPoint() not permitted on Lazy Data (object is const which prevents resolving).");
2752        tempData=new DataEmpty();    }
2753        break;    else
2754      case 1:    {
2755        // DataConstant      const DataReady* dr=getReady();
2756        tempData=new DataConstant(fspace,dataPointShape,dataVec);      return dr->getDataAtOffset(dr->getPointOffset(sampleNo, dataPointNo));
       break;  
     case 2:  
       // DataTagged  
       tempData=new DataTagged(fspace,dataPointShape,tagNumbers,dataVec);  
       break;  
     case 3:  
       // DataExpanded  
       tempData=new DataExpanded(fspace,dataPointShape,dataVec);  
       break;  
2757    }    }
   shared_ptr<DataAbstract> temp_data(tempData);  
   m_data=temp_data;  
2758  }  }
2759    
2760  ostream& escript::operator<<(ostream& o, const Data& data)  
2761    DataTypes::ValueType::reference
2762    Data::getDataPoint(int sampleNo, int dataPointNo)
2763  {  {
2764    o << data.toString();    FORCERESOLVE;
2765    return o;    if (!isReady())
2766      {
2767        throw DataException("Programmer error - getDataPoint() not permitted on Lazy Data.");
2768      }
2769      else
2770      {
2771        DataReady* dr=getReady();
2772        return dr->getDataAtOffset(dr->getPointOffset(sampleNo, dataPointNo));
2773      }
2774  }  }
2775    
2776    
2777  /* Member functions specific to the MPI implementation */  /* Member functions specific to the MPI implementation */
2778    
2779  void  void
2780  Data::print()  Data::print()
2781  {  {
2782    int i,j;    int i,j;
2783      
2784    printf( "Data is %dX%d\n", getNumSamples(), getNumDataPointsPerSample() );    printf( "Data is %dX%d\n", getNumSamples(), getNumDataPointsPerSample() );
2785    for( i=0; i<getNumSamples(); i++ )    for( i=0; i<getNumSamples(); i++ )
2786    {    {
# Line 2557  Data::print() Line 2790  Data::print()
2790      printf( "\n" );      printf( "\n" );
2791    }    }
2792  }  }
2793    void
2794    Data::dump(const std::string fileName) const
2795    {
2796      try
2797      {
2798        if (isLazy())
2799        {
2800          Data temp(*this); // this is to get a non-const object which we can resolve
2801          temp.resolve();
2802          temp.dump(fileName);
2803        }
2804        else
2805        {
2806              return m_data->dump(fileName);
2807        }
2808      }
2809      catch (exception& e)
2810      {
2811            cout << e.what() << endl;
2812      }
2813    }
2814    
2815  int  int
2816  Data::get_MPISize() const  Data::get_MPISize() const
2817  {  {
2818      int error, size;      int size;
2819  #ifdef PASO_MPI  #ifdef PASO_MPI
2820        int error;
2821      error = MPI_Comm_size( get_MPIComm(), &size );      error = MPI_Comm_size( get_MPIComm(), &size );
2822  #else  #else
2823      size = 1;      size = 1;
# Line 2573  Data::get_MPISize() const Line 2828  Data::get_MPISize() const
2828  int  int
2829  Data::get_MPIRank() const  Data::get_MPIRank() const
2830  {  {
2831      int error, rank;      int rank;
2832  #ifdef PASO_MPI  #ifdef PASO_MPI
2833        int error;
2834      error = MPI_Comm_rank( get_MPIComm(), &rank );      error = MPI_Comm_rank( get_MPIComm(), &rank );
2835  #else  #else
2836      rank = 0;      rank = 0;
# Line 2584  Data::get_MPIRank() const Line 2840  Data::get_MPIRank() const
2840    
2841  MPI_Comm  MPI_Comm
2842  Data::get_MPIComm() const  Data::get_MPIComm() const
2843  {  {
2844  #ifdef PASO_MPI  #ifdef PASO_MPI
2845      return MPI_COMM_WORLD;      return MPI_COMM_WORLD;
2846  #else  #else
# Line 2592  Data::get_MPIComm() const Line 2848  Data::get_MPIComm() const
2848  #endif  #endif
2849  }  }
2850    
2851    

Legend:
Removed from v.790  
changed lines
  Added in v.2146

  ViewVC Help
Powered by ViewVC 1.1.26