/[escript]/branches/clazy/escriptcore/src/DataLazy.cpp
ViewVC logotype

Diff of /branches/clazy/escriptcore/src/DataLazy.cpp

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

branches/schroedinger/escript/src/DataLazy.cpp revision 1889 by jfenwick, Thu Oct 16 05:57:09 2008 UTC branches/schroedinger_upto1946/escript/src/DataLazy.cpp revision 1950 by jfenwick, Thu Oct 30 00:59:34 2008 UTC
# Line 26  Line 26 
26  #include "DataTypes.h"  #include "DataTypes.h"
27  #include "Data.h"  #include "Data.h"
28  #include "UnaryFuncs.h"     // for escript::fsign  #include "UnaryFuncs.h"     // for escript::fsign
29    #include "Utils.h"
30    
31    /*
32    How does DataLazy work?
33    ~~~~~~~~~~~~~~~~~~~~~~~
34    
35    Each instance represents a single operation on one or two other DataLazy instances. These arguments are normally
36    denoted left and right.
37    
38    A special operation, IDENTITY, stores an instance of DataReady in the m_id member.
39    This means that all "internal" nodes in the structure are instances of DataLazy.
40    
41    Each operation has a string representation as well as an opgroup - eg G_IDENTITY, G_BINARY, ...
42    Note that IDENITY is not considered a unary operation.
43    
44    I am avoiding calling the structure formed a tree because it is not guaranteed to be one (eg c=a+a).
45    It must however form a DAG (directed acyclic graph).
46    I will refer to individual DataLazy objects with the structure as nodes.
47    
48    Each node also stores:
49    - m_readytype \in {'E','T','C','?'} ~ indicates what sort of DataReady would be produced if the expression was
50        evaluated.
51    - m_length ~ how many values would be stored in the answer if the expression was evaluated.
52    - m_buffsrequired ~ the larged number of samples which would need to be kept simultaneously in order to
53        evaluate the expression.
54    - m_samplesize ~ the number of doubles stored in a sample.
55    
56    When a new node is created, the above values are computed based on the values in the child nodes.
57    Eg: if left requires 4 samples and right requires 6 then left+right requires 7 samples.
58    
59    The resolve method, which produces a DataReady from a DataLazy, does the following:
60    1) Create a DataReady to hold the new result.
61    2) Allocate a vector (v) big enough to hold m_buffsrequired samples.
62    3) For each sample, call resolveSample with v, to get its values and copy them into the result object.
63    
64    (In the case of OMP, multiple samples are resolved in parallel so the vector needs to be larger.)
65    
66    resolveSample returns a Vector* and an offset within that vector where the result is stored.
67    Normally, this would be v, but for identity nodes their internal vector is returned instead.
68    
69    The convention that I use, is that the resolve methods should store their results starting at the offset they are passed.
70    
71    For expressions which evaluate to Constant or Tagged, there is a different evaluation method.
72    The collapse method invokes the (non-lazy) operations on the Data class to evaluate the expression.
73    */
74    
75    
76  using namespace std;  using namespace std;
77  using namespace boost;  using namespace boost;
# Line 39  opToString(ES_optype op); Line 85  opToString(ES_optype op);
85  namespace  namespace
86  {  {
87    
   
   
88  enum ES_opgroup  enum ES_opgroup
89  {  {
90     G_UNKNOWN,     G_UNKNOWN,
91     G_IDENTITY,     G_IDENTITY,
92     G_BINARY,     G_BINARY,        // pointwise operations with two arguments
93     G_UNARY     G_UNARY      // pointwise operations with one argument
94  };  };
95    
96    
97    
98    
99  string ES_opstrings[]={"UNKNOWN","IDENTITY","+","-","*","/","sin","cos","tan",  string ES_opstrings[]={"UNKNOWN","IDENTITY","+","-","*","/","^",
100                "sin","cos","tan",
101              "asin","acos","atan","sinh","cosh","tanh","erf",              "asin","acos","atan","sinh","cosh","tanh","erf",
102              "asinh","acosh","atanh",              "asinh","acosh","atanh",
103              "log10","log","sign","abs","neg","pos","exp","sqrt",              "log10","log","sign","abs","neg","pos","exp","sqrt",
104              "1/","where>0","where<0","where>=0","where<=0"};              "1/","where>0","where<0","where>=0","where<=0"};
105  int ES_opcount=32;  int ES_opcount=33;
106  ES_opgroup opgroups[]={G_UNKNOWN,G_IDENTITY,G_BINARY,G_BINARY,G_BINARY,G_BINARY,G_UNARY,G_UNARY,G_UNARY, //9  ES_opgroup opgroups[]={G_UNKNOWN,G_IDENTITY,G_BINARY,G_BINARY,G_BINARY,G_BINARY, G_BINARY,
107              G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,    // 16              G_UNARY,G_UNARY,G_UNARY, //10
108              G_UNARY,G_UNARY,G_UNARY,                    // 19              G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,    // 17
109              G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,        // 27              G_UNARY,G_UNARY,G_UNARY,                    // 20
110                G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY,        // 28
111              G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY};              G_UNARY,G_UNARY,G_UNARY,G_UNARY,G_UNARY};
112  inline  inline
113  ES_opgroup  ES_opgroup
# Line 79  resultFS(DataAbstract_ptr left, DataAbst Line 125  resultFS(DataAbstract_ptr left, DataAbst
125      // that way, if interpolate is required in any other op we can just throw a      // that way, if interpolate is required in any other op we can just throw a
126      // programming error exception.      // programming error exception.
127    
128      FunctionSpace l=left->getFunctionSpace();
129      if (left->getFunctionSpace()!=right->getFunctionSpace())    FunctionSpace r=right->getFunctionSpace();
130      {    if (l!=r)
131          throw DataException("FunctionSpaces not equal - interpolation not supported on lazy data.");    {
132      }      if (r.probeInterpolation(l))
133      return left->getFunctionSpace();      {
134        return l;
135        }
136        if (l.probeInterpolation(r))
137        {
138        return r;
139        }
140        throw DataException("Cannot interpolate between the FunctionSpaces given for operation "+opToString(op)+".");
141      }
142      return l;
143  }  }
144    
145  // return the shape of the result of "left op right"  // return the shape of the result of "left op right"
# Line 93  resultShape(DataAbstract_ptr left, DataA Line 148  resultShape(DataAbstract_ptr left, DataA
148  {  {
149      if (left->getShape()!=right->getShape())      if (left->getShape()!=right->getShape())
150      {      {
151          throw DataException("Shapes not the same - shapes must match for lazy data.");        if (getOpgroup(op)!=G_BINARY)
152          {
153            throw DataException("Shapes not the name - shapes must match for (point)binary operations.");
154          }
155          if (left->getRank()==0)   // we need to allow scalar * anything
156          {
157            return right->getShape();
158          }
159          if (right->getRank()==0)
160          {
161            return left->getShape();
162          }
163          throw DataException("Shapes not the same - arguments must have matching shapes (or be scalars) for (point)binary operations on lazy data.");
164      }      }
165      return left->getShape();      return left->getShape();
166  }  }
167    
168    // determine the number of points in the result of "left op right"
169  size_t  size_t
170  resultLength(DataAbstract_ptr left, DataAbstract_ptr right, ES_optype op)  resultLength(DataAbstract_ptr left, DataAbstract_ptr right, ES_optype op)
171  {  {
# Line 110  resultLength(DataAbstract_ptr left, Data Line 178  resultLength(DataAbstract_ptr left, Data
178     }     }
179  }  }
180    
181    // determine the number of samples requires to evaluate an expression combining left and right
182  int  int
183  calcBuffs(const DataLazy_ptr& left, const DataLazy_ptr& right, ES_optype op)  calcBuffs(const DataLazy_ptr& left, const DataLazy_ptr& right, ES_optype op)
184  {  {
# Line 123  calcBuffs(const DataLazy_ptr& left, cons Line 192  calcBuffs(const DataLazy_ptr& left, cons
192     }     }
193  }  }
194    
195    
196  }   // end anonymous namespace  }   // end anonymous namespace
197    
198    
199    
200    // Return a string representing the operation
201  const std::string&  const std::string&
202  opToString(ES_optype op)  opToString(ES_optype op)
203  {  {
# Line 143  DataLazy::DataLazy(DataAbstract_ptr p) Line 215  DataLazy::DataLazy(DataAbstract_ptr p)
215  {  {
216     if (p->isLazy())     if (p->isLazy())
217     {     {
     // TODO: fix this.   We could make the new node a copy of p?  
218      // I don't want identity of Lazy.      // I don't want identity of Lazy.
219      // Question: Why would that be so bad?      // Question: Why would that be so bad?
220      // Answer: We assume that the child of ID is something we can call getVector on      // Answer: We assume that the child of ID is something we can call getVector on
# Line 163  DataLazy::DataLazy(DataAbstract_ptr p) Line 234  DataLazy::DataLazy(DataAbstract_ptr p)
234  cout << "(1)Lazy created with " << m_samplesize << endl;  cout << "(1)Lazy created with " << m_samplesize << endl;
235  }  }
236    
237    
238    
239    
240  DataLazy::DataLazy(DataAbstract_ptr left, ES_optype op)  DataLazy::DataLazy(DataAbstract_ptr left, ES_optype op)
241      : parent(left->getFunctionSpace(),left->getShape()),      : parent(left->getFunctionSpace(),left->getShape()),
242      m_op(op)      m_op(op)
# Line 188  DataLazy::DataLazy(DataAbstract_ptr left Line 262  DataLazy::DataLazy(DataAbstract_ptr left
262  }  }
263    
264    
265  // DataLazy::DataLazy(DataLazy_ptr left, DataLazy_ptr right, ES_optype op)  // In this constructor we need to consider interpolation
 //  : parent(resultFS(left,right,op), resultShape(left,right,op)),  
 //  m_left(left),  
 //  m_right(right),  
 //  m_op(op)  
 // {  
 //    if (getOpgroup(op)!=G_BINARY)  
 //    {  
 //  throw DataException("Programmer error - constructor DataLazy(left, right, op) will only process BINARY operations.");  
 //    }  
 //    m_length=resultLength(m_left,m_right,m_op);  
 //    m_samplesize=getNumDPPSample()*getNoValues();  
 //    m_buffsRequired=calcBuffs(m_left, m_right, m_op);  
 // cout << "(2)Lazy created with " << m_samplesize << endl;  
 // }  
   
266  DataLazy::DataLazy(DataAbstract_ptr left, DataAbstract_ptr right, ES_optype op)  DataLazy::DataLazy(DataAbstract_ptr left, DataAbstract_ptr right, ES_optype op)
267      : parent(resultFS(left,right,op), resultShape(left,right,op)),      : parent(resultFS(left,right,op), resultShape(left,right,op)),
268      m_op(op)      m_op(op)
# Line 212  DataLazy::DataLazy(DataAbstract_ptr left Line 271  DataLazy::DataLazy(DataAbstract_ptr left
271     {     {
272      throw DataException("Programmer error - constructor DataLazy(left, right, op) will only process BINARY operations.");      throw DataException("Programmer error - constructor DataLazy(left, right, op) will only process BINARY operations.");
273     }     }
274     if (left->isLazy())  
275       if (getFunctionSpace()!=left->getFunctionSpace())    // left needs to be interpolated
276       {
277        FunctionSpace fs=getFunctionSpace();
278        Data ltemp(left);
279        Data tmp(ltemp,fs);
280        left=tmp.borrowDataPtr();
281       }
282       if (getFunctionSpace()!=right->getFunctionSpace())   // left needs to be interpolated
283       {
284        Data tmp(Data(right),getFunctionSpace());
285        right=tmp.borrowDataPtr();
286       }
287       left->operandCheck(*right);
288    
289       if (left->isLazy())          // the children need to be DataLazy. Wrap them in IDENTITY if required
290     {     {
291      m_left=dynamic_pointer_cast<DataLazy>(left);      m_left=dynamic_pointer_cast<DataLazy>(left);
292     }     }
# Line 243  DataLazy::DataLazy(DataAbstract_ptr left Line 317  DataLazy::DataLazy(DataAbstract_ptr left
317      m_readytype='C';      m_readytype='C';
318     }     }
319     m_length=resultLength(m_left,m_right,m_op);     m_length=resultLength(m_left,m_right,m_op);
320     m_samplesize=getNumDPPSample()*getNoValues();     m_samplesize=getNumDPPSample()*getNoValues();    
321     m_buffsRequired=calcBuffs(m_left, m_right,m_op);     m_buffsRequired=calcBuffs(m_left, m_right,m_op);
322  cout << "(3)Lazy created with " << m_samplesize << endl;  cout << "(3)Lazy created with " << m_samplesize << endl;
323  }  }
# Line 261  DataLazy::getBuffsRequired() const Line 335  DataLazy::getBuffsRequired() const
335  }  }
336    
337    
338    /*
339      \brief Evaluates the expression using methods on Data.
340      This does the work for the collapse method.
341      For reasons of efficiency do not call this method on DataExpanded nodes.
342    */
343  DataReady_ptr  DataReady_ptr
344  DataLazy::collapseToReady()  DataLazy::collapseToReady()
345  {  {
# Line 380  DataLazy::collapseToReady() Line 459  DataLazy::collapseToReady()
459    return result.borrowReadyPtr();    return result.borrowReadyPtr();
460  }  }
461    
462    /*
463       \brief Converts the DataLazy into an IDENTITY storing the value of the expression.
464       This method uses the original methods on the Data class to evaluate the expressions.
465       For this reason, it should not be used on DataExpanded instances. (To do so would defeat
466       the purpose of using DataLazy in the first place).
467    */
468  void  void
469  DataLazy::collapse()  DataLazy::collapse()
470  {  {
# Line 395  DataLazy::collapse() Line 480  DataLazy::collapse()
480    m_op=IDENTITY;    m_op=IDENTITY;
481  }  }
482    
483  const double*  /*
484  DataLazy::resolveUnary(ValueType& v,int sampleNo,  size_t offset) const    \brief Compute the value of the expression (binary operation) for the given sample.
485      \return Vector which stores the value of the subexpression for the given sample.
486      \param v A vector to store intermediate results.
487      \param offset Index in v to begin storing results.
488      \param sampleNo Sample number to evaluate.
489      \param roffset (output parameter) the offset in the return vector where the result begins.
490    
491      The return value will be an existing vector so do not deallocate it.
492      If the result is stored in v it should be stored at the offset given.
493      Everything from offset to the end of v should be considered available for this method to use.
494    */
495    DataTypes::ValueType*
496    DataLazy::resolveUnary(ValueType& v, size_t offset, int sampleNo, size_t& roffset) const
497  {  {
498      // we assume that any collapsing has been done before we get here      // we assume that any collapsing has been done before we get here
499      // since we only have one argument we don't need to think about only      // since we only have one argument we don't need to think about only
# Line 405  DataLazy::resolveUnary(ValueType& v,int Line 502  DataLazy::resolveUnary(ValueType& v,int
502    {    {
503      throw DataException("Programmer error - resolveUnary should only be called on expanded Data.");      throw DataException("Programmer error - resolveUnary should only be called on expanded Data.");
504    }    }
505    const double* left=m_left->resolveSample(v,sampleNo,offset);    const ValueType* vleft=m_left->resolveSample(v,offset,sampleNo,roffset);
506      const double* left=&((*vleft)[roffset]);
507    double* result=&(v[offset]);    double* result=&(v[offset]);
508      roffset=offset;
509    switch (m_op)    switch (m_op)
510    {    {
511      case SIN:        case SIN:  
# Line 509  DataLazy::resolveUnary(ValueType& v,int Line 608  DataLazy::resolveUnary(ValueType& v,int
608      default:      default:
609      throw DataException("Programmer error - resolveUnary can not resolve operator "+opToString(m_op)+".");      throw DataException("Programmer error - resolveUnary can not resolve operator "+opToString(m_op)+".");
610    }    }
611    return result;    return &v;
612  }  }
613    
614    
615    
616    
617    
618  #define PROC_OP(X) \  #define PROC_OP(X) \
619      for (int i=0;i<steps;++i,resultp+=getNoValues()) \      for (int i=0;i<steps;++i,resultp+=resultStep) \
620      { \      { \
621  cout << "Step#" << i << " chunk=" << chunksize << endl; \         tensor_binary_operation(chunksize, &((*left)[lroffset]), &((*right)[rroffset]), resultp, X); \
622  cout << left[0] << left[1] << left[2] << endl; \         lroffset+=leftStep; \
623  cout << right[0] << right[1] << right[2] << endl; \         rroffset+=rightStep; \
        tensor_binary_operation(chunksize, left, right, resultp, X); \  
        left+=leftStep; \  
        right+=rightStep; \  
 cout << "Result=" << result << " " << result[0] << result[1] << result[2] << endl; \  
624      }      }
625    
626  const double*  /*
627  DataLazy::resolveBinary(ValueType& v,int sampleNo,  size_t offset) const    \brief Compute the value of the expression (binary operation) for the given sample.
628      \return Vector which stores the value of the subexpression for the given sample.
629      \param v A vector to store intermediate results.
630      \param offset Index in v to begin storing results.
631      \param sampleNo Sample number to evaluate.
632      \param roffset (output parameter) the offset in the return vector where the result begins.
633    
634      The return value will be an existing vector so do not deallocate it.
635      If the result is stored in v it should be stored at the offset given.
636      Everything from offset to the end of v should be considered available for this method to use.
637    */
638    // This method assumes that any subexpressions which evaluate to Constant or Tagged Data
639    // have already been collapsed to IDENTITY. So we must have at least one expanded child.
640    // If both children are expanded, then we can process them in a single operation (we treat
641    // the whole sample as one big datapoint.
642    // If one of the children is not expanded, then we need to treat each point in the sample
643    // individually.
644    // There is an additional complication when scalar operations are considered.
645    // For example, 2+Vector.
646    // In this case each double within the point is treated individually
647    DataTypes::ValueType*
648    DataLazy::resolveBinary(ValueType& v,  size_t offset, int sampleNo, size_t& roffset) const
649  {  {
     // again we assume that all collapsing has already been done  
     // so we have at least one expanded child.  
     // however, we could still have one of the children being not expanded.  
   
650  cout << "Resolve binary: " << toString() << endl;  cout << "Resolve binary: " << toString() << endl;
651    
652    const double* left=m_left->resolveSample(v,sampleNo,offset);    size_t lroffset=0, rroffset=0;    // offsets in the left and right result vectors
653  cout << "Done Left " << left[0] << left[1] << left[2] << endl;      // first work out which of the children are expanded
   const double* right=m_right->resolveSample(v,sampleNo,offset);      
 cout << "Done Right"  << right[0] << right[1] << right[2] << endl;  
     // now we need to know which args are expanded  
654    bool leftExp=(m_left->m_readytype=='E');    bool leftExp=(m_left->m_readytype=='E');
655    bool rightExp=(m_right->m_readytype=='E');    bool rightExp=(m_right->m_readytype=='E');
656    bool bigloops=((leftExp && rightExp) || (!leftExp && !rightExp)); // is processing in single step    bool bigloops=((leftExp && rightExp) || (!leftExp && !rightExp)); // is processing in single step?
657    int steps=(bigloops?1:getNumSamples());    int steps=(bigloops?1:getNumDPPSample());
658    size_t chunksize=(bigloops? m_samplesize : getNoValues());    size_t chunksize=(bigloops? m_samplesize : getNoValues());    // if bigloops, pretend the whole sample is a datapoint
659    int leftStep=(rightExp? getNoValues() : 0);    if (m_left->getRank()!=m_right->getRank())    // need to deal with scalar * ? ops
660    int rightStep=(leftExp? getNoValues() : 0);    {
661  cout << "left=" << left << " right=" << right << endl;      EsysAssert((m_left->getRank()==0) || (m_right->getRank()==0), "Error - Ranks must match unless one is 0.");
662    double* result=&(v[offset]);      steps=getNumDPPSample()*max(m_left->getNoValues(),m_right->getNoValues());
663    double* resultp=result;      chunksize=1;    // for scalar
664      }    
665      int leftStep=((leftExp && !rightExp)? m_right->getNoValues() : 0);
666      int rightStep=((rightExp && !leftExp)? m_left->getNoValues() : 0);
667      int resultStep=max(leftStep,rightStep);   // only one (at most) should be !=0
668        // Get the values of sub-expressions
669      const ValueType* left=m_left->resolveSample(v,offset,sampleNo,lroffset);
670      const ValueType* right=m_right->resolveSample(v,offset+m_samplesize,sampleNo,rroffset); // Note
671        // the right child starts further along.
672      double* resultp=&(v[offset]);     // results are stored at the vector offset we recieved
673    switch(m_op)    switch(m_op)
674    {    {
675      case ADD:      case ADD:
676      PROC_OP(plus<double>())      PROC_OP(plus<double>());
677        break;
678        case SUB:
679        PROC_OP(minus<double>());
680        break;
681        case MUL:
682        PROC_OP(multiplies<double>());
683        break;
684        case DIV:
685        PROC_OP(divides<double>());
686        break;
687        case POW:
688        PROC_OP(::pow);
689      break;      break;
 // need to fill in the rest  
690      default:      default:
691      throw DataException("Programmer error - resolveBinay can not resolve operator "+opToString(m_op)+".");      throw DataException("Programmer error - resolveBinary can not resolve operator "+opToString(m_op)+".");
692    }    }
693  cout << "About to return "  << result[0] << result[1] << result[2] << endl;;    roffset=offset;  
694    return result;    return &v;
695  }  }
696    
697    
698    
699    /*
700      \brief Compute the value of the expression for the given sample.
701      \return Vector which stores the value of the subexpression for the given sample.
702      \param v A vector to store intermediate results.
703      \param offset Index in v to begin storing results.
704      \param sampleNo Sample number to evaluate.
705      \param roffset (output parameter) the offset in the return vector where the result begins.
706    
707      The return value will be an existing vector so do not deallocate it.
708    */
709  // the vector and the offset are a place where the method could write its data if it wishes  // the vector and the offset are a place where the method could write its data if it wishes
710  // it is not obligated to do so. For example, if it has its own storage already, it can use that.  // it is not obligated to do so. For example, if it has its own storage already, it can use that.
711  // Hence the return value to indicate where the data is actually stored.  // Hence the return value to indicate where the data is actually stored.
712  // Regardless, the storage should be assumed to be used, even if it isn't.  // Regardless, the storage should be assumed to be used, even if it isn't.
713  const double*  
714  DataLazy::resolveSample(ValueType& v,int sampleNo,  size_t offset )  // the roffset is the offset within the returned vector where the data begins
715    const DataTypes::ValueType*
716    DataLazy::resolveSample(ValueType& v, size_t offset, int sampleNo, size_t& roffset)
717  {  {
718  cout << "Resolve sample " << toString() << endl;  cout << "Resolve sample " << toString() << endl;
719      // collapse so we have a 'E' node or an IDENTITY for some other type      // collapse so we have a 'E' node or an IDENTITY for some other type
# Line 575  cout << "Resolve sample " << toString() Line 721  cout << "Resolve sample " << toString()
721    {    {
722      collapse();      collapse();
723    }    }
 cout << "Post collapse check\n";  
724    if (m_op==IDENTITY)      if (m_op==IDENTITY)  
725    {    {
 cout << "In IDENTITY check\n";  
726      const ValueType& vec=m_id->getVector();      const ValueType& vec=m_id->getVector();
727      if (m_readytype=='C')      if (m_readytype=='C')
728      {      {
729      return &(vec[0]);      roffset=0;
730        return &(vec);
731      }      }
732      return &(vec[m_id->getPointOffset(sampleNo, 0)]);      roffset=m_id->getPointOffset(sampleNo, 0);
733        return &(vec);
734    }    }
735    if (m_readytype!='E')    if (m_readytype!='E')
736    {    {
737      throw DataException("Programmer Error - Collapse did not produce an expanded node.");      throw DataException("Programmer Error - Collapse did not produce an expanded node.");
738    }    }
 cout << "Calling sub resolvers\n";  
739    switch (getOpgroup(m_op))    switch (getOpgroup(m_op))
740    {    {
741    case G_UNARY: return resolveUnary(v,sampleNo,offset);    case G_UNARY: return resolveUnary(v, offset,sampleNo,roffset);
742    case G_BINARY: return resolveBinary(v,sampleNo,offset);    case G_BINARY: return resolveBinary(v, offset,sampleNo,roffset);
743    default:    default:
744      throw DataException("Programmer Error - resolveSample does not know how to process "+opToString(m_op)+".");      throw DataException("Programmer Error - resolveSample does not know how to process "+opToString(m_op)+".");
745    }    }
746  }  }
747    
748    
749  // the vector and the offset are a place where the method could write its data if it wishes  // To simplify the memory management, all threads operate on one large vector, rather than one each.
750  // it is not obligated to do so. For example, if it has its own storage already, it can use that.  // Each sample is evaluated independently and copied into the result DataExpanded.
 // Hence the return value to indicate where the data is actually stored.  
 // Regardless, the storage should be assumed to be used, even if it isn't.  
 const double*  
 DataLazy::resolveSample2(ValueType& v,int sampleNo,  size_t offset )  
 {  
   if (m_readytype!='E')  
   {  
     throw DataException("Only supporting Expanded Data.");  
   }  
   if (m_op==IDENTITY)    
   {  
     const ValueType& vec=m_id->getVector();  
     return &(vec[m_id->getPointOffset(sampleNo, 0)]);  
   }  
   size_t rightoffset=offset+m_samplesize;  
   const double* left=m_left->resolveSample(v,sampleNo,offset);  
   const double* right=0;  
   if (getOpgroup(m_op)==G_BINARY)  
   {  
     right=m_right->resolveSample(v,sampleNo,rightoffset);  
   }  
   double* result=&(v[offset]);  
   {  
     switch(m_op)  
     {  
     case ADD:       // since these are pointwise ops, pretend each sample is one point  
     tensor_binary_operation(m_samplesize, left, right, result, plus<double>());  
     break;  
     case SUB:        
     tensor_binary_operation(m_samplesize, left, right, result, minus<double>());  
     break;  
     case MUL:        
     tensor_binary_operation(m_samplesize, left, right, result, multiplies<double>());  
     break;  
     case DIV:        
     tensor_binary_operation(m_samplesize, left, right, result, divides<double>());  
     break;  
 // unary ops  
     case SIN:  
     tensor_unary_operation(m_samplesize, left, result, ::sin);  
     break;  
     case COS:  
     tensor_unary_operation(m_samplesize, left, result, ::cos);  
     break;  
     case TAN:  
     tensor_unary_operation(m_samplesize, left, result, ::tan);  
     break;  
     case ASIN:  
     tensor_unary_operation(m_samplesize, left, result, ::asin);  
     break;  
     case ACOS:  
     tensor_unary_operation(m_samplesize, left, result, ::acos);  
     break;  
     case ATAN:  
     tensor_unary_operation(m_samplesize, left, result, ::atan);  
     break;  
     case SINH:  
     tensor_unary_operation(m_samplesize, left, result, ::sinh);  
     break;  
     case COSH:  
     tensor_unary_operation(m_samplesize, left, result, ::cosh);  
     break;  
     case TANH:  
     tensor_unary_operation(m_samplesize, left, result, ::tanh);  
     break;  
     case ERF:  
 #ifdef _WIN32  
     throw DataException("Error - Data:: erf function is not supported on _WIN32 platforms.");  
 #else  
     tensor_unary_operation(m_samplesize, left, result, ::erf);  
     break;  
 #endif  
    case ASINH:  
 #ifdef _WIN32  
     tensor_unary_operation(m_samplesize, left, result, escript::asinh_substitute);  
 #else  
     tensor_unary_operation(m_samplesize, left, result, ::asinh);  
 #endif    
     break;  
    case ACOSH:  
 #ifdef _WIN32  
     tensor_unary_operation(m_samplesize, left, result, escript::acosh_substitute);  
 #else  
     tensor_unary_operation(m_samplesize, left, result, ::acosh);  
 #endif    
     break;  
    case ATANH:  
 #ifdef _WIN32  
     tensor_unary_operation(m_samplesize, left, result, escript::atanh_substitute);  
 #else  
     tensor_unary_operation(m_samplesize, left, result, ::atanh);  
 #endif    
     break;  
     case LOG10:  
     tensor_unary_operation(m_samplesize, left, result, ::log10);  
     break;  
     case LOG:  
     tensor_unary_operation(m_samplesize, left, result, ::log);  
     break;  
     case SIGN:  
     tensor_unary_operation(m_samplesize, left, result, escript::fsign);  
     break;  
     case ABS:  
     tensor_unary_operation(m_samplesize, left, result, ::fabs);  
     break;  
     case NEG:  
     tensor_unary_operation(m_samplesize, left, result, negate<double>());  
     break;  
     case POS:  
     // it doesn't mean anything for delayed.  
     // it will just trigger a deep copy of the lazy object  
     throw DataException("Programmer error - POS not supported for lazy data.");  
     break;  
     case EXP:  
     tensor_unary_operation(m_samplesize, left, result, ::exp);  
     break;  
     case SQRT:  
     tensor_unary_operation(m_samplesize, left, result, ::sqrt);  
     break;  
     case RECIP:  
     tensor_unary_operation(m_samplesize, left, result, bind1st(divides<double>(),1.));  
     break;  
     case GZ:  
     tensor_unary_operation(m_samplesize, left, result, bind2nd(greater<double>(),0.0));  
     break;  
     case LZ:  
     tensor_unary_operation(m_samplesize, left, result, bind2nd(less<double>(),0.0));  
     break;  
     case GEZ:  
     tensor_unary_operation(m_samplesize, left, result, bind2nd(greater_equal<double>(),0.0));  
     break;  
     case LEZ:  
     tensor_unary_operation(m_samplesize, left, result, bind2nd(less_equal<double>(),0.0));  
     break;  
   
     default:  
     throw DataException("Programmer error - do not know how to resolve operator "+opToString(m_op)+".");  
     }  
   }  
   return result;  
 }  
   
751  DataReady_ptr  DataReady_ptr
752  DataLazy::resolve()  DataLazy::resolve()
753  {  {
# Line 752  DataLazy::resolve() Line 755  DataLazy::resolve()
755  cout << "Sample size=" << m_samplesize << endl;  cout << "Sample size=" << m_samplesize << endl;
756  cout << "Buffers=" << m_buffsRequired << endl;  cout << "Buffers=" << m_buffsRequired << endl;
757    
758    if (m_readytype!='E')    if (m_readytype!='E')     // if the whole sub-expression is Constant or Tagged, then evaluate it normally
759    {    {
760      collapse();      collapse();
761    }    }
762    if (m_op==IDENTITY)    if (m_op==IDENTITY)       // So a lazy expression of Constant or Tagged data will be returned here.
763    {    {
764      return m_id;      return m_id;
765    }    }
766      // from this point on we must have m_op!=IDENTITY and m_readytype=='E'      // from this point on we must have m_op!=IDENTITY and m_readytype=='E'
767    size_t threadbuffersize=m_samplesize*(max(1,m_buffsRequired)+1);    size_t threadbuffersize=m_samplesize*(max(1,m_buffsRequired));    // Each thread needs to have enough
768        // storage to evaluate its expression
769    int numthreads=1;    int numthreads=1;
770  #ifdef _OPENMP  #ifdef _OPENMP
771    numthreads=getNumberOfThreads();    numthreads=getNumberOfThreads();
# Line 769  cout << "Buffers=" << m_buffsRequired << Line 773  cout << "Buffers=" << m_buffsRequired <<
773  #endif  #endif
774    ValueType v(numthreads*threadbuffersize);    ValueType v(numthreads*threadbuffersize);
775  cout << "Buffer created with size=" << v.size() << endl;  cout << "Buffer created with size=" << v.size() << endl;
776    ValueType dummy(getNoValues());    DataExpanded* result=new DataExpanded(getFunctionSpace(),getShape(),  ValueType(getNoValues()));
   DataExpanded* result=new DataExpanded(getFunctionSpace(),getShape(),dummy);  
777    ValueType& resvec=result->getVector();    ValueType& resvec=result->getVector();
778    DataReady_ptr resptr=DataReady_ptr(result);    DataReady_ptr resptr=DataReady_ptr(result);
779    int sample;    int sample;
780    int resoffset;    size_t outoffset;     // offset in the output data
781    int totalsamples=getNumSamples();    int totalsamples=getNumSamples();
782    #pragma omp parallel for private(sample,resoffset,threadnum) schedule(static)    const ValueType* res=0;   // Vector storing the answer
783      size_t resoffset=0;       // where in the vector to find the answer
784      #pragma omp parallel for private(sample,resoffset,outoffset,threadnum,res) schedule(static)
785    for (sample=0;sample<totalsamples;++sample)    for (sample=0;sample<totalsamples;++sample)
786    {    {
787    cout << "################################# " << sample << endl;
788  #ifdef _OPENMP  #ifdef _OPENMP
789      const double* res=resolveSample(v,sample,threadbuffersize*omp_get_thread_num());      res=resolveSample(v,threadbuffersize*omp_get_thread_num(),sample,resoffset);
790  #else  #else
791      const double* res=resolveSample(v,sample,0);   // this would normally be v, but not if its a single IDENTITY op.      res=resolveSample(v,0,sample,resoffset);   // res would normally be v, but not if its a single IDENTITY op.
792  #endif  #endif
793      resoffset=result->getPointOffset(sample,0);  cerr << "-------------------------------- " << endl;
794      for (unsigned int i=0;i<m_samplesize;++i,++resoffset)   // copy values into the output vector      outoffset=result->getPointOffset(sample,0);
795    cerr << "offset=" << outoffset << endl;
796        for (unsigned int i=0;i<m_samplesize;++i,++outoffset,++resoffset)   // copy values into the output vector
797      {      {
798      resvec[resoffset]=res[i];      resvec[outoffset]=(*res)[resoffset];
799      }      }
800    cerr << "*********************************" << endl;
801    }    }
802    return resptr;    return resptr;
803  }  }
# Line 802  DataLazy::toString() const Line 811  DataLazy::toString() const
811    return oss.str();    return oss.str();
812  }  }
813    
814    
815  void  void
816  DataLazy::intoString(ostringstream& oss) const  DataLazy::intoString(ostringstream& oss) const
817  {  {
# Line 843  DataLazy::intoString(ostringstream& oss) Line 853  DataLazy::intoString(ostringstream& oss)
853    }    }
854  }  }
855    
 // Note that in this case, deepCopy does not make copies of the leaves.  
 // Hopefully copy on write (or whatever we end up using) will take care of this.  
856  DataAbstract*  DataAbstract*
857  DataLazy::deepCopy()  DataLazy::deepCopy()
858  {  {
859    if (m_op==IDENTITY)    switch (getOpgroup(m_op))
860    {    {
861      return new DataLazy(m_left);    // we don't need to copy the child here    case G_IDENTITY:  return new DataLazy(m_id->deepCopy()->getPtr());
862      case G_UNARY: return new DataLazy(m_left->deepCopy()->getPtr(),m_op);
863      case G_BINARY:    return new DataLazy(m_left->deepCopy()->getPtr(),m_right->deepCopy()->getPtr(),m_op);
864      default:
865        throw DataException("Programmer error - do not know how to deepcopy operator "+opToString(m_op)+".");
866    }    }
   return new DataLazy(m_left->deepCopy()->getPtr(),m_right->deepCopy()->getPtr(),m_op);  
867  }  }
868    
869    
# Line 869  DataLazy::getSlice(const DataTypes::Regi Line 880  DataLazy::getSlice(const DataTypes::Regi
880    throw DataException("getSlice - not implemented for Lazy objects.");    throw DataException("getSlice - not implemented for Lazy objects.");
881  }  }
882    
883    
884    // To do this we need to rely on our child nodes
885    DataTypes::ValueType::size_type
886    DataLazy::getPointOffset(int sampleNo,
887                     int dataPointNo)
888    {
889      if (m_op==IDENTITY)
890      {
891        return m_id->getPointOffset(sampleNo,dataPointNo);
892      }
893      if (m_readytype!='E')
894      {
895        collapse();
896        return m_id->getPointOffset(sampleNo,dataPointNo);
897      }
898      // at this point we do not have an identity node and the expression will be Expanded
899      // so we only need to know which child to ask
900      if (m_left->m_readytype=='E')
901      {
902        return m_left->getPointOffset(sampleNo,dataPointNo);
903      }
904      else
905      {
906        return m_right->getPointOffset(sampleNo,dataPointNo);
907      }
908    }
909    
910    // To do this we need to rely on our child nodes
911  DataTypes::ValueType::size_type  DataTypes::ValueType::size_type
912  DataLazy::getPointOffset(int sampleNo,  DataLazy::getPointOffset(int sampleNo,
913                   int dataPointNo) const                   int dataPointNo) const
914  {  {
915    throw DataException("getPointOffset - not implemented for Lazy objects - yet.");    if (m_op==IDENTITY)
916      {
917        return m_id->getPointOffset(sampleNo,dataPointNo);
918      }
919      if (m_readytype=='E')
920      {
921        // at this point we do not have an identity node and the expression will be Expanded
922        // so we only need to know which child to ask
923        if (m_left->m_readytype=='E')
924        {
925        return m_left->getPointOffset(sampleNo,dataPointNo);
926        }
927        else
928        {
929        return m_right->getPointOffset(sampleNo,dataPointNo);
930        }
931      }
932      if (m_readytype=='C')
933      {
934        return m_left->getPointOffset(sampleNo,dataPointNo); // which child doesn't matter
935      }
936      throw DataException("Programmer error - getPointOffset on lazy data may require collapsing (but this object is marked const).");
937    }
938    
939    // It would seem that DataTagged will need to be treated differently since even after setting all tags
940    // to zero, all the tags from all the DataTags would be in the result.
941    // However since they all have the same value (0) whether they are there or not should not matter.
942    // So I have decided that for all types this method will create a constant 0.
943    // It can be promoted up as required.
944    // A possible efficiency concern might be expanded->constant->expanded which has an extra memory management
945    // but we can deal with that if it arrises.
946    void
947    DataLazy::setToZero()
948    {
949      DataTypes::ValueType v(getNoValues(),0);
950      m_id=DataReady_ptr(new DataConstant(getFunctionSpace(),getShape(),v));
951      m_op=IDENTITY;
952      m_right.reset();  
953      m_left.reset();
954      m_readytype='C';
955      m_buffsRequired=1;
956  }  }
957    
958  }   // end namespace  }   // end namespace

Legend:
Removed from v.1889  
changed lines
  Added in v.1950

  ViewVC Help
Powered by ViewVC 1.1.26