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

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

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

trunk/esys2/escript/src/Data/Data.cpp revision 123 by jgs, Fri Jul 8 04:08:13 2005 UTC trunk/escript/src/Data.cpp revision 1859 by gross, Wed Oct 8 03:03:37 2008 UTC
# Line 1  Line 1 
 // $Id$  
 /*=============================================================================  
1    
2   ******************************************************************************  /*******************************************************
3   *                                                                            *  *
4   *       COPYRIGHT ACcESS 2004 -  All Rights Reserved                         *  * Copyright (c) 2003-2008 by University of Queensland
5   *                                                                            *  * Earth Systems Science Computational Center (ESSCC)
6   * This software is the property of ACcESS.  No part of this code             *  * http://www.uq.edu.au/esscc
7   * may be copied in any form or by any means without the expressed written    *  *
8   * consent of ACcESS.  Copying, use or modification of this software          *  * Primary Business: Queensland, Australia
9   * by any unauthorised person is illegal unless that                          *  * Licensed under the Open Software License version 3.0
10   * person has a software license agreement with ACcESS.                       *  * http://www.opensource.org/licenses/osl-3.0.php
11   *                                                                            *  *
12   ******************************************************************************  *******************************************************/
13    
14    
15    #include "Data.h"
16    
17    #include "DataExpanded.h"
18    #include "DataConstant.h"
19    #include "DataTagged.h"
20    #include "DataEmpty.h"
21    #include "FunctionSpaceFactory.h"
22    #include "AbstractContinuousDomain.h"
23    #include "UnaryFuncs.h"
24    #include "FunctionSpaceException.h"
25    
26  ******************************************************************************/  extern "C" {
27    #include "escript/blocktimer.h"
28  #include "escript/Data/Data.h"  }
29    
 #include <iostream>  
30  #include <fstream>  #include <fstream>
31  #include <algorithm>  #include <algorithm>
32  #include <vector>  #include <vector>
 #include <exception>  
33  #include <functional>  #include <functional>
 #include <math.h>  
34    
35  #include <boost/python/str.hpp>  #include <boost/python/dict.hpp>
36  #include <boost/python/extract.hpp>  #include <boost/python/extract.hpp>
37  #include <boost/python/long.hpp>  #include <boost/python/long.hpp>
38    
 #include "escript/Data/DataException.h"  
 #include "escript/Data/DataExpanded.h"  
 #include "escript/Data/DataConstant.h"  
 #include "escript/Data/DataTagged.h"  
 #include "escript/Data/DataEmpty.h"  
 #include "escript/Data/DataArray.h"  
 #include "escript/Data/DataProf.h"  
 #include "escript/Data/FunctionSpaceFactory.h"  
 #include "escript/Data/AbstractContinuousDomain.h"  
 #include "escript/Data/UnaryFuncs.h"  
   
39  using namespace std;  using namespace std;
40  using namespace boost::python;  using namespace boost::python;
41  using namespace boost;  using namespace boost;
42  using namespace escript;  using namespace escript;
43    
 //  
 // global table of profiling data for all Data objects  
 DataProf dataProfTable;  
   
44  Data::Data()  Data::Data()
45  {  {
46    //    //
# Line 56  Data::Data() Line 48  Data::Data()
48    DataAbstract* temp=new DataEmpty();    DataAbstract* temp=new DataEmpty();
49    shared_ptr<DataAbstract> temp_data(temp);    shared_ptr<DataAbstract> temp_data(temp);
50    m_data=temp_data;    m_data=temp_data;
51    // create entry in global profiling table for this object    m_protected=false;
   profData = dataProfTable.newData();  
52  }  }
53    
54  Data::Data(double value,  Data::Data(double value,
# Line 65  Data::Data(double value, Line 56  Data::Data(double value,
56             const FunctionSpace& what,             const FunctionSpace& what,
57             bool expanded)             bool expanded)
58  {  {
59    DataArrayView::ShapeType dataPointShape;    DataTypes::ShapeType dataPointShape;
60    for (int i = 0; i < shape.attr("__len__")(); ++i) {    for (int i = 0; i < shape.attr("__len__")(); ++i) {
61      dataPointShape.push_back(extract<const int>(shape[i]));      dataPointShape.push_back(extract<const int>(shape[i]));
62    }    }
63    DataArray temp(dataPointShape,value);  
64    initialise(temp.getView(),what,expanded);    int len = DataTypes::noValues(dataPointShape);
65    // create entry in global profiling table for this object    DataVector temp_data(len,value,len);
66    profData = dataProfTable.newData();  //   DataArrayView temp_dataView(temp_data, dataPointShape);
67    
68    //   initialise(temp_dataView, what, expanded);
69      initialise(temp_data, dataPointShape, what, expanded);
70    
71      m_protected=false;
72  }  }
73    
74  Data::Data(double value,  Data::Data(double value,
75         const DataArrayView::ShapeType& dataPointShape,         const DataTypes::ShapeType& dataPointShape,
76         const FunctionSpace& what,         const FunctionSpace& what,
77             bool expanded)             bool expanded)
78  {  {
79    DataArray temp(dataPointShape,value);    int len = DataTypes::noValues(dataPointShape);
80    pair<int,int> dataShape=what.getDataShape();  
81    initialise(temp.getView(),what,expanded);    DataVector temp_data(len,value,len);
82    // create entry in global profiling table for this object  //   DataArrayView temp_dataView(temp_data, dataPointShape);
83    profData = dataProfTable.newData();  
84    //   initialise(temp_dataView, what, expanded);
85      initialise(temp_data, dataPointShape, what, expanded);
86    
87      m_protected=false;
88  }  }
89    
90  Data::Data(const Data& inData)  Data::Data(const Data& inData)
91  {  {
92    m_data=inData.m_data;    m_data=inData.m_data;
93    // create entry in global profiling table for this object    m_protected=inData.isProtected();
   profData = dataProfTable.newData();  
94  }  }
95    
96    
97  Data::Data(const Data& inData,  Data::Data(const Data& inData,
98             const DataArrayView::RegionType& region)             const DataTypes::RegionType& region)
99  {  {
100    //    //
101    // Create Data which is a slice of another Data    // Create Data which is a slice of another Data
102    DataAbstract* tmp = inData.m_data->getSlice(region);    DataAbstract* tmp = inData.m_data->getSlice(region);
103    shared_ptr<DataAbstract> temp_data(tmp);    shared_ptr<DataAbstract> temp_data(tmp);
104    m_data=temp_data;    m_data=temp_data;
105    // create entry in global profiling table for this object    m_protected=false;
   profData = dataProfTable.newData();  
106  }  }
107    
108  Data::Data(const Data& inData,  Data::Data(const Data& inData,
109             const FunctionSpace& functionspace)             const FunctionSpace& functionspace)
110  {  {
111      if (inData.isEmpty())
112      {
113        throw DataException("Error - will not interpolate for instances of DataEmpty.");
114      }
115    if (inData.getFunctionSpace()==functionspace) {    if (inData.getFunctionSpace()==functionspace) {
116      m_data=inData.m_data;      m_data=inData.m_data;
117      } else if (inData.isConstant()) { // for a constant function, we just need to use the new function space
118        if (!inData.probeInterpolation(functionspace))
119        {           // Even though this is constant, we still need to check whether interpolation is allowed
120        throw FunctionSpaceException("Call to probeInterpolation returned false for DataConstant.");
121        }
122        DataConstant* dc=new DataConstant(functionspace,inData.m_data->getShape(),inData.m_data->getVector());  
123        m_data=shared_ptr<DataAbstract>(dc);
124    } else {    } else {
125      Data tmp(0,inData.getPointDataView().getShape(),functionspace,true);      Data tmp(0,inData.getDataPointShape(),functionspace,true);
126      // Note: Must use a reference or pointer to a derived object      // Note: Must use a reference or pointer to a derived object
127      // in order to get polymorphic behaviour. Shouldn't really      // in order to get polymorphic behaviour. Shouldn't really
128      // be able to create an instance of AbstractDomain but that was done      // be able to create an instance of AbstractDomain but that was done
# Line 125  Data::Data(const Data& inData, Line 135  Data::Data(const Data& inData,
135      }      }
136      m_data=tmp.m_data;      m_data=tmp.m_data;
137    }    }
138    // create entry in global profiling table for this object    m_protected=false;
   profData = dataProfTable.newData();  
139  }  }
140    
141  Data::Data(const DataTagged::TagListType& tagKeys,  // Data::Data(const DataTagged::TagListType& tagKeys,
142             const DataTagged::ValueListType & values,  //            const DataTagged::ValueListType & values,
143             const DataArrayView& defaultValue,  //            const DataArrayView& defaultValue,
144             const FunctionSpace& what,  //            const FunctionSpace& what,
145             bool expanded)  //            bool expanded)
146    // {
147    //   DataAbstract* temp=new DataTagged(tagKeys,values,defaultValue,what);
148    //   shared_ptr<DataAbstract> temp_data(temp);
149    //   m_data=temp_data;
150    //   m_protected=false;
151    //   if (expanded) {
152    //     expand();
153    //   }
154    // }
155    
156    
157    
158    Data::Data(DataAbstract* underlyingdata)
159  {  {
160    DataAbstract* temp=new DataTagged(tagKeys,values,defaultValue,what);      m_data=shared_ptr<DataAbstract>(underlyingdata);
161    shared_ptr<DataAbstract> temp_data(temp);      m_protected=false;
   m_data=temp_data;  
   if (expanded) {  
     expand();  
   }  
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
162  }  }
163    
164  Data::Data(const numeric::array& value,  Data::Data(const numeric::array& value,
# Line 150  Data::Data(const numeric::array& value, Line 166  Data::Data(const numeric::array& value,
166             bool expanded)             bool expanded)
167  {  {
168    initialise(value,what,expanded);    initialise(value,what,expanded);
169    // create entry in global profiling table for this object    m_protected=false;
   profData = dataProfTable.newData();  
170  }  }
171    /*
172  Data::Data(const DataArrayView& value,  Data::Data(const DataArrayView& value,
173         const FunctionSpace& what,         const FunctionSpace& what,
174             bool expanded)             bool expanded)
175  {  {
176    initialise(value,what,expanded);    initialise(value,what,expanded);
177    // create entry in global profiling table for this object    m_protected=false;
178    profData = dataProfTable.newData();  }*/
179    
180    Data::Data(const DataTypes::ValueType& value,
181             const DataTypes::ShapeType& shape,
182                     const FunctionSpace& what,
183                     bool expanded)
184    {
185       initialise(value,shape,what,expanded);
186       m_protected=false;
187  }  }
188    
189    
190  Data::Data(const object& value,  Data::Data(const object& value,
191         const FunctionSpace& what,         const FunctionSpace& what,
192             bool expanded)             bool expanded)
193  {  {
194    numeric::array asNumArray(value);    numeric::array asNumArray(value);
195    initialise(asNumArray,what,expanded);    initialise(asNumArray,what,expanded);
196    // create entry in global profiling table for this object    m_protected=false;
   profData = dataProfTable.newData();  
197  }  }
198    
199    
200  Data::Data(const object& value,  Data::Data(const object& value,
201             const Data& other)             const Data& other)
202  {  {
203      numeric::array asNumArray(value);
204    
205      // extract the shape of the numarray
206      DataTypes::ShapeType tempShape=DataTypes::shapeFromNumArray(asNumArray);
207    // /*  for (int i=0; i < asNumArray.getrank(); i++) {
208    //     tempShape.push_back(extract<int>(asNumArray.getshape()[i]));
209    //   }*/
210    //   // get the space for the data vector
211    //   int len = DataTypes::noValues(tempShape);
212    //   DataVector temp_data(len, 0.0, len);
213    // /*  DataArrayView temp_dataView(temp_data, tempShape);
214    //   temp_dataView.copy(asNumArray);*/
215    //   temp_data.copyFromNumArray(asNumArray);
216    
217    //    //
218    // Create DataConstant using the given value and all other parameters    // Create DataConstant using the given value and all other parameters
219    // copied from other. If value is a rank 0 object this Data    // copied from other. If value is a rank 0 object this Data
220    // will assume the point data shape of other.    // will assume the point data shape of other.
221    DataArray temp(value);  
222    if (temp.getView().getRank()==0) {    if (DataTypes::getRank(tempShape)/*temp_dataView.getRank()*/==0) {
223      //  
224      // Create a DataArray with the scalar value for all elements  
225      DataArray temp2(other.getPointDataView().getShape(),temp.getView()());      // get the space for the data vector
226      initialise(temp2.getView(),other.getFunctionSpace(),false);      int len1 = DataTypes::noValues(tempShape);
227        DataVector temp_data(len1, 0.0, len1);
228        temp_data.copyFromNumArray(asNumArray);
229    
230        int len = DataTypes::noValues(other.getDataPointShape());
231    
232        DataVector temp2_data(len, temp_data[0]/*temp_dataView()*/, len);
233        //DataArrayView temp2_dataView(temp2_data, other.getPointDataView().getShape());
234    //     initialise(temp2_dataView, other.getFunctionSpace(), false);
235    
236        DataConstant* t=new DataConstant(other.getFunctionSpace(),other.getDataPointShape(),temp2_data);
237        boost::shared_ptr<DataAbstract> sp(t);
238        m_data=sp;
239    
240    
241    } else {    } else {
242      //      //
243      // Create a DataConstant with the same sample shape as other      // Create a DataConstant with the same sample shape as other
244      initialise(temp.getView(),other.getFunctionSpace(),false);  //     initialise(temp_dataView, other.getFunctionSpace(), false);
245        DataConstant* t=new DataConstant(asNumArray,other.getFunctionSpace());
246        boost::shared_ptr<DataAbstract> sp(t);
247        m_data=sp;
248      }
249      m_protected=false;
250    }
251    
252    Data::~Data()
253    {
254    
255    }
256    
257    
258    
259    void
260    Data::initialise(const boost::python::numeric::array& value,
261                     const FunctionSpace& what,
262                     bool expanded)
263    {
264      //
265      // Construct a Data object of the appropriate type.
266      // Construct the object first as there seems to be a bug which causes
267      // undefined behaviour if an exception is thrown during construction
268      // within the shared_ptr constructor.
269      if (expanded) {
270        DataAbstract* temp=new DataExpanded(value, what);
271        boost::shared_ptr<DataAbstract> temp_data(temp);
272        m_data=temp_data;
273      } else {
274        DataAbstract* temp=new DataConstant(value, what);
275        boost::shared_ptr<DataAbstract> temp_data(temp);
276        m_data=temp_data;
277      }
278    }
279    
280    
281    void
282    Data::initialise(const DataTypes::ValueType& value,
283             const DataTypes::ShapeType& shape,
284                     const FunctionSpace& what,
285                     bool expanded)
286    {
287      //
288      // Construct a Data object of the appropriate type.
289      // Construct the object first as there seems to be a bug which causes
290      // undefined behaviour if an exception is thrown during construction
291      // within the shared_ptr constructor.
292      if (expanded) {
293        DataAbstract* temp=new DataExpanded(what, shape, value);
294        boost::shared_ptr<DataAbstract> temp_data(temp);
295        m_data=temp_data;
296      } else {
297        DataAbstract* temp=new DataConstant(what, shape, value);
298        boost::shared_ptr<DataAbstract> temp_data(temp);
299        m_data=temp_data;
300    }    }
   // create entry in global profiling table for this object  
   profData = dataProfTable.newData();  
301  }  }
302    
303    
304    // void
305    // Data::CompareDebug(const Data& rd)
306    // {
307    //  using namespace std;
308    //  bool mismatch=false;
309    //  std::cout << "Comparing left and right" << endl;
310    //  const DataTagged* left=dynamic_cast<DataTagged*>(m_data.get());
311    //  const DataTagged* right=dynamic_cast<DataTagged*>(rd.m_data.get());
312    //  
313    //  if (left==0)
314    //  {
315    //      cout << "left arg is not a DataTagged\n";
316    //      return;
317    //  }
318    //  
319    //  if (right==0)
320    //  {
321    //      cout << "right arg is not a DataTagged\n";
322    //      return;
323    //  }
324    //  cout << "Num elements=" << left->getVector().size() << ":" << right->getVector().size() << std::endl;
325    //  cout << "Shapes ";
326    //  if (left->getShape()==right->getShape())
327    //  {
328    //      cout << "ok\n";
329    //  }
330    //  else
331    //  {
332    //      cout << "Problem: shapes do not match\n";
333    //      mismatch=true;
334    //  }
335    //  int lim=left->getVector().size();
336    //  if (right->getVector().size()) lim=right->getVector().size();
337    //  for (int i=0;i<lim;++i)
338    //  {
339    //      if (left->getVector()[i]!=right->getVector()[i])
340    //      {
341    //          cout << "[" << i << "] value mismatch " << left->getVector()[i] << ":" << right->getVector()[i] << endl;
342    //          mismatch=true;
343    //      }
344    //  }
345    //
346    //  // still need to check the tag map
347    //  // also need to watch what is happening to function spaces, are they copied or what?
348    //
349    //  const DataTagged::DataMapType& mapleft=left->getTagLookup();
350    //  const DataTagged::DataMapType& mapright=right->getTagLookup();
351    //
352    //  if (mapleft.size()!=mapright.size())
353    //  {
354    //      cout << "Maps are different sizes " << mapleft.size() << ":" << mapright.size() << endl;
355    //      mismatch=true;
356    //      cout << "Left map\n";
357    //      DataTagged::DataMapType::const_iterator i,j;
358    //      for (i=mapleft.begin();i!=mapleft.end();++i) {
359    //          cout << "(" << i->first << "=>" << i->second << ")\n";
360    //      }
361    //      cout << "Right map\n";
362    //      for (i=mapright.begin();i!=mapright.end();++i) {
363    //          cout << "(" << i->first << "=>" << i->second << ")\n";
364    //      }
365    //      cout << "End map\n";
366    //
367    //  }
368    //
369    //  DataTagged::DataMapType::const_iterator i,j;
370    //  for (i=mapleft.begin(),j=mapright.begin();i!=mapleft.end() && j!=mapright.end();++i,++j) {
371    //     if ((i->first!=j->first) || (i->second!=j->second))
372    //     {
373    //      cout << "(" << i->first << "=>" << i->second << ")";
374    //      cout << ":(" << j->first << "=>" << j->second << ") ";
375    //      mismatch=true;
376    //            }
377    //  }
378    //  if (mismatch)
379    //  {
380    //      cout << "#Mismatch\n";
381    //  }
382    // }
383    
384  escriptDataC  escriptDataC
385  Data::getDataC()  Data::getDataC()
386  {  {
# Line 214  Data::getDataC() const Line 400  Data::getDataC() const
400  const boost::python::tuple  const boost::python::tuple
401  Data::getShapeTuple() const  Data::getShapeTuple() const
402  {  {
403    const DataArrayView::ShapeType& shape=getDataPointShape();    const DataTypes::ShapeType& shape=getDataPointShape();
404    switch(getDataPointRank()) {    switch(getDataPointRank()) {
405       case 0:       case 0:
406          return make_tuple();          return make_tuple();
# Line 231  Data::getShapeTuple() const Line 417  Data::getShapeTuple() const
417    }    }
418  }  }
419    
420    
421    // The different name is needed because boost has trouble with overloaded functions.
422    // It can't work out what type the function is based soley on its name.
423    // There are ways to fix this involving creating function pointer variables for each form
424    // but there doesn't seem to be a need given that the methods have the same name from the python point of view
425    Data*
426    Data::copySelf()
427    {
428       DataAbstract* temp=m_data->deepCopy();
429       return new Data(temp);
430    }
431    
432  void  void
433  Data::copy(const Data& other)  Data::copy(const Data& other)
434  {  {
435    //    DataAbstract* temp=other.m_data->deepCopy();
436    // Perform a deep copy    shared_ptr<DataAbstract> temp_data(temp);
437      m_data=temp_data;
438    }
439    
440    
441    void
442    Data::setToZero()
443    {
444      if (isEmpty())
445    {    {
446      DataExpanded* temp=dynamic_cast<DataExpanded*>(other.m_data.get());       throw DataException("Error - Operations not permitted on instances of DataEmpty.");
     if (temp!=0) {  
       //  
       // Construct a DataExpanded copy  
       DataAbstract* newData=new DataExpanded(*temp);  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
       return;  
     }  
447    }    }
448    {    {
449      DataTagged* temp=dynamic_cast<DataTagged*>(other.m_data.get());      DataExpanded* temp=dynamic_cast<DataExpanded*>(m_data.get());
450      if (temp!=0) {      if (temp!=0) {
451        //         temp->setToZero();
452        // Construct a DataTagged copy         return;
       DataAbstract* newData=new DataTagged(*temp);  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
       return;  
453      }      }
454    }    }
455    {    {
456      DataConstant* temp=dynamic_cast<DataConstant*>(other.m_data.get());      DataTagged* temp=dynamic_cast<DataTagged*>(m_data.get());
457      if (temp!=0) {      if (temp!=0) {
458        //        temp->setToZero();
       // Construct a DataConstant copy  
       DataAbstract* newData=new DataConstant(*temp);  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
459        return;        return;
460      }      }
461    }    }
462    {    {
463      DataEmpty* temp=dynamic_cast<DataEmpty*>(other.m_data.get());      DataConstant* temp=dynamic_cast<DataConstant*>(m_data.get());
464      if (temp!=0) {      if (temp!=0) {
465        //        temp->setToZero();
       // Construct a DataEmpty copy  
       DataAbstract* newData=new DataEmpty();  
       shared_ptr<DataAbstract> temp_data(newData);  
       m_data=temp_data;  
466        return;        return;
467      }      }
468    }    }
469    throw DataException("Error - Copy not implemented for this Data type.");    throw DataException("Error - Data can not be set to zero.");
470  }  }
471    
472    // void
473    // Data::copyWithMask(const Data& other,
474    //                    const Data& mask)
475    // {
476    //   if (other.isEmpty() || mask.isEmpty())
477    //   {
478    //  throw DataException("Error - copyWithMask not permitted using instances of DataEmpty.");
479    //   }
480    //   Data mask1;
481    //   Data mask2;
482    //   mask1 = mask.wherePositive();
483    //
484    //   mask2.copy(mask1);
485    //   mask1 *= other;
486    //
487    //   mask2 *= *this;
488    //   mask2 = *this - mask2;
489    //   *this = mask1 + mask2;
490    // }
491    
492  void  void
493  Data::copyWithMask(const Data& other,  Data::copyWithMask(const Data& other,
494                     const Data& mask)                     const Data& mask)
495  {  {
496    Data mask1;    // 1. Interpolate if required so all Datas use the same FS as this
497    Data mask2;    // 2. Tag or Expand so that all Data's are the same type
498      // 3. Iterate over the data vectors copying values where mask is >0
499    mask1 = mask.wherePositive();    if (other.isEmpty() || mask.isEmpty())
500    mask2.copy(mask1);    {
501        throw DataException("Error - copyWithMask not permitted using instances of DataEmpty.");
502      }
503      Data other2(other);
504      Data mask2(mask);
505      FunctionSpace myFS=getFunctionSpace();
506      FunctionSpace oFS=other2.getFunctionSpace();
507      FunctionSpace mFS=mask2.getFunctionSpace();
508      if (oFS!=myFS)
509      {
510         if (other2.probeInterpolation(myFS))
511         {
512        other2=other2.interpolate(myFS);
513         }
514         else
515         {
516        throw DataException("Error - copyWithMask: other FunctionSpace is not compatible with this one.");
517         }
518      }
519      if (mFS!=myFS)
520      {
521         if (mask2.probeInterpolation(myFS))
522         {
523        mask2=mask2.interpolate(myFS);
524         }
525         else
526         {
527        throw DataException("Error - copyWithMask: mask FunctionSpace is not compatible with this one.");
528         }
529      }
530                // Ensure that all args have the same type
531      if (this->isExpanded() || mask2.isExpanded() || other2.isExpanded())
532      {
533        this->expand();
534        other2.expand();
535        mask2.expand();
536      }
537      else if (this->isTagged() || mask2.isTagged() || other2.isTagged())
538      {
539        this->tag();
540        other2.tag();
541        mask2.tag();
542      }
543      else if (this->isConstant() && mask2.isConstant() && other2.isConstant())
544      {
545      }
546      else
547      {
548        throw DataException("Error - Unknown DataAbstract passed to copyWithMask.");
549      }
550      // Now we iterate over the elements
551      DataVector& self=m_data->getVector();
552      const DataVector& ovec=other2.m_data->getVector();
553      const DataVector& mvec=mask2.m_data->getVector();
554      if ((self.size()!=ovec.size()) || (self.size()!=mvec.size()))
555      {
556        throw DataException("Error - size mismatch in arguments to copyWithMask.");
557      }
558      size_t num_points=self.size();
559      long i;
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 329  Data::isConstant() const Line 598  Data::isConstant() const
598  }  }
599    
600  void  void
601    Data::setProtection()
602    {
603       m_protected=true;
604    }
605    
606    bool
607    Data::isProtected() const
608    {
609       return m_protected;
610    }
611    
612    
613    
614    void
615  Data::expand()  Data::expand()
616  {  {
617    if (isConstant()) {    if (isConstant()) {
# Line 370  Data::tag() Line 653  Data::tag()
653    }    }
654  }  }
655    
656  void  Data
657  Data::reshapeDataPoint(const DataArrayView::ShapeType& shape)  Data::oneOver() const
658  {  {
659    m_data->reshapeDataPoint(shape);    return C_TensorUnaryOperation(*this, bind1st(divides<double>(),1.));
660  }  }
661    
662  Data  Data
663  Data::wherePositive() const  Data::wherePositive() const
664  {  {
665    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(greater<double>(),0.0));
   return escript::unaryOp(*this,bind2nd(greater<double>(),0.0));  
666  }  }
667    
668  Data  Data
669  Data::whereNegative() const  Data::whereNegative() const
670  {  {
671    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(less<double>(),0.0));
   return escript::unaryOp(*this,bind2nd(less<double>(),0.0));  
672  }  }
673    
674  Data  Data
675  Data::whereNonNegative() const  Data::whereNonNegative() const
676  {  {
677    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(greater_equal<double>(),0.0));
   return escript::unaryOp(*this,bind2nd(greater_equal<double>(),0.0));  
678  }  }
679    
680  Data  Data
681  Data::whereNonPositive() const  Data::whereNonPositive() const
682  {  {
683    profData->where++;    return C_TensorUnaryOperation(*this, bind2nd(less_equal<double>(),0.0));
   return escript::unaryOp(*this,bind2nd(less_equal<double>(),0.0));  
684  }  }
685    
686  Data  Data
687  Data::whereZero() const  Data::whereZero(double tol) const
688  {  {
689    profData->where++;    Data dataAbs=abs();
690    return escript::unaryOp(*this,bind2nd(equal_to<double>(),0.0));    return C_TensorUnaryOperation(dataAbs, bind2nd(less_equal<double>(),tol));
691  }  }
692    
693  Data  Data
694  Data::whereNonZero() const  Data::whereNonZero(double tol) const
695  {  {
696    profData->where++;    Data dataAbs=abs();
697    return escript::unaryOp(*this,bind2nd(not_equal_to<double>(),0.0));    return C_TensorUnaryOperation(dataAbs, bind2nd(greater<double>(),tol));
698  }  }
699    
700  Data  Data
701  Data::interpolate(const FunctionSpace& functionspace) const  Data::interpolate(const FunctionSpace& functionspace) const
702  {  {
   profData->interpolate++;  
703    return Data(*this,functionspace);    return Data(*this,functionspace);
704  }  }
705    
# Line 443  Data::probeInterpolation(const FunctionS Line 721  Data::probeInterpolation(const FunctionS
721  Data  Data
722  Data::gradOn(const FunctionSpace& functionspace) const  Data::gradOn(const FunctionSpace& functionspace) const
723  {  {
724    profData->grad++;    if (isEmpty())
725      {
726        throw DataException("Error - operation not permitted on instances of DataEmpty.");
727      }
728      double blocktimer_start = blocktimer_time();
729    if (functionspace.getDomain()!=getDomain())    if (functionspace.getDomain()!=getDomain())
730      throw DataException("Error - gradient cannot be calculated on different domains.");      throw DataException("Error - gradient cannot be calculated on different domains.");
731    DataArrayView::ShapeType grad_shape=getPointDataView().getShape();    DataTypes::ShapeType grad_shape=getDataPointShape();
732    grad_shape.push_back(functionspace.getDim());    grad_shape.push_back(functionspace.getDim());
733    Data out(0.0,grad_shape,functionspace,true);    Data out(0.0,grad_shape,functionspace,true);
734    getDomain().setToGradient(out,*this);    getDomain().setToGradient(out,*this);
735      blocktimer_increment("grad()", blocktimer_start);
736    return out;    return out;
737  }  }
738    
739  Data  Data
740  Data::grad() const  Data::grad() const
741  {  {
742      if (isEmpty())
743      {
744        throw DataException("Error - operation not permitted on instances of DataEmpty.");
745      }
746    return gradOn(escript::function(getDomain()));    return gradOn(escript::function(getDomain()));
747  }  }
748    
749  int  int
750  Data::getDataPointSize() const  Data::getDataPointSize() const
751  {  {
752    return getPointDataView().noValues();    return m_data->getNoValues();
753  }  }
754    
755  DataArrayView::ValueType::size_type  DataTypes::ValueType::size_type
756  Data::getLength() const  Data::getLength() const
757  {  {
758    return m_data->getLength();    return m_data->getLength();
759  }  }
760    
 const DataArrayView::ShapeType&  
 Data::getDataPointShape() const  
 {  
   return getPointDataView().getShape();  
 }  
   
761  const  const
762  boost::python::numeric::array  boost::python::numeric::array
763  Data::convertToNumArray()  Data:: getValueOfDataPoint(int dataPointNo)
764  {  {
765    //    size_t length=0;
766    // determine the total number of data points    int i, j, k, l;
   int numSamples = getNumSamples();  
   int numDataPointsPerSample = getNumDataPointsPerSample();  
   int numDataPoints = numSamples * numDataPointsPerSample;  
   
767    //    //
768    // determine the rank and shape of each data point    // determine the rank and shape of each data point
769    int dataPointRank = getDataPointRank();    int dataPointRank = getDataPointRank();
770    DataArrayView::ShapeType dataPointShape = getDataPointShape();    const DataTypes::ShapeType& dataPointShape = getDataPointShape();
771    
772    //    //
773    // create the numeric array to be returned    // create the numeric array to be returned
774    boost::python::numeric::array numArray(0.0);    boost::python::numeric::array numArray(0.0);
775    
776    //    //
777    // the rank of the returned numeric array will be the rank of    // the shape of the returned numeric array will be the same
778    // the data points, plus one. Where the rank of the array is n,    // as that of the data point
779    // the last n-1 dimensions will be equal to the shape of the    int arrayRank = dataPointRank;
780    // 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]);  
   }  
781    
782    //    //
783    // resize the numeric array to the shape just calculated    // resize the numeric array to the shape just calculated
784      if (arrayRank==0) {
785        numArray.resize(1);
786      }
787    if (arrayRank==1) {    if (arrayRank==1) {
788      numArray.resize(arrayShape[0]);      numArray.resize(arrayShape[0]);
789    }    }
# Line 524  Data::convertToNumArray() Line 796  Data::convertToNumArray()
796    if (arrayRank==4) {    if (arrayRank==4) {
797      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);
798    }    }
   if (arrayRank==5) {  
     numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3],arrayShape[4]);  
   }  
799    
800    //    if (getNumDataPointsPerSample()>0) {
801    // loop through each data point in turn, loading the values for that data point         int sampleNo = dataPointNo/getNumDataPointsPerSample();
802    // into the numeric array.         int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
803    int dataPoint = 0;         //
804    for (int sampleNo = 0; sampleNo < numSamples; sampleNo++) {         // Check a valid sample number has been supplied
805      for (int dataPointNo = 0; dataPointNo < numDataPointsPerSample; dataPointNo++) {         if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {
806        DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNo);             throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");
807        if (dataPointRank==0) {         }
808          numArray[dataPoint]=dataPointView();  
809        }         //
810        if (dataPointRank==1) {         // Check a valid data point number has been supplied
811          for (int i=0; i<dataPointShape[0]; i++) {         if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {
812            numArray[dataPoint][i]=dataPointView(i);             throw DataException("Error - Data::convertToNumArray: invalid dataPointNoInSample.");
813          }         }
814        }         // TODO: global error handling
815        if (dataPointRank==2) {         // create a view of the data if it is stored locally
816          for (int i=0; i<dataPointShape[0]; i++) {  //       DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNoInSample);
817            for (int j=0; j<dataPointShape[1]; j++) {         DataTypes::ValueType::size_type offset=getDataOffset(sampleNo, dataPointNoInSample);
818              numArray[dataPoint][i][j] = dataPointView(i,j);  
819            }  
820          }         switch( dataPointRank ){
821        }              case 0 :
822        if (dataPointRank==3) {                  numArray[0] = getDataAtOffset(offset);
823          for (int i=0; i<dataPointShape[0]; i++) {                  break;
824            for (int j=0; j<dataPointShape[1]; j++) {              case 1 :
825              for (int k=0; k<dataPointShape[2]; k++) {                  for( i=0; i<dataPointShape[0]; i++ )
826                numArray[dataPoint][i][j][k]=dataPointView(i,j,k);                      numArray[i]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i));
827              }                  break;
828            }              case 2 :
829          }                  for( i=0; i<dataPointShape[0]; i++ )
830        }                      for( j=0; j<dataPointShape[1]; j++)
831        if (dataPointRank==4) {                          numArray[make_tuple(i,j)]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j));
832          for (int i=0; i<dataPointShape[0]; i++) {                  break;
833            for (int j=0; j<dataPointShape[1]; j++) {              case 3 :
834              for (int k=0; k<dataPointShape[2]; k++) {                  for( i=0; i<dataPointShape[0]; i++ )
835                for (int l=0; l<dataPointShape[3]; l++) {                      for( j=0; j<dataPointShape[1]; j++ )
836                  numArray[dataPoint][i][j][k][l]=dataPointView(i,j,k,l);                          for( k=0; k<dataPointShape[2]; k++)
837                }                              numArray[make_tuple(i,j,k)]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k));
838              }                  break;
839            }              case 4 :
840          }                  for( i=0; i<dataPointShape[0]; i++ )
841        }                      for( j=0; j<dataPointShape[1]; j++ )
842        dataPoint++;                          for( k=0; k<dataPointShape[2]; k++ )
843      }                              for( l=0; l<dataPointShape[3]; l++)
844                                    numArray[make_tuple(i,j,k,l)]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k,l));
845                    break;
846        }
847    }    }
   
848    //    //
849    // return the loaded array    // return the array
850    return numArray;    return numArray;
851    
852  }  }
853    
854  const  void
855  boost::python::numeric::array  Data::setValueOfDataPointToPyObject(int dataPointNo, const boost::python::object& py_object)
 Data::convertToNumArrayFromSampleNo(int sampleNo)  
856  {  {
857    //      // this will throw if the value cannot be represented
858    // Check a valid sample number has been supplied      boost::python::numeric::array num_array(py_object);
859    if (sampleNo >= getNumSamples()) {      setValueOfDataPointToArray(dataPointNo,num_array);
860      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();  
861    
862    void
863    Data::setValueOfDataPointToArray(int dataPointNo, const boost::python::numeric::array& num_array)
864    {
865      if (isProtected()) {
866            throw DataException("Error - attempt to update protected Data object.");
867      }
868    //    //
869    // create the numeric array to be returned    // check rank
870    boost::python::numeric::array numArray(0.0);    if (num_array.getrank()<getDataPointRank())
871          throw DataException("Rank of numarray does not match Data object rank");
872    
873    //    //
874    // the rank of the returned numeric array will be the rank of    // check shape of num_array
875    // the data points, plus one. Where the rank of the array is n,    for (int i=0; i<getDataPointRank(); i++) {
876    // the last n-1 dimensions will be equal to the shape of the      if (extract<int>(num_array.getshape()[i])!=getDataPointShape()[i])
877    // 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]);  
878    }    }
   
879    //    //
880    // resize the numeric array to the shape just calculated    // make sure data is expanded:
881    if (arrayRank==1) {    //
882      numArray.resize(arrayShape[0]);    if (!isExpanded()) {
883    }      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]);  
884    }    }
885    if (arrayRank==5) {    if (getNumDataPointsPerSample()>0) {
886      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3],arrayShape[4]);         int sampleNo = dataPointNo/getNumDataPointsPerSample();
887           int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
888           m_data->copyToDataPoint(sampleNo, dataPointNoInSample,num_array);
889      } else {
890           m_data->copyToDataPoint(-1, 0,num_array);
891    }    }
892    }
893    
894    //  void
895    // loop through each data point in turn, loading the values for that data point  Data::setValueOfDataPoint(int dataPointNo, const double value)
896    // into the numeric array.  {
897    for (int dataPoint = 0; dataPoint < numDataPointsPerSample; dataPoint++) {    if (isProtected()) {
898      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);  
             }  
           }  
         }  
       }  
     }  
899    }    }
   
900    //    //
901    // return the loaded array    // make sure data is expanded:
902    return numArray;    if (!isExpanded()) {
903        expand();
904      }
905      if (getNumDataPointsPerSample()>0) {
906           int sampleNo = dataPointNo/getNumDataPointsPerSample();
907           int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
908           m_data->copyToDataPoint(sampleNo, dataPointNoInSample,value);
909      } else {
910           m_data->copyToDataPoint(-1, 0,value);
911      }
912  }  }
913    
914  const  const
915  boost::python::numeric::array  boost::python::numeric::array
916  Data::convertToNumArrayFromDPNo(int sampleNo,  Data::getValueOfGlobalDataPoint(int procNo, int dataPointNo)
                                 int dataPointNo)  
917  {  {
918    //    size_t length=0;
919    // Check a valid sample number has been supplied    int i, j, k, l, pos;
   if (sampleNo >= getNumSamples()) {  
     throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");  
   }  
   
   //  
   // Check a valid data point number has been supplied  
   if (dataPointNo >= getNumDataPointsPerSample()) {  
     throw DataException("Error - Data::convertToNumArray: invalid dataPointNo.");  
   }  
   
920    //    //
921    // determine the rank and shape of each data point    // determine the rank and shape of each data point
922    int dataPointRank = getDataPointRank();    int dataPointRank = getDataPointRank();
923    DataArrayView::ShapeType dataPointShape = getDataPointShape();    const DataTypes::ShapeType& dataPointShape = getDataPointShape();
924    
925    //    //
926    // create the numeric array to be returned    // create the numeric array to be returned
# Line 711  Data::convertToNumArrayFromDPNo(int samp Line 930  Data::convertToNumArrayFromDPNo(int samp
930    // the shape of the returned numeric array will be the same    // the shape of the returned numeric array will be the same
931    // as that of the data point    // as that of the data point
932    int arrayRank = dataPointRank;    int arrayRank = dataPointRank;
933    DataArrayView::ShapeType arrayShape = dataPointShape;    const DataTypes::ShapeType& arrayShape = dataPointShape;
934    
935    //    //
936    // resize the numeric array to the shape just calculated    // resize the numeric array to the shape just calculated
# Line 731  Data::convertToNumArrayFromDPNo(int samp Line 950  Data::convertToNumArrayFromDPNo(int samp
950      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);      numArray.resize(arrayShape[0],arrayShape[1],arrayShape[2],arrayShape[3]);
951    }    }
952    
953      // added for the MPI communication
954      length=1;
955      for( i=0; i<arrayRank; i++ ) length *= arrayShape[i];
956      double *tmpData = new double[length];
957    
958    //    //
959    // load the values for the data point into the numeric array.    // load the values for the data point into the numeric array.
   DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNo);  
   if (dataPointRank==0) {  
     numArray[0]=dataPointView();  
   }  
   if (dataPointRank==1) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       numArray[i]=dataPointView(i);  
     }  
   }  
   if (dataPointRank==2) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       for (int j=0; j<dataPointShape[1]; j++) {  
         numArray[i][j] = dataPointView(i,j);  
       }  
     }  
   }  
   if (dataPointRank==3) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       for (int j=0; j<dataPointShape[1]; j++) {  
         for (int k=0; k<dataPointShape[2]; k++) {  
           numArray[i][j][k]=dataPointView(i,j,k);  
         }  
       }  
     }  
   }  
   if (dataPointRank==4) {  
     for (int i=0; i<dataPointShape[0]; i++) {  
       for (int j=0; j<dataPointShape[1]; j++) {  
         for (int k=0; k<dataPointShape[2]; k++) {  
           for (int l=0; l<dataPointShape[3]; l++) {  
             numArray[i][j][k][l]=dataPointView(i,j,k,l);  
           }  
         }  
       }  
     }  
   }  
960    
961        // updated for the MPI case
962        if( get_MPIRank()==procNo ){
963                 if (getNumDataPointsPerSample()>0) {
964                    int sampleNo = dataPointNo/getNumDataPointsPerSample();
965                    int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();
966                    //
967                    // Check a valid sample number has been supplied
968                    if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {
969                      throw DataException("Error - Data::convertToNumArray: invalid sampleNo.");
970                    }
971    
972                    //
973                    // Check a valid data point number has been supplied
974                    if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {
975                      throw DataException("Error - Data::convertToNumArray: invalid dataPointNoInSample.");
976                    }
977                    // TODO: global error handling
978            // create a view of the data if it is stored locally
979            //DataArrayView dataPointView = getDataPoint(sampleNo, dataPointNoInSample);
980            DataTypes::ValueType::size_type offset=getDataOffset(sampleNo, dataPointNoInSample);
981    
982            // pack the data from the view into tmpData for MPI communication
983            pos=0;
984            switch( dataPointRank ){
985                case 0 :
986                    tmpData[0] = getDataAtOffset(offset);
987                    break;
988                case 1 :
989                    for( i=0; i<dataPointShape[0]; i++ )
990                        tmpData[i]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i));
991                    break;
992                case 2 :
993                    for( i=0; i<dataPointShape[0]; i++ )
994                        for( j=0; j<dataPointShape[1]; j++, pos++ )
995                            tmpData[pos]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j));
996                    break;
997                case 3 :
998                    for( i=0; i<dataPointShape[0]; i++ )
999                        for( j=0; j<dataPointShape[1]; j++ )
1000                            for( k=0; k<dataPointShape[2]; k++, pos++ )
1001                                tmpData[pos]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k));
1002                    break;
1003                case 4 :
1004                    for( i=0; i<dataPointShape[0]; i++ )
1005                        for( j=0; j<dataPointShape[1]; j++ )
1006                            for( k=0; k<dataPointShape[2]; k++ )
1007                                for( l=0; l<dataPointShape[3]; l++, pos++ )
1008                                    tmpData[pos]=getDataAtOffset(offset+DataTypes::getRelIndex(dataPointShape, i,j,k,l));
1009                    break;
1010            }
1011                }
1012        }
1013            #ifdef PASO_MPI
1014            // broadcast the data to all other processes
1015        MPI_Bcast( tmpData, length, MPI_DOUBLE, procNo, get_MPIComm() );
1016            #endif
1017    
1018        // unpack the data
1019        switch( dataPointRank ){
1020            case 0 :
1021                numArray[0]=tmpData[0];
1022                break;
1023            case 1 :
1024                for( i=0; i<dataPointShape[0]; i++ )
1025                    numArray[i]=tmpData[i];
1026                break;
1027            case 2 :
1028                for( i=0; i<dataPointShape[0]; i++ )
1029                    for( j=0; j<dataPointShape[1]; j++ )
1030                       numArray[make_tuple(i,j)]=tmpData[i+j*dataPointShape[0]];
1031                break;
1032            case 3 :
1033                for( i=0; i<dataPointShape[0]; i++ )
1034                    for( j=0; j<dataPointShape[1]; j++ )
1035                        for( k=0; k<dataPointShape[2]; k++ )
1036                            numArray[make_tuple(i,j,k)]=tmpData[i+dataPointShape[0]*(j*+k*dataPointShape[1])];
1037                break;
1038            case 4 :
1039                for( i=0; i<dataPointShape[0]; i++ )
1040                    for( j=0; j<dataPointShape[1]; j++ )
1041                        for( k=0; k<dataPointShape[2]; k++ )
1042                            for( l=0; l<dataPointShape[3]; l++ )
1043                                    numArray[make_tuple(i,j,k,l)]=tmpData[i+dataPointShape[0]*(j*+dataPointShape[1]*(k+l*dataPointShape[2]))];
1044                break;
1045        }
1046    
1047        delete [] tmpData;
1048    //    //
1049    // return the loaded array    // return the loaded array
1050    return numArray;    return numArray;
1051  }  }
1052    
1053    
1054    
1055  boost::python::numeric::array  boost::python::numeric::array
1056  Data::integrate() const  Data::integrate() const
1057  {  {
1058    int index;    int index;
1059    int rank = getDataPointRank();    int rank = getDataPointRank();
1060    DataArrayView::ShapeType shape = getDataPointShape();    DataTypes::ShapeType shape = getDataPointShape();
1061      int dataPointSize = getDataPointSize();
   profData->integrate++;  
1062    
1063    //    //
1064    // calculate the integral values    // calculate the integral values
1065    vector<double> integrals(getDataPointSize());    vector<double> integrals(dataPointSize);
1066      vector<double> integrals_local(dataPointSize);
1067    #ifdef PASO_MPI
1068      AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals_local,*this);
1069      // Global sum: use an array instead of a vector because elements of array are guaranteed to be contiguous in memory
1070      double *tmp = new double[dataPointSize];
1071      double *tmp_local = new double[dataPointSize];
1072      for (int i=0; i<dataPointSize; i++) { tmp_local[i] = integrals_local[i]; }
1073      MPI_Allreduce( &tmp_local[0], &tmp[0], dataPointSize, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
1074      for (int i=0; i<dataPointSize; i++) { integrals[i] = tmp[i]; }
1075      delete[] tmp;
1076      delete[] tmp_local;
1077    #else
1078    AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals,*this);    AbstractContinuousDomain::asAbstractContinuousDomain(getDomain()).setToIntegrals(integrals,*this);
1079    #endif
1080    
1081    //    //
1082    // create the numeric array to be returned    // create the numeric array to be returned
# Line 806  Data::integrate() const Line 1095  Data::integrate() const
1095      }      }
1096    }    }
1097    if (rank==2) {    if (rank==2) {
1098      bp_array.resize(shape[0],shape[1]);         bp_array.resize(shape[0],shape[1]);
1099      for (int i=0; i<shape[0]; i++) {         for (int i=0; i<shape[0]; i++) {
1100        for (int j=0; j<shape[1]; j++) {           for (int j=0; j<shape[1]; j++) {
1101          index = i + shape[0] * j;             index = i + shape[0] * j;
1102          bp_array[i,j] = integrals[index];             bp_array[make_tuple(i,j)] = integrals[index];
1103        }           }
1104      }         }
1105    }    }
1106    if (rank==3) {    if (rank==3) {
1107      bp_array.resize(shape[0],shape[1],shape[2]);      bp_array.resize(shape[0],shape[1],shape[2]);
# Line 820  Data::integrate() const Line 1109  Data::integrate() const
1109        for (int j=0; j<shape[1]; j++) {        for (int j=0; j<shape[1]; j++) {
1110          for (int k=0; k<shape[2]; k++) {          for (int k=0; k<shape[2]; k++) {
1111            index = i + shape[0] * ( j + shape[1] * k );            index = i + shape[0] * ( j + shape[1] * k );
1112            bp_array[i,j,k] = integrals[index];            bp_array[make_tuple(i,j,k)] = integrals[index];
1113          }          }
1114        }        }
1115      }      }
# Line 832  Data::integrate() const Line 1121  Data::integrate() const
1121          for (int k=0; k<shape[2]; k++) {          for (int k=0; k<shape[2]; k++) {
1122            for (int l=0; l<shape[3]; l++) {            for (int l=0; l<shape[3]; l++) {
1123              index = i + shape[0] * ( j + shape[1] * ( k + shape[2] * l ) );              index = i + shape[0] * ( j + shape[1] * ( k + shape[2] * l ) );
1124              bp_array[i,j,k,l] = integrals[index];              bp_array[make_tuple(i,j,k,l)] = integrals[index];
1125            }            }
1126          }          }
1127        }        }
# Line 847  Data::integrate() const Line 1136  Data::integrate() const
1136  Data  Data
1137  Data::sin() const  Data::sin() const
1138  {  {
1139    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sin);
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sin);  
1140  }  }
1141    
1142  Data  Data
1143  Data::cos() const  Data::cos() const
1144  {  {
1145    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::cos);
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::cos);  
1146  }  }
1147    
1148  Data  Data
1149  Data::tan() const  Data::tan() const
1150  {  {
1151    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::tan);
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::tan);  
1152  }  }
1153    
1154  Data  Data
1155  Data::log() const  Data::asin() const
1156    {
1157      return C_TensorUnaryOperation<double (*)(double)>(*this, ::asin);
1158    }
1159    
1160    Data
1161    Data::acos() const
1162    {
1163      return C_TensorUnaryOperation<double (*)(double)>(*this, ::acos);
1164    }
1165    
1166    
1167    Data
1168    Data::atan() const
1169    {
1170      return C_TensorUnaryOperation<double (*)(double)>(*this, ::atan);
1171    }
1172    
1173    Data
1174    Data::sinh() const
1175    {
1176        return C_TensorUnaryOperation<double (*)(double)>(*this, ::sinh);
1177    
1178    }
1179    
1180    Data
1181    Data::cosh() const
1182    {
1183        return C_TensorUnaryOperation<double (*)(double)>(*this, ::cosh);
1184    }
1185    
1186    Data
1187    Data::tanh() const
1188    {
1189        return C_TensorUnaryOperation<double (*)(double)>(*this, ::tanh);
1190    }
1191    
1192    
1193    Data
1194    Data::erf() const
1195    {
1196    #ifdef _WIN32
1197      throw DataException("Error - Data:: erf function is not supported on _WIN32 platforms.");
1198    #else
1199      return C_TensorUnaryOperation(*this, ::erf);
1200    #endif
1201    }
1202    
1203    Data
1204    Data::asinh() const
1205    {
1206    #ifdef _WIN32
1207      return C_TensorUnaryOperation(*this, escript::asinh_substitute);
1208    #else
1209      return C_TensorUnaryOperation(*this, ::asinh);
1210    #endif
1211    }
1212    
1213    Data
1214    Data::acosh() const
1215    {
1216    #ifdef _WIN32
1217      return C_TensorUnaryOperation(*this, escript::acosh_substitute);
1218    #else
1219      return C_TensorUnaryOperation(*this, ::acosh);
1220    #endif
1221    }
1222    
1223    Data
1224    Data::atanh() const
1225  {  {
1226    profData->unary++;  #ifdef _WIN32
1227    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log10);    return C_TensorUnaryOperation(*this, escript::atanh_substitute);
1228    #else
1229      return C_TensorUnaryOperation(*this, ::atanh);
1230    #endif
1231  }  }
1232    
1233  Data  Data
1234  Data::ln() const  Data::log10() const
1235  {  {
1236    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::log10);
1237    return escript::unaryOp(*this,(Data::UnaryDFunPtr)::log);  }
1238    
1239    Data
1240    Data::log() const
1241    {
1242      return C_TensorUnaryOperation<double (*)(double)>(*this, ::log);
1243  }  }
1244    
1245  Data  Data
1246  Data::sign() const  Data::sign() const
1247  {  {
1248    profData->unary++;    return C_TensorUnaryOperation(*this, escript::fsign);
   return escript::unaryOp(*this,escript::fsign);  
1249  }  }
1250    
1251  Data  Data
1252  Data::abs() const  Data::abs() const
1253  {  {
1254    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::fabs);
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::fabs);  
1255  }  }
1256    
1257  Data  Data
1258  Data::neg() const  Data::neg() const
1259  {  {
1260    profData->unary++;    return C_TensorUnaryOperation(*this, negate<double>());
   return escript::unaryOp(*this,negate<double>());  
1261  }  }
1262    
1263  Data  Data
1264  Data::pos() const  Data::pos() const
1265  {  {
1266    profData->unary++;    Data result;
1267    return (*this);    // perform a deep copy
1268      result.copy(*this);
1269      return result;
1270  }  }
1271    
1272  Data  Data
1273  Data::exp() const  Data::exp() const
1274  {  {
1275    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::exp);
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::exp);  
1276  }  }
1277    
1278  Data  Data
1279  Data::sqrt() const  Data::sqrt() const
1280  {  {
1281    profData->unary++;    return C_TensorUnaryOperation<double (*)(double)>(*this, ::sqrt);
   return escript::unaryOp(*this,(Data::UnaryDFunPtr)::sqrt);  
1282  }  }
1283    
1284  double  double
1285  Data::Lsup() const  Data::Lsup() const
1286  {  {
1287    profData->reduction1++;    double localValue;
1288    //    //
1289    // set the initial absolute maximum value to zero    // set the initial absolute maximum value to zero
   return algorithm(DataAlgorithmAdapter<AbsMax>(0));  
 }  
1290    
1291  double    AbsMax abs_max_func;
1292  Data::Linf() const    localValue = algorithm(abs_max_func,0);
1293  {  #ifdef PASO_MPI
1294    profData->reduction1++;    double globalValue;
1295    //    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1296    // set the initial absolute minimum value to max double    return globalValue;
1297    return algorithm(DataAlgorithmAdapter<AbsMin>(numeric_limits<double>::max()));  #else
1298      return localValue;
1299    #endif
1300  }  }
1301    
1302  double  double
1303  Data::sup() const  Data::sup() const
1304  {  {
1305    profData->reduction1++;    double localValue;
1306    //    //
1307    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1308    return algorithm(DataAlgorithmAdapter<FMax>(numeric_limits<double>::max()*-1));    FMax fmax_func;
1309      localValue = algorithm(fmax_func,numeric_limits<double>::max()*-1);
1310    #ifdef PASO_MPI
1311      double globalValue;
1312      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD );
1313      return globalValue;
1314    #else
1315      return localValue;
1316    #endif
1317  }  }
1318    
1319  double  double
1320  Data::inf() const  Data::inf() const
1321  {  {
1322    profData->reduction1++;    double localValue;
1323    //    //
1324    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1325    return algorithm(DataAlgorithmAdapter<FMin>(numeric_limits<double>::max()));    FMin fmin_func;
1326      localValue = algorithm(fmin_func,numeric_limits<double>::max());
1327    #ifdef PASO_MPI
1328      double globalValue;
1329      MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD );
1330      return globalValue;
1331    #else
1332      return localValue;
1333    #endif
1334  }  }
1335    
1336    /* TODO */
1337    /* global reduction */
1338  Data  Data
1339  Data::maxval() const  Data::maxval() const
1340  {  {
   profData->reduction2++;  
1341    //    //
1342    // set the initial maximum value to min possible double    // set the initial maximum value to min possible double
1343    return dp_algorithm(DataAlgorithmAdapter<FMax>(numeric_limits<double>::max()*-1));    FMax fmax_func;
1344      return dp_algorithm(fmax_func,numeric_limits<double>::max()*-1);
1345  }  }
1346    
1347  Data  Data
1348  Data::minval() const  Data::minval() const
1349  {  {
   profData->reduction2++;  
1350    //    //
1351    // set the initial minimum value to max possible double    // set the initial minimum value to max possible double
1352    return dp_algorithm(DataAlgorithmAdapter<FMin>(numeric_limits<double>::max()));    FMin fmin_func;
1353      return dp_algorithm(fmin_func,numeric_limits<double>::max());
1354  }  }
1355    
1356  Data  Data
1357  Data::length() const  Data::swapaxes(const int axis0, const int axis1) const
1358  {  {
1359    profData->reduction2++;       int axis0_tmp,axis1_tmp;
1360    return dp_algorithm(DataAlgorithmAdapter<Length>(0));       DataTypes::ShapeType s=getDataPointShape();
1361         DataTypes::ShapeType ev_shape;
1362         // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1363         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1364         int rank=getDataPointRank();
1365         if (rank<2) {
1366            throw DataException("Error - Data::swapaxes argument must have at least rank 2.");
1367         }
1368         if (axis0<0 || axis0>rank-1) {
1369            throw DataException("Error - Data::swapaxes: axis0 must be between 0 and rank-1=" + rank-1);
1370         }
1371         if (axis1<0 || axis1>rank-1) {
1372             throw DataException("Error - Data::swapaxes: axis1 must be between 0 and rank-1=" + rank-1);
1373         }
1374         if (axis0 == axis1) {
1375             throw DataException("Error - Data::swapaxes: axis indices must be different.");
1376         }
1377         if (axis0 > axis1) {
1378             axis0_tmp=axis1;
1379             axis1_tmp=axis0;
1380         } else {
1381             axis0_tmp=axis0;
1382             axis1_tmp=axis1;
1383         }
1384         for (int i=0; i<rank; i++) {
1385           if (i == axis0_tmp) {
1386              ev_shape.push_back(s[axis1_tmp]);
1387           } else if (i == axis1_tmp) {
1388              ev_shape.push_back(s[axis0_tmp]);
1389           } else {
1390              ev_shape.push_back(s[i]);
1391           }
1392         }
1393         Data ev(0.,ev_shape,getFunctionSpace());
1394         ev.typeMatchRight(*this);
1395         m_data->swapaxes(ev.m_data.get(), axis0_tmp, axis1_tmp);
1396         return ev;
1397    
1398    }
1399    
1400    Data
1401    Data::symmetric() const
1402    {
1403         // check input
1404         DataTypes::ShapeType s=getDataPointShape();
1405         if (getDataPointRank()==2) {
1406            if(s[0] != s[1])
1407               throw DataException("Error - Data::symmetric can only be calculated for rank 2 object with equal first and second dimension.");
1408         }
1409         else if (getDataPointRank()==4) {
1410            if(!(s[0] == s[2] && s[1] == s[3]))
1411               throw DataException("Error - Data::symmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1412         }
1413         else {
1414            throw DataException("Error - Data::symmetric can only be calculated for rank 2 or 4 object.");
1415         }
1416         Data ev(0.,getDataPointShape(),getFunctionSpace());
1417         ev.typeMatchRight(*this);
1418         m_data->symmetric(ev.m_data.get());
1419         return ev;
1420    }
1421    
1422    Data
1423    Data::nonsymmetric() const
1424    {
1425         // check input
1426         DataTypes::ShapeType s=getDataPointShape();
1427         if (getDataPointRank()==2) {
1428            if(s[0] != s[1])
1429               throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 object with equal first and second dimension.");
1430            DataTypes::ShapeType ev_shape;
1431            ev_shape.push_back(s[0]);
1432            ev_shape.push_back(s[1]);
1433            Data ev(0.,ev_shape,getFunctionSpace());
1434            ev.typeMatchRight(*this);
1435            m_data->nonsymmetric(ev.m_data.get());
1436            return ev;
1437         }
1438         else if (getDataPointRank()==4) {
1439            if(!(s[0] == s[2] && s[1] == s[3]))
1440               throw DataException("Error - Data::nonsymmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.");
1441            DataTypes::ShapeType ev_shape;
1442            ev_shape.push_back(s[0]);
1443            ev_shape.push_back(s[1]);
1444            ev_shape.push_back(s[2]);
1445            ev_shape.push_back(s[3]);
1446            Data ev(0.,ev_shape,getFunctionSpace());
1447            ev.typeMatchRight(*this);
1448            m_data->nonsymmetric(ev.m_data.get());
1449            return ev;
1450         }
1451         else {
1452            throw DataException("Error - Data::nonsymmetric can only be calculated for rank 2 or 4 object.");
1453         }
1454    }
1455    
1456    Data
1457    Data::trace(int axis_offset) const
1458    {
1459         DataTypes::ShapeType s=getDataPointShape();
1460         if (getDataPointRank()==2) {
1461            DataTypes::ShapeType ev_shape;
1462            Data ev(0.,ev_shape,getFunctionSpace());
1463            ev.typeMatchRight(*this);
1464            m_data->trace(ev.m_data.get(), axis_offset);
1465            return ev;
1466         }
1467         if (getDataPointRank()==3) {
1468            DataTypes::ShapeType ev_shape;
1469            if (axis_offset==0) {
1470              int s2=s[2];
1471              ev_shape.push_back(s2);
1472            }
1473            else if (axis_offset==1) {
1474              int s0=s[0];
1475              ev_shape.push_back(s0);
1476            }
1477            Data ev(0.,ev_shape,getFunctionSpace());
1478            ev.typeMatchRight(*this);
1479            m_data->trace(ev.m_data.get(), axis_offset);
1480            return ev;
1481         }
1482         if (getDataPointRank()==4) {
1483            DataTypes::ShapeType ev_shape;
1484            if (axis_offset==0) {
1485              ev_shape.push_back(s[2]);
1486              ev_shape.push_back(s[3]);
1487            }
1488            else if (axis_offset==1) {
1489              ev_shape.push_back(s[0]);
1490              ev_shape.push_back(s[3]);
1491            }
1492        else if (axis_offset==2) {
1493          ev_shape.push_back(s[0]);
1494          ev_shape.push_back(s[1]);
1495        }
1496            Data ev(0.,ev_shape,getFunctionSpace());
1497            ev.typeMatchRight(*this);
1498        m_data->trace(ev.m_data.get(), axis_offset);
1499            return ev;
1500         }
1501         else {
1502            throw DataException("Error - Data::trace can only be calculated for rank 2, 3 or 4 object.");
1503         }
1504  }  }
1505    
1506  Data  Data
1507  Data::trace() const  Data::transpose(int axis_offset) const
1508  {  {
1509    profData->reduction2++;       DataTypes::ShapeType s=getDataPointShape();
1510    return dp_algorithm(DataAlgorithmAdapter<Trace>(0));       DataTypes::ShapeType ev_shape;
1511         // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]
1512         // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)
1513         int rank=getDataPointRank();
1514         if (axis_offset<0 || axis_offset>rank) {
1515            throw DataException("Error - Data::transpose must have 0 <= axis_offset <= rank=" + rank);
1516         }
1517         for (int i=0; i<rank; i++) {
1518           int index = (axis_offset+i)%rank;
1519           ev_shape.push_back(s[index]); // Append to new shape
1520         }
1521         Data ev(0.,ev_shape,getFunctionSpace());
1522         ev.typeMatchRight(*this);
1523         m_data->transpose(ev.m_data.get(), axis_offset);
1524         return ev;
1525  }  }
1526    
1527  Data  Data
1528  Data::transpose(int axis) const  Data::eigenvalues() const
1529    {
1530         // check input
1531         DataTypes::ShapeType s=getDataPointShape();
1532         if (getDataPointRank()!=2)
1533            throw DataException("Error - Data::eigenvalues can only be calculated for rank 2 object.");
1534         if(s[0] != s[1])
1535            throw DataException("Error - Data::eigenvalues can only be calculated for object with equal first and second dimension.");
1536         // create return
1537         DataTypes::ShapeType ev_shape(1,s[0]);
1538         Data ev(0.,ev_shape,getFunctionSpace());
1539         ev.typeMatchRight(*this);
1540         m_data->eigenvalues(ev.m_data.get());
1541         return ev;
1542    }
1543    
1544    const boost::python::tuple
1545    Data::eigenvalues_and_eigenvectors(const double tol) const
1546  {  {
1547    profData->reduction2++;       DataTypes::ShapeType s=getDataPointShape();
1548    // not implemented       if (getDataPointRank()!=2)
1549    throw DataException("Error - Data::transpose not implemented yet.");          throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for rank 2 object.");
1550    return Data();       if(s[0] != s[1])
1551            throw DataException("Error - Data::eigenvalues and eigenvectors can only be calculated for object with equal first and second dimension.");
1552         // create return
1553         DataTypes::ShapeType ev_shape(1,s[0]);
1554         Data ev(0.,ev_shape,getFunctionSpace());
1555         ev.typeMatchRight(*this);
1556         DataTypes::ShapeType V_shape(2,s[0]);
1557         Data V(0.,V_shape,getFunctionSpace());
1558         V.typeMatchRight(*this);
1559         m_data->eigenvalues_and_eigenvectors(ev.m_data.get(),V.m_data.get(),tol);
1560         return make_tuple(boost::python::object(ev),boost::python::object(V));
1561  }  }
1562    
1563  const boost::python::tuple  const boost::python::tuple
1564  Data::mindp() const  Data::minGlobalDataPoint() const
1565    {
1566      // NB: calc_minGlobalDataPoint( had to be split off from minGlobalDataPoint( as boost::make_tuple causes an
1567      // abort (for unknown reasons) if there are openmp directives with it in the
1568      // surrounding function
1569    
1570      int DataPointNo;
1571      int ProcNo;
1572      calc_minGlobalDataPoint(ProcNo,DataPointNo);
1573      return make_tuple(ProcNo,DataPointNo);
1574    }
1575    
1576    void
1577    Data::calc_minGlobalDataPoint(int& ProcNo,
1578                            int& DataPointNo) const
1579  {  {
1580      int i,j;
1581      int lowi=0,lowj=0;
1582      double min=numeric_limits<double>::max();
1583    
1584    Data temp=minval();    Data temp=minval();
1585    
1586    int numSamples=temp.getNumSamples();    int numSamples=temp.getNumSamples();
1587    int numDPPSample=temp.getNumDataPointsPerSample();    int numDPPSample=temp.getNumDataPointsPerSample();
1588    
1589    int i,j,lowi=0,lowj=0;    double next,local_min;
1590    double min=numeric_limits<double>::max();    int local_lowi,local_lowj;
1591    
1592    for (i=0; i<numSamples; i++) {    #pragma omp parallel private(next,local_min,local_lowi,local_lowj)
1593      for (j=0; j<numDPPSample; j++) {    {
1594        double next=temp.getDataPoint(i,j)();      local_min=min;
1595        if (next<min) {      #pragma omp for private(i,j) schedule(static)
1596          min=next;      for (i=0; i<numSamples; i++) {
1597          lowi=i;        for (j=0; j<numDPPSample; j++) {
1598          lowj=j;          next=temp.getDataAtOffset(temp.getDataOffset(i,j));
1599            if (next<local_min) {
1600              local_min=next;
1601              local_lowi=i;
1602              local_lowj=j;
1603            }
1604        }        }
1605      }      }
1606        #pragma omp critical
1607        if (local_min<min) {
1608          min=local_min;
1609          lowi=local_lowi;
1610          lowj=local_lowj;
1611        }
1612    }    }
1613    
1614    return make_tuple(lowi,lowj);  #ifdef PASO_MPI
1615        // determine the processor on which the minimum occurs
1616        next = temp.getDataPoint(lowi,lowj);
1617        int lowProc = 0;
1618        double *globalMins = new double[get_MPISize()+1];
1619        int error = MPI_Gather ( &next, 1, MPI_DOUBLE, globalMins, 1, MPI_DOUBLE, 0, get_MPIComm() );
1620    
1621        if( get_MPIRank()==0 ){
1622            next = globalMins[lowProc];
1623            for( i=1; i<get_MPISize(); i++ )
1624                if( next>globalMins[i] ){
1625                    lowProc = i;
1626                    next = globalMins[i];
1627                }
1628        }
1629        MPI_Bcast( &lowProc, 1, MPI_DOUBLE, 0, get_MPIComm() );
1630    
1631        delete [] globalMins;
1632        ProcNo = lowProc;
1633    #else
1634        ProcNo = 0;
1635    #endif
1636      DataPointNo = lowj + lowi * numDPPSample;
1637  }  }
1638    
1639  void  void
1640  Data::saveDX(std::string fileName) const  Data::saveDX(std::string fileName) const
1641  {  {
1642    getDomain().saveDX(fileName,*this);    if (isEmpty())
1643      {
1644        throw DataException("Error - Operations not permitted on instances of DataEmpty.");
1645      }
1646      boost::python::dict args;
1647      args["data"]=boost::python::object(this);
1648      getDomain().saveDX(fileName,args);
1649    return;    return;
1650  }  }
1651    
1652  void  void
1653  Data::saveVTK(std::string fileName) const  Data::saveVTK(std::string fileName) const
1654  {  {
1655    getDomain().saveVTK(fileName,*this);    if (isEmpty())
1656      {
1657        throw DataException("Error - Operations not permitted on instances of DataEmpty.");
1658      }
1659      boost::python::dict args;
1660      args["data"]=boost::python::object(this);
1661      getDomain().saveVTK(fileName,args);
1662    return;    return;
1663  }  }
1664    
1665  Data&  Data&
1666  Data::operator+=(const Data& right)  Data::operator+=(const Data& right)
1667  {  {
1668    profData->binary++;    if (isProtected()) {
1669            throw DataException("Error - attempt to update protected Data object.");
1670      }
1671    binaryOp(right,plus<double>());    binaryOp(right,plus<double>());
1672    return (*this);    return (*this);
1673  }  }
# Line 1048  Data::operator+=(const Data& right) Line 1675  Data::operator+=(const Data& right)
1675  Data&  Data&
1676  Data::operator+=(const boost::python::object& right)  Data::operator+=(const boost::python::object& right)
1677  {  {
1678    profData->binary++;    Data tmp(right,getFunctionSpace(),false);
1679    binaryOp(right,plus<double>());    binaryOp(tmp,plus<double>());
1680      return (*this);
1681    }
1682    Data&
1683    Data::operator=(const Data& other)
1684    {
1685      copy(other);
1686    return (*this);    return (*this);
1687  }  }
1688    
1689  Data&  Data&
1690  Data::operator-=(const Data& right)  Data::operator-=(const Data& right)
1691  {  {
1692    profData->binary++;    if (isProtected()) {
1693            throw DataException("Error - attempt to update protected Data object.");
1694      }
1695    binaryOp(right,minus<double>());    binaryOp(right,minus<double>());
1696    return (*this);    return (*this);
1697  }  }
# Line 1064  Data::operator-=(const Data& right) Line 1699  Data::operator-=(const Data& right)
1699  Data&  Data&
1700  Data::operator-=(const boost::python::object& right)  Data::operator-=(const boost::python::object& right)
1701  {  {
1702    profData->binary++;    Data tmp(right,getFunctionSpace(),false);
1703    binaryOp(right,minus<double>());    binaryOp(tmp,minus<double>());
1704    return (*this);    return (*this);
1705  }  }
1706    
1707  Data&  Data&
1708  Data::operator*=(const Data& right)  Data::operator*=(const Data& right)
1709  {  {
1710    profData->binary++;    if (isProtected()) {
1711            throw DataException("Error - attempt to update protected Data object.");
1712      }
1713    binaryOp(right,multiplies<double>());    binaryOp(right,multiplies<double>());
1714    return (*this);    return (*this);
1715  }  }
# Line 1080  Data::operator*=(const Data& right) Line 1717  Data::operator*=(const Data& right)
1717  Data&  Data&
1718  Data::operator*=(const boost::python::object& right)  Data::operator*=(const boost::python::object& right)
1719  {  {
1720    profData->binary++;    Data tmp(right,getFunctionSpace(),false);
1721    binaryOp(right,multiplies<double>());    binaryOp(tmp,multiplies<double>());
1722    return (*this);    return (*this);
1723  }  }
1724    
1725  Data&  Data&
1726  Data::operator/=(const Data& right)  Data::operator/=(const Data& right)
1727  {  {
1728    profData->binary++;    if (isProtected()) {
1729            throw DataException("Error - attempt to update protected Data object.");
1730      }
1731    binaryOp(right,divides<double>());    binaryOp(right,divides<double>());
1732    return (*this);    return (*this);
1733  }  }
# Line 1096  Data::operator/=(const Data& right) Line 1735  Data::operator/=(const Data& right)
1735  Data&  Data&
1736  Data::operator/=(const boost::python::object& right)  Data::operator/=(const boost::python::object& right)
1737  {  {
1738    profData->binary++;    Data tmp(right,getFunctionSpace(),false);
1739    binaryOp(right,divides<double>());    binaryOp(tmp,divides<double>());
1740    return (*this);    return (*this);
1741  }  }
1742    
1743  Data  Data
1744    Data::rpowO(const boost::python::object& left) const
1745    {
1746      Data left_d(left,*this);
1747      return left_d.powD(*this);
1748    }
1749    
1750    Data
1751  Data::powO(const boost::python::object& right) const  Data::powO(const boost::python::object& right) const
1752  {  {
1753    profData->binary++;    Data tmp(right,getFunctionSpace(),false);
1754    Data result;    return powD(tmp);
   result.copy(*this);  
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1755  }  }
1756    
1757  Data  Data
1758  Data::powD(const Data& right) const  Data::powD(const Data& right) const
1759  {  {
1760    profData->binary++;    return C_TensorBinaryOperation<double (*)(double, double)>(*this, right, ::pow);
   Data result;  
   result.copy(*this);  
   result.binaryOp(right,(Data::BinaryDFunPtr)::pow);  
   return result;  
1761  }  }
1762    
1763  //  //
# Line 1126  Data::powD(const Data& right) const Line 1765  Data::powD(const Data& right) const
1765  Data  Data
1766  escript::operator+(const Data& left, const Data& right)  escript::operator+(const Data& left, const Data& right)
1767  {  {
1768    Data result;    return C_TensorBinaryOperation(left, right, plus<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result+=right;  
   return result;  
1769  }  }
1770    
1771  //  //
# Line 1139  escript::operator+(const Data& left, con Line 1773  escript::operator+(const Data& left, con
1773  Data  Data
1774  escript::operator-(const Data& left, const Data& right)  escript::operator-(const Data& left, const Data& right)
1775  {  {
1776    Data result;    return C_TensorBinaryOperation(left, right, minus<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result-=right;  
   return result;  
1777  }  }
1778    
1779  //  //
# Line 1152  escript::operator-(const Data& left, con Line 1781  escript::operator-(const Data& left, con
1781  Data  Data
1782  escript::operator*(const Data& left, const Data& right)  escript::operator*(const Data& left, const Data& right)
1783  {  {
1784    Data result;    return C_TensorBinaryOperation(left, right, multiplies<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result*=right;  
   return result;  
1785  }  }
1786    
1787  //  //
# Line 1165  escript::operator*(const Data& left, con Line 1789  escript::operator*(const Data& left, con
1789  Data  Data
1790  escript::operator/(const Data& left, const Data& right)  escript::operator/(const Data& left, const Data& right)
1791  {  {
1792    Data result;    return C_TensorBinaryOperation(left, right, divides<double>());
   //  
   // perform a deep copy  
   result.copy(left);  
   result/=right;  
   return result;  
1793  }  }
1794    
1795  //  //
# Line 1178  escript::operator/(const Data& left, con Line 1797  escript::operator/(const Data& left, con
1797  Data  Data
1798  escript::operator+(const Data& left, const boost::python::object& right)  escript::operator+(const Data& left, const boost::python::object& right)
1799  {  {
1800    //    return left+Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result+=right;  
   return result;  
1801  }  }
1802    
1803  //  //
# Line 1194  escript::operator+(const Data& left, con Line 1805  escript::operator+(const Data& left, con
1805  Data  Data
1806  escript::operator-(const Data& left, const boost::python::object& right)  escript::operator-(const Data& left, const boost::python::object& right)
1807  {  {
1808    //    return left-Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result-=right;  
   return result;  
1809  }  }
1810    
1811  //  //
# Line 1210  escript::operator-(const Data& left, con Line 1813  escript::operator-(const Data& left, con
1813  Data  Data
1814  escript::operator*(const Data& left, const boost::python::object& right)  escript::operator*(const Data& left, const boost::python::object& right)
1815  {  {
1816    //    return left*Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result*=right;  
   return result;  
1817  }  }
1818    
1819  //  //
# Line 1226  escript::operator*(const Data& left, con Line 1821  escript::operator*(const Data& left, con
1821  Data  Data
1822  escript::operator/(const Data& left, const boost::python::object& right)  escript::operator/(const Data& left, const boost::python::object& right)
1823  {  {
1824    //    return left/Data(right,left.getFunctionSpace(),false);
   // Convert to DataArray format if possible  
   DataArray temp(right);  
   Data result;  
   //  
   // perform a deep copy  
   result.copy(left);  
   result/=right;  
   return result;  
1825  }  }
1826    
1827  //  //
# Line 1242  escript::operator/(const Data& left, con Line 1829  escript::operator/(const Data& left, con
1829  Data  Data
1830  escript::operator+(const boost::python::object& left, const Data& right)  escript::operator+(const boost::python::object& left, const Data& right)
1831  {  {
1832    //    return Data(left,right.getFunctionSpace(),false)+right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result+=right;  
   return result;  
1833  }  }
1834    
1835  //  //
# Line 1255  escript::operator+(const boost::python:: Line 1837  escript::operator+(const boost::python::
1837  Data  Data
1838  escript::operator-(const boost::python::object& left, const Data& right)  escript::operator-(const boost::python::object& left, const Data& right)
1839  {  {
1840    //    return Data(left,right.getFunctionSpace(),false)-right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result-=right;  
   return result;  
1841  }  }
1842    
1843  //  //
# Line 1268  escript::operator-(const boost::python:: Line 1845  escript::operator-(const boost::python::
1845  Data  Data
1846  escript::operator*(const boost::python::object& left, const Data& right)  escript::operator*(const boost::python::object& left, const Data& right)
1847  {  {
1848    //    return Data(left,right.getFunctionSpace(),false)*right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result*=right;  
   return result;  
1849  }  }
1850    
1851  //  //
# Line 1281  escript::operator*(const boost::python:: Line 1853  escript::operator*(const boost::python::
1853  Data  Data
1854  escript::operator/(const boost::python::object& left, const Data& right)  escript::operator/(const boost::python::object& left, const Data& right)
1855  {  {
1856    //    return Data(left,right.getFunctionSpace(),false)/right;
   // Construct the result using the given value and the other parameters  
   // from right  
   Data result(left,right);  
   result/=right;  
   return result;  
1857  }  }
1858    
1859  //  //
# Line 1334  escript::operator/(const boost::python:: Line 1901  escript::operator/(const boost::python::
1901  //  return ret;  //  return ret;
1902  //}  //}
1903    
1904    /* TODO */
1905    /* global reduction */
1906  Data  Data
1907  Data::getItem(const boost::python::object& key) const  Data::getItem(const boost::python::object& key) const
1908  {  {
1909    const DataArrayView& view=getPointDataView();  //  const DataArrayView& view=getPointDataView();
1910    
1911    DataArrayView::RegionType slice_region=view.getSliceRegion(key);    DataTypes::RegionType slice_region=DataTypes::getSliceRegion(getDataPointShape(),key);
1912    
1913    if (slice_region.size()!=view.getRank()) {    if (slice_region.size()!=getDataPointRank()) {
1914      throw DataException("Error - slice size does not match Data rank.");      throw DataException("Error - slice size does not match Data rank.");
1915    }    }
1916    
1917    return getSlice(slice_region);    return getSlice(slice_region);
1918  }  }
1919    
1920    /* TODO */
1921    /* global reduction */
1922  Data  Data
1923  Data::getSlice(const DataArrayView::RegionType& region) const  Data::getSlice(const DataTypes::RegionType& region) const
1924  {  {
   profData->slicing++;  
1925    return Data(*this,region);    return Data(*this,region);
1926  }  }
1927    
1928    /* TODO */
1929    /* global reduction */
1930  void  void
1931  Data::setItemO(const boost::python::object& key,  Data::setItemO(const boost::python::object& key,
1932                 const boost::python::object& value)                 const boost::python::object& value)
# Line 1367  void Line 1939  void
1939  Data::setItemD(const boost::python::object& key,  Data::setItemD(const boost::python::object& key,
1940                 const Data& value)                 const Data& value)
1941  {  {
1942    const DataArrayView& view=getPointDataView();  //  const DataArrayView& view=getPointDataView();
1943    
1944    DataArrayView::RegionType slice_region=view.getSliceRegion(key);    DataTypes::RegionType slice_region=DataTypes::getSliceRegion(getDataPointShape(),key);
1945    if (slice_region.size()!=view.getRank()) {    if (slice_region.size()!=getDataPointRank()) {
1946      throw DataException("Error - slice size does not match Data rank.");      throw DataException("Error - slice size does not match Data rank.");
1947    }    }
1948    if (getFunctionSpace()!=value.getFunctionSpace()) {    if (getFunctionSpace()!=value.getFunctionSpace()) {
# Line 1382  Data::setItemD(const boost::python::obje Line 1954  Data::setItemD(const boost::python::obje
1954    
1955  void  void
1956  Data::setSlice(const Data& value,  Data::setSlice(const Data& value,
1957                 const DataArrayView::RegionType& region)                 const DataTypes::RegionType& region)
1958  {  {
1959    profData->slicing++;    if (isProtected()) {
1960            throw DataException("Error - attempt to update protected Data object.");
1961      }
1962    Data tempValue(value);    Data tempValue(value);
1963    typeMatchLeft(tempValue);    typeMatchLeft(tempValue);
1964    typeMatchRight(tempValue);    typeMatchRight(tempValue);
# Line 1420  Data::typeMatchRight(const Data& right) Line 1994  Data::typeMatchRight(const Data& right)
1994  }  }
1995    
1996  void  void
1997    Data::setTaggedValueByName(std::string name,
1998                               const boost::python::object& value)
1999    {
2000         if (getFunctionSpace().getDomain().isValidTagName(name)) {
2001            int tagKey=getFunctionSpace().getDomain().getTag(name);
2002            setTaggedValue(tagKey,value);
2003         }
2004    }
2005    void
2006  Data::setTaggedValue(int tagKey,  Data::setTaggedValue(int tagKey,
2007                       const boost::python::object& value)                       const boost::python::object& value)
2008  {  {
2009      if (isProtected()) {
2010            throw DataException("Error - attempt to update protected Data object.");
2011      }
2012    //    //
2013    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
2014    tag();    if (isConstant()) tag();
2015    
2016    if (!isTagged()) {    numeric::array asNumArray(value);
2017      throw DataException("Error - DataTagged conversion failed!!");  
2018    
2019      // extract the shape of the numarray
2020      DataTypes::ShapeType tempShape;
2021      for (int i=0; i < asNumArray.getrank(); i++) {
2022        tempShape.push_back(extract<int>(asNumArray.getshape()[i]));
2023    }    }
2024    
2025    //    // get the space for the data vector
2026    // Construct DataArray from boost::python::object input value  //   int len = DataTypes::noValues(tempShape);
2027    DataArray valueDataArray(value);  //   DataVector temp_data(len, 0.0, len);
2028    //   DataArrayView temp_dataView(temp_data, tempShape);
2029    //   temp_dataView.copy(asNumArray);
2030    
2031      DataVector temp_data2;
2032      temp_data2.copyFromNumArray(asNumArray);
2033    
2034    //    //
2035    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
2036    m_data->setTaggedValue(tagKey,valueDataArray.getView());    //m_data->setTaggedValue(tagKey,temp_dataView);
2037    
2038        m_data->setTaggedValue(tagKey,tempShape, temp_data2);
2039  }  }
2040    
2041    // void
2042    // Data::setTaggedValueFromCPP(int tagKey,
2043    //                             const DataArrayView& value)
2044    // {
2045    //   if (isProtected()) {
2046    //         throw DataException("Error - attempt to update protected Data object.");
2047    //   }
2048    //   //
2049    //   // Ensure underlying data object is of type DataTagged
2050    //   if (isConstant()) tag();
2051    //
2052    //   //
2053    //   // Call DataAbstract::setTaggedValue
2054    //   m_data->setTaggedValue(tagKey,value);
2055    // }
2056    
2057  void  void
2058  Data::setTaggedValueFromCPP(int tagKey,  Data::setTaggedValueFromCPP(int tagKey,
2059                              const DataArrayView& value)                  const DataTypes::ShapeType& pointshape,
2060                                const DataTypes::ValueType& value,
2061                    int dataOffset)
2062  {  {
2063      if (isProtected()) {
2064            throw DataException("Error - attempt to update protected Data object.");
2065      }
2066    //    //
2067    // Ensure underlying data object is of type DataTagged    // Ensure underlying data object is of type DataTagged
2068    tag();    if (isConstant()) tag();
2069    
   if (!isTagged()) {  
     throw DataException("Error - DataTagged conversion failed!!");  
   }  
                                                                                                                 
2070    //    //
2071    // Call DataAbstract::setTaggedValue    // Call DataAbstract::setTaggedValue
2072    m_data->setTaggedValue(tagKey,value);    m_data->setTaggedValue(tagKey,pointshape, value, dataOffset);
2073  }  }
2074    
2075  void  int
2076  Data::setRefValue(int ref,  Data::getTagNumber(int dpno)
                   const boost::python::numeric::array& value)  
2077  {  {
2078    //    if (isEmpty())
2079    // Construct DataArray from boost::python::object input value    {
2080    DataArray valueDataArray(value);      throw DataException("Error - operation not permitted on instances of DataEmpty.");
2081      }
2082    //    return getFunctionSpace().getTagFromDataPointNo(dpno);
   // Call DataAbstract::setRefValue  
   m_data->setRefValue(ref,valueDataArray);  
2083  }  }
2084    
2085  void  
2086  Data::getRefValue(int ref,  ostream& escript::operator<<(ostream& o, const Data& data)
                   boost::python::numeric::array& value)  
2087  {  {
2088    //    o << data.toString();
2089    // Construct DataArray for boost::python::object return value    return o;
2090    DataArray valueDataArray(value);  }
2091    
2092    //  Data
2093    // Load DataArray with values from data-points specified by ref  escript::C_GeneralTensorProduct(Data& arg_0,
2094    m_data->getRefValue(ref,valueDataArray);                       Data& arg_1,
2095                         int axis_offset,
2096                         int transpose)
2097    {
2098      // General tensor product: res(SL x SR) = arg_0(SL x SM) * arg_1(SM x SR)
2099      // SM is the product of the last axis_offset entries in arg_0.getShape().
2100    
2101      // Interpolate if necessary and find an appropriate function space
2102      Data arg_0_Z, arg_1_Z;
2103      if (arg_0.getFunctionSpace()!=arg_1.getFunctionSpace()) {
2104        if (arg_0.probeInterpolation(arg_1.getFunctionSpace())) {
2105          arg_0_Z = arg_0.interpolate(arg_1.getFunctionSpace());
2106          arg_1_Z = Data(arg_1);
2107        }
2108        else if (arg_1.probeInterpolation(arg_0.getFunctionSpace())) {
2109          arg_1_Z=arg_1.interpolate(arg_0.getFunctionSpace());
2110          arg_0_Z =Data(arg_0);
2111        }
2112        else {
2113          throw DataException("Error - C_GeneralTensorProduct: arguments have incompatible function spaces.");
2114        }
2115      } else {
2116          arg_0_Z = Data(arg_0);
2117          arg_1_Z = Data(arg_1);
2118      }
2119      // Get rank and shape of inputs
2120      int rank0 = arg_0_Z.getDataPointRank();
2121      int rank1 = arg_1_Z.getDataPointRank();
2122      const DataTypes::ShapeType& shape0 = arg_0_Z.getDataPointShape();
2123      const DataTypes::ShapeType& shape1 = arg_1_Z.getDataPointShape();
2124    
2125    //    // Prepare for the loops of the product and verify compatibility of shapes
2126    // Load values from valueDataArray into return numarray    int start0=0, start1=0;
2127      if (transpose == 0)       {}
2128      else if (transpose == 1)  { start0 = axis_offset; }
2129      else if (transpose == 2)  { start1 = rank1-axis_offset; }
2130      else              { throw DataException("C_GeneralTensorProduct: Error - transpose should be 0, 1 or 2"); }
2131    
   // extract the shape of the numarray  
   int rank = value.getrank();  
   DataArrayView::ShapeType shape;  
   for (int i=0; i < rank; i++) {  
     shape.push_back(extract<int>(value.getshape()[i]));  
   }  
2132    
2133    // and load the numarray with the data from the DataArray    // Adjust the shapes for transpose
2134    DataArrayView valueView = valueDataArray.getView();    DataTypes::ShapeType tmpShape0(rank0);    // pre-sizing the vectors rather
2135      DataTypes::ShapeType tmpShape1(rank1);    // than using push_back
2136      for (int i=0; i<rank0; i++)   { tmpShape0[i]=shape0[(i+start0)%rank0]; }
2137      for (int i=0; i<rank1; i++)   { tmpShape1[i]=shape1[(i+start1)%rank1]; }
2138    
2139    if (rank==0) {  #if 0
2140      throw DataException("Data::getRefValue error: only rank 1 data handled for now.");    // For debugging: show shape after transpose
2141      char tmp[100];
2142      std::string shapeStr;
2143      shapeStr = "(";
2144      for (int i=0; i<rank0; i++)   { sprintf(tmp, "%d,", tmpShape0[i]); shapeStr += tmp; }
2145      shapeStr += ")";
2146      cout << "C_GeneralTensorProduct: Shape of arg0 is " << shapeStr << endl;
2147      shapeStr = "(";
2148      for (int i=0; i<rank1; i++)   { sprintf(tmp, "%d,", tmpShape1[i]); shapeStr += tmp; }
2149      shapeStr += ")";
2150      cout << "C_GeneralTensorProduct: Shape of arg1 is " << shapeStr << endl;
2151    #endif
2152    
2153      // Prepare for the loops of the product
2154      int SL=1, SM=1, SR=1;
2155      for (int i=0; i<rank0-axis_offset; i++)   {
2156        SL *= tmpShape0[i];
2157    }    }
2158    if (rank==1) {    for (int i=rank0-axis_offset; i<rank0; i++)   {
2159      for (int i=0; i < shape[0]; i++) {      if (tmpShape0[i] != tmpShape1[i-(rank0-axis_offset)]) {
2160        value[i] = valueView(i);        throw DataException("C_GeneralTensorProduct: Error - incompatible shapes");
2161      }      }
2162        SM *= tmpShape0[i];
2163    }    }
2164    if (rank==2) {    for (int i=axis_offset; i<rank1; i++)     {
2165      throw DataException("Data::getRefValue error: only rank 1 data handled for now.");      SR *= tmpShape1[i];
2166    }    }
2167    if (rank==3) {  
2168      throw DataException("Data::getRefValue error: only rank 1 data handled for now.");    // Define the shape of the output (rank of shape is the sum of the loop ranges below)
2169      DataTypes::ShapeType shape2(rank0+rank1-2*axis_offset);  
2170      {         // block to limit the scope of out_index
2171         int out_index=0;
2172         for (int i=0; i<rank0-axis_offset; i++, ++out_index) { shape2[out_index]=tmpShape0[i]; } // First part of arg_0_Z
2173         for (int i=axis_offset; i<rank1; i++, ++out_index)   { shape2[out_index]=tmpShape1[i]; } // Last part of arg_1_Z
2174    }    }
2175    if (rank==4) {  
2176      throw DataException("Data::getRefValue error: only rank 1 data handled for now.");    // Declare output Data object
2177      Data res;
2178    
2179      if      (arg_0_Z.isConstant()   && arg_1_Z.isConstant()) {
2180        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataConstant output
2181        double *ptr_0 = &(arg_0_Z.getDataAtOffset(0));
2182        double *ptr_1 = &(arg_1_Z.getDataAtOffset(0));
2183        double *ptr_2 = &(res.getDataAtOffset(0));
2184        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2185    }    }
2186      else if (arg_0_Z.isConstant()   && arg_1_Z.isTagged()) {
2187    
2188  }      // Prepare the DataConstant input
2189        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2190        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2191    
2192  void      // Borrow DataTagged input from Data object
2193  Data::archiveData(const std::string fileName)      DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2194  {      if (tmp_1==0) { throw DataException("GTP_1 Programming error - casting to DataTagged."); }
   cout << "Archiving Data object to: " << fileName << endl;  
2195    
2196    //      // Prepare a DataTagged output 2
2197    // Determine type of this Data object      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());    // DataTagged output
2198    int dataType = -1;      res.tag();
2199        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2200        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2201    
2202    if (isEmpty()) {      // Prepare offset into DataConstant
2203      dataType = 0;      int offset_0 = tmp_0->getPointOffset(0,0);
2204      cout << "\tdataType: DataEmpty" << endl;      double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2205    }      // Get the views
2206    if (isConstant()) {  //     DataArrayView view_1 = tmp_1->getDefaultValue();
2207      dataType = 1;  //     DataArrayView view_2 = tmp_2->getDefaultValue();
2208      cout << "\tdataType: DataConstant" << endl;  //     // Get the pointers to the actual data
2209    }  //     double *ptr_1 = &((view_1.getData())[0]);
2210    if (isTagged()) {  //     double *ptr_2 = &((view_2.getData())[0]);
     dataType = 2;  
     cout << "\tdataType: DataTagged" << endl;  
   }  
   if (isExpanded()) {  
     dataType = 3;  
     cout << "\tdataType: DataExpanded" << endl;  
   }  
2211    
2212    if (dataType == -1) {      double *ptr_1 = &(tmp_1->getDefaultValue(0));
2213      throw DataException("archiveData Error: undefined dataType");      double *ptr_2 = &(tmp_2->getDefaultValue(0));
   }  
2214    
2215    //  
2216    // Collect data items common to all Data types      // Compute an MVP for the default
2217    int noSamples = getNumSamples();      matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2218    int noDPPSample = getNumDataPointsPerSample();      // Compute an MVP for each tag
2219    int functionSpaceType = getFunctionSpace().getTypeCode();      const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2220    int dataPointRank = getDataPointRank();      DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2221    int dataPointSize = getDataPointSize();      for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2222    int dataLength = getLength();        tmp_2->addTag(i->first);
2223    DataArrayView::ShapeType dataPointShape = getDataPointShape();  //       DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2224    int referenceNumbers[noSamples];  //       DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2225    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  //       double *ptr_1 = &view_1.getData(0);
2226      referenceNumbers[sampleNo] = getFunctionSpace().getReferenceNoFromSampleNo(sampleNo);  //       double *ptr_2 = &view_2.getData(0);
2227    }  
2228    int tagNumbers[noSamples];        double *ptr_1 = &(tmp_1->getDataByTag(i->first,0));
2229    if (isTagged()) {        double *ptr_2 = &(tmp_2->getDataByTag(i->first,0));
2230      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      
2231        tagNumbers[sampleNo] = getFunctionSpace().getTagFromSampleNo(sampleNo);        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2232      }      }
2233    
2234    }    }
2235      else if (arg_0_Z.isConstant()   && arg_1_Z.isExpanded()) {
2236    
2237    cout << "\tnoSamples: " << noSamples << " noDPPSample: " << noDPPSample << endl;      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2238    cout << "\tfunctionSpaceType: " << functionSpaceType << endl;      DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());
2239    cout << "\trank: " << dataPointRank << " size: " << dataPointSize << " length: " << dataLength << endl;      DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2240        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2241        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2242        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2243        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2244        int sampleNo_1,dataPointNo_1;
2245        int numSamples_1 = arg_1_Z.getNumSamples();
2246        int numDataPointsPerSample_1 = arg_1_Z.getNumDataPointsPerSample();
2247        int offset_0 = tmp_0->getPointOffset(0,0);
2248        #pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)
2249        for (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {
2250          for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {
2251            int offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);
2252            int offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);
2253            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2254            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2255            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2256            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2257          }
2258        }
2259    
   //  
   // Flatten Shape to an array of integers suitable for writing to file  
   int flatShape[4] = {0,0,0,0};  
   cout << "\tshape: < ";  
   for (int dim=0; dim<dataPointRank; dim++) {  
     flatShape[dim] = dataPointShape[dim];  
     cout << dataPointShape[dim] << " ";  
2260    }    }
2261    cout << ">" << endl;    else if (arg_0_Z.isTagged()     && arg_1_Z.isConstant()) {
2262    
2263    //      // Borrow DataTagged input from Data object
2264    // Open archive file      DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2265    ofstream archiveFile;      if (tmp_0==0) { throw DataException("GTP_0 Programming error - casting to DataTagged."); }
   archiveFile.open(fileName.data(), ios::out);  
2266    
2267    if (!archiveFile.good()) {      // Prepare the DataConstant input
2268      throw DataException("archiveData Error: problem opening archive file");      DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2269    }      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2270    
2271    //      // Prepare a DataTagged output 2
2272    // Write common data items to archive file      res = Data(0.0, shape2, arg_0_Z.getFunctionSpace());    // DataTagged output
2273    archiveFile.write(reinterpret_cast<char *>(&dataType),sizeof(int));      res.tag();
2274    archiveFile.write(reinterpret_cast<char *>(&noSamples),sizeof(int));      DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2275    archiveFile.write(reinterpret_cast<char *>(&noDPPSample),sizeof(int));      if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
   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));  
     }  
   }  
2276    
2277    if (!archiveFile.good()) {      // Prepare offset into DataConstant
2278      throw DataException("archiveData Error: problem writing to archive file");      int offset_1 = tmp_1->getPointOffset(0,0);
2279    }      double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2280        // Get the views
2281    //     DataArrayView view_0 = tmp_0->getDefaultValue();
2282    //     DataArrayView view_2 = tmp_2->getDefaultValue();
2283    //     // Get the pointers to the actual data
2284    //     double *ptr_0 = &((view_0.getData())[0]);
2285    //     double *ptr_2 = &((view_2.getData())[0]);
2286    
2287    //      double *ptr_0 = &(tmp_0->getDefaultValue(0));
2288    // Archive underlying data values for each Data type      double *ptr_2 = &(tmp_2->getDefaultValue(0));
   int noValues;  
   switch (dataType) {  
     case 0:  
       // DataEmpty  
       noValues = 0;  
       archiveFile.write(reinterpret_cast<char *>(&noValues),sizeof(int));  
       cout << "\tnoValues: " << noValues << endl;  
       break;  
     case 1:  
       // DataConstant  
       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 2:  
       // DataTagged  
       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;  
   }  
2289    
2290    if (!archiveFile.good()) {      // Compute an MVP for the default
2291      throw DataException("archiveData Error: problem writing data to archive file");      matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2292    }      // Compute an MVP for each tag
2293        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2294        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2295        for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2296    //      tmp_2->addTaggedValue(i->first,tmp_2->getDefaultValue());
2297    //       DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2298    //       DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2299    //       double *ptr_0 = &view_0.getData(0);
2300    //       double *ptr_2 = &view_2.getData(0);
2301    
2302    //        tmp_2->addTag(i->first);
2303    // Close archive file        double *ptr_0 = &(tmp_0->getDataByTag(i->first,0));
2304    archiveFile.close();        double *ptr_2 = &(tmp_2->getDataByTag(i->first,0));
2305          matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2306        }
2307    
   if (!archiveFile.good()) {  
     throw DataException("archiveData Error: problem closing archive file");  
2308    }    }
2309      else if (arg_0_Z.isTagged()     && arg_1_Z.isTagged()) {
2310    
2311  }      // Borrow DataTagged input from Data object
2312        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2313        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2314    
2315  void      // Borrow DataTagged input from Data object
2316  Data::extractData(const std::string fileName,      DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2317                    const FunctionSpace& fspace)      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
 {  
   //  
   // Can only extract Data to an object which is initially DataEmpty  
   if (!isEmpty()) {  
     throw DataException("extractData Error: can only extract to DataEmpty object");  
   }  
2318    
2319    cout << "Extracting Data object from: " << fileName << endl;      // Prepare a DataTagged output 2
2320        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace());
2321        res.tag();  // DataTagged output
2322        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());
2323        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2324    
2325    int dataType;  //     // Get the views
2326    int noSamples;  //     DataArrayView view_0 = tmp_0->getDefaultValue();
2327    int noDPPSample;  //     DataArrayView view_1 = tmp_1->getDefaultValue();
2328    int functionSpaceType;  //     DataArrayView view_2 = tmp_2->getDefaultValue();
2329    int dataPointRank;  //     // Get the pointers to the actual data
2330    int dataPointSize;  //     double *ptr_0 = &((view_0.getData())[0]);
2331    int dataLength;  //     double *ptr_1 = &((view_1.getData())[0]);
2332    DataArrayView::ShapeType dataPointShape;  //     double *ptr_2 = &((view_2.getData())[0]);
   int flatShape[4];  
2333    
2334    //      double *ptr_0 = &(tmp_0->getDefaultValue(0));
2335    // Open the archive file      double *ptr_1 = &(tmp_1->getDefaultValue(0));
2336    ifstream archiveFile;      double *ptr_2 = &(tmp_2->getDefaultValue(0));
   archiveFile.open(fileName.data(), ios::in);  
2337    
   if (!archiveFile.good()) {  
     throw DataException("extractData Error: problem opening archive file");  
   }  
2338    
2339    //      // Compute an MVP for the default
2340    // Read common data items from archive file      matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2341    archiveFile.read(reinterpret_cast<char *>(&dataType),sizeof(int));      // Merge the tags
2342    archiveFile.read(reinterpret_cast<char *>(&noSamples),sizeof(int));      DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory
2343    archiveFile.read(reinterpret_cast<char *>(&noDPPSample),sizeof(int));      const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();
2344    archiveFile.read(reinterpret_cast<char *>(&functionSpaceType),sizeof(int));      const DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();
2345    archiveFile.read(reinterpret_cast<char *>(&dataPointRank),sizeof(int));      for (i=lookup_0.begin();i!=lookup_0.end();i++) {
2346    archiveFile.read(reinterpret_cast<char *>(&dataPointSize),sizeof(int));        tmp_2->addTag(i->first); // use tmp_2 to get correct shape
   archiveFile.read(reinterpret_cast<char *>(&dataLength),sizeof(int));  
   for (int dim = 0; dim < 4; dim++) {  
     archiveFile.read(reinterpret_cast<char *>(&flatShape[dim]),sizeof(int));  
     if (flatShape[dim]>0) {  
       dataPointShape.push_back(flatShape[dim]);  
2347      }      }
2348    }      for (i=lookup_1.begin();i!=lookup_1.end();i++) {
2349    int referenceNumbers[noSamples];        tmp_2->addTag(i->first);
   for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  
     archiveFile.read(reinterpret_cast<char *>(&referenceNumbers[sampleNo]),sizeof(int));  
   }  
   int tagNumbers[noSamples];  
   if (dataType==2) {  
     for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  
       archiveFile.read(reinterpret_cast<char *>(&tagNumbers[sampleNo]),sizeof(int));  
2350      }      }
2351    }      // Compute an MVP for each tag
2352        const DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();
2353        for (i=lookup_2.begin();i!=lookup_2.end();i++) {
2354    //       DataArrayView view_0 = tmp_0->getDataPointByTag(i->first);
2355    //       DataArrayView view_1 = tmp_1->getDataPointByTag(i->first);
2356    //       DataArrayView view_2 = tmp_2->getDataPointByTag(i->first);
2357    //       double *ptr_0 = &view_0.getData(0);
2358    //       double *ptr_1 = &view_1.getData(0);
2359    //       double *ptr_2 = &view_2.getData(0);
2360    
2361    if (!archiveFile.good()) {        double *ptr_0 = &(tmp_0->getDataByTag(i->first,0));
2362      throw DataException("extractData Error: problem reading from archive file");        double *ptr_1 = &(tmp_1->getDataByTag(i->first,0));
2363    }        double *ptr_2 = &(tmp_2->getDataByTag(i->first,0));
2364    
2365    //        matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2366    // 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;  
   }  
2367    
   cout << "\tnoSamples: " << noSamples << " noDPPSample: " << noDPPSample << endl;  
   cout << "\tfunctionSpaceType: " << functionSpaceType << endl;  
   cout << "\trank: " << dataPointRank << " size: " << dataPointSize << " length: " << dataLength << endl;  
   cout << "\tshape: < ";  
   for (int dim = 0; dim < dataPointRank; dim++) {  
     cout << dataPointShape[dim] << " ";  
2368    }    }
2369    cout << ">" << endl;    else if (arg_0_Z.isTagged()     && arg_1_Z.isExpanded()) {
2370    
2371    //      // After finding a common function space above the two inputs have the same numSamples and num DPPS
2372    // Verify that supplied FunctionSpace object is compatible with this Data object.      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2373    if ( (fspace.getTypeCode()!=functionSpaceType) ||      DataTagged*   tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());
2374         (fspace.getNumSamples()!=noSamples) ||      DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2375         (fspace.getNumDPPSample()!=noDPPSample)      DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2376       ) {      if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2377      throw DataException("extractData Error: incompatible FunctionSpace");      if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2378    }      if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2379    for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {      int sampleNo_0,dataPointNo_0;
2380      if (referenceNumbers[sampleNo] != fspace.getReferenceNoFromSampleNo(sampleNo)) {      int numSamples_0 = arg_0_Z.getNumSamples();
2381        throw DataException("extractData Error: incompatible FunctionSpace");      int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2382        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2383        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2384          int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0
2385          double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2386          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2387            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2388            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2389            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2390            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2391            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2392          }
2393      }      }
2394    
2395    }    }
2396    if (dataType==2) {    else if (arg_0_Z.isExpanded()   && arg_1_Z.isConstant()) {
2397      for (int sampleNo=0; sampleNo<noSamples; sampleNo++) {  
2398        if (tagNumbers[sampleNo] != fspace.getTagFromSampleNo(sampleNo)) {      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2399          throw DataException("extractData Error: incompatible FunctionSpace");      DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2400        DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());
2401        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2402        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2403        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataConstant."); }
2404        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2405        int sampleNo_0,dataPointNo_0;
2406        int numSamples_0 = arg_0_Z.getNumSamples();
2407        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2408        int offset_1 = tmp_1->getPointOffset(0,0);
2409        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2410        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2411          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2412            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2413            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2414            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2415            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2416            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2417            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2418        }        }
2419      }      }
   }  
2420    
   //  
   // Construct a DataVector to hold underlying data values  
   DataVector dataVec(dataLength);  
2421    
   //  
   // 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;  
2422    }    }
2423      else if (arg_0_Z.isExpanded()   && arg_1_Z.isTagged()) {
2424    
2425        // After finding a common function space above the two inputs have the same numSamples and num DPPS
2426        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2427        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2428        DataTagged*   tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());
2429        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2430        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2431        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataTagged."); }
2432        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2433        int sampleNo_0,dataPointNo_0;
2434        int numSamples_0 = arg_0_Z.getNumSamples();
2435        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2436        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2437        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2438          int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);
2439          double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2440          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2441            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2442            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2443            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2444            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2445            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2446          }
2447        }
2448    
   if (!archiveFile.good()) {  
     throw DataException("extractData Error: problem reading from archive file");  
2449    }    }
2450      else if (arg_0_Z.isExpanded()   && arg_1_Z.isExpanded()) {
2451    
2452    //      // After finding a common function space above the two inputs have the same numSamples and num DPPS
2453    // Close archive file      res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output
2454    archiveFile.close();      DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());
2455        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());
2456        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());
2457        if (tmp_0==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2458        if (tmp_1==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2459        if (tmp_2==0) { throw DataException("GTP Programming error - casting to DataExpanded."); }
2460        int sampleNo_0,dataPointNo_0;
2461        int numSamples_0 = arg_0_Z.getNumSamples();
2462        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();
2463        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)
2464        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {
2465          for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {
2466            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);
2467            int offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);
2468            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);
2469            double *ptr_0 = &(arg_0_Z.getDataAtOffset(offset_0));
2470            double *ptr_1 = &(arg_1_Z.getDataAtOffset(offset_1));
2471            double *ptr_2 = &(res.getDataAtOffset(offset_2));
2472            matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);
2473          }
2474        }
2475    
2476    if (!archiveFile.good()) {    }
2477      throw DataException("extractData Error: problem closing archive file");    else {
2478        throw DataException("Error - C_GeneralTensorProduct: unknown combination of inputs");
2479    }    }
2480    
2481    //    return res;
2482    // Construct an appropriate Data object  }
2483    DataAbstract* tempData;  
2484    switch (dataType) {  DataAbstract*
2485      case 0:  Data::borrowData() const
2486        // DataEmpty  {
2487        tempData=new DataEmpty();    return m_data.get();
2488        break;  }
2489      case 1:  
2490        // DataConstant  
2491        tempData=new DataConstant(fspace,dataPointShape,dataVec);  std::string
2492        break;  Data::toString() const
2493      case 2:  {
2494        // DataTagged      static const DataTypes::ValueType::size_type TOO_MANY_POINTS=80;
2495        tempData=new DataTagged(fspace,dataPointShape,tagNumbers,dataVec);      if (getNumDataPoints()*getDataPointSize()>TOO_MANY_POINTS)
2496        break;      {
2497      case 3:      stringstream temp;
2498        // DataExpanded      temp << "Summary: inf="<< inf() << " sup=" << sup() << " data points=" << getNumDataPoints();
2499        tempData=new DataExpanded(fspace,dataPointShape,dataVec);      return  temp.str();
2500        break;      }
2501        return m_data->toString();
2502    }
2503    
2504    
2505    
2506    DataTypes::ValueType::const_reference
2507    Data::getDataAtOffset(DataTypes::ValueType::size_type i) const
2508    {
2509        return m_data->getDataAtOffset(i);
2510    }
2511    
2512    
2513    DataTypes::ValueType::reference
2514    Data::getDataAtOffset(DataTypes::ValueType::size_type i)
2515    {
2516        return m_data->getDataAtOffset(i);
2517    }
2518    
2519    DataTypes::ValueType::const_reference
2520    Data::getDataPoint(int sampleNo, int dataPointNo) const
2521    {
2522        return m_data->getDataAtOffset(m_data->getPointOffset(sampleNo, dataPointNo));
2523    }
2524    
2525    
2526    DataTypes::ValueType::reference
2527    Data::getDataPoint(int sampleNo, int dataPointNo)
2528    {
2529        return m_data->getDataAtOffset(m_data->getPointOffset(sampleNo, dataPointNo));
2530    }
2531    
2532    
2533    /* Member functions specific to the MPI implementation */
2534    
2535    void
2536    Data::print()
2537    {
2538      int i,j;
2539    
2540      printf( "Data is %dX%d\n", getNumSamples(), getNumDataPointsPerSample() );
2541      for( i=0; i<getNumSamples(); i++ )
2542      {
2543        printf( "[%6d]", i );
2544        for( j=0; j<getNumDataPointsPerSample(); j++ )
2545          printf( "\t%10.7g", (getSampleData(i))[j] );
2546        printf( "\n" );
2547    }    }
2548    shared_ptr<DataAbstract> temp_data(tempData);  }
2549    m_data=temp_data;  void
2550    Data::dump(const std::string fileName) const
2551    {
2552      try
2553         {
2554            return m_data->dump(fileName);
2555         }
2556         catch (exception& e)
2557         {
2558            cout << e.what() << endl;
2559         }
2560    }
2561    
2562    int
2563    Data::get_MPISize() const
2564    {
2565        int size;
2566    #ifdef PASO_MPI
2567        int error;
2568        error = MPI_Comm_size( get_MPIComm(), &size );
2569    #else
2570        size = 1;
2571    #endif
2572        return size;
2573  }  }
2574    
2575  ostream& escript::operator<<(ostream& o, const Data& data)  int
2576    Data::get_MPIRank() const
2577  {  {
2578    o << data.toString();      int rank;
2579    return o;  #ifdef PASO_MPI
2580        int error;
2581        error = MPI_Comm_rank( get_MPIComm(), &rank );
2582    #else
2583        rank = 0;
2584    #endif
2585        return rank;
2586    }
2587    
2588    MPI_Comm
2589    Data::get_MPIComm() const
2590    {
2591    #ifdef PASO_MPI
2592        return MPI_COMM_WORLD;
2593    #else
2594        return -1;
2595    #endif
2596  }  }
2597    
2598    

Legend:
Removed from v.123  
changed lines
  Added in v.1859

  ViewVC Help
Powered by ViewVC 1.1.26