xref: /trunk/main/sc/source/core/tool/interpr5.cxx (revision e8df90a080f9dc7518c4b937d7dcd461d7b4d178) !
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_sc.hxx"
26 
27 // INCLUDE ---------------------------------------------------------------
28 
29 #ifndef INCLUDED_RTL_MATH_HXX
30 #include <rtl/math.hxx>
31 #endif
32 #include <rtl/logfile.hxx>
33 #include <string.h>
34 #include <math.h>
35 #include <stdio.h>
36 
37 #if OSL_DEBUG_LEVEL > 1
38 #include <stdio.h>
39 #endif
40 #include <unotools/bootstrap.hxx>
41 #include <svl/zforlist.hxx>
42 
43 #include "interpre.hxx"
44 #include "global.hxx"
45 #include "compiler.hxx"
46 #include "cell.hxx"
47 #include "document.hxx"
48 #include "dociter.hxx"
49 #include "scmatrix.hxx"
50 #include "globstr.hrc"
51 #include "cellkeytranslator.hxx"
52 
53 #include <string.h>
54 #include <math.h>
55 #include <vector>
56 
57 using ::std::vector;
58 using namespace formula;
59 
60 const double fInvEpsilon = 1.0E-7;
61 
62 // -----------------------------------------------------------------------
63     struct MatrixAdd
64     {
65         typedef double first_argument_type;
66         typedef double second_argument_type;
67         typedef double result_type;
operator ()MatrixAdd68         inline double operator() (const double& lhs, const double& rhs) const
69         {
70             return ::rtl::math::approxAdd( lhs,rhs);
71         }
72     };
73     struct MatrixSub
74     {
75         typedef double first_argument_type;
76         typedef double second_argument_type;
77         typedef double result_type;
operator ()MatrixSub78         inline double operator() (const double& lhs, const double& rhs) const
79         {
80             return ::rtl::math::approxSub( lhs,rhs);
81         }
82     };
83     struct MatrixMul
84     {
85         typedef double first_argument_type;
86         typedef double second_argument_type;
87         typedef double result_type;
operator ()MatrixMul88         inline double operator() (const double& lhs, const double& rhs) const
89         {
90             return lhs * rhs;
91         }
92     };
93     struct MatrixDiv
94     {
95         typedef double first_argument_type;
96         typedef double second_argument_type;
97         typedef double result_type;
operator ()MatrixDiv98         inline double operator() (const double& lhs, const double& rhs) const
99         {
100             return ScInterpreter::div( lhs,rhs);
101         }
102     };
103     struct MatrixPow
104     {
105         typedef double first_argument_type;
106         typedef double second_argument_type;
107         typedef double result_type;
operator ()MatrixPow108         inline double operator() (const double& lhs, const double& rhs) const
109         {
110             return ::pow( lhs,rhs);
111         }
112     };
113 
ScGetGCD(double fx,double fy)114 double ScInterpreter::ScGetGCD(double fx, double fy)
115 {
116     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::div" );
117     // By ODFF definition GCD(0,a) => a. This is also vital for the code in
118     // ScGCD() to work correctly with a preset fy=0.0
119     if (fy == 0.0)
120         return fx;
121     else if (fx == 0.0)
122         return fy;
123     else
124     {
125         double fz = fmod(fx, fy);
126         while (fz > 0.0)
127         {
128             fx = fy;
129             fy = fz;
130             fz = fmod(fx, fy);
131         }
132         return fy;
133     }
134 }
135 
ScGCD()136 void ScInterpreter::ScGCD()
137 {
138     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGCD" );
139     short nParamCount = GetByte();
140     if ( MustHaveParamCountMin( nParamCount, 1 ) )
141     {
142         double fx, fy = 0.0;
143         ScRange aRange;
144         size_t nRefInList = 0;
145         while (!nGlobalError && nParamCount-- > 0)
146         {
147             switch (GetStackType())
148             {
149                 case svDouble :
150                 case svString:
151                 case svSingleRef:
152                 {
153                     fx = ::rtl::math::approxFloor( GetDouble());
154                     if (fx < 0.0)
155                     {
156                         PushIllegalArgument();
157                         return;
158                     }
159                     fy = ScGetGCD(fx, fy);
160                 }
161                 break;
162                 case svDoubleRef :
163                 case svRefList :
164                 {
165                     sal_uInt16 nErr = 0;
166                     PopDoubleRef( aRange, nParamCount, nRefInList);
167                     double nCellVal;
168                     ScValueIterator aValIter(pDok, aRange, glSubTotal);
169                     if (aValIter.GetFirst(nCellVal, nErr))
170                     {
171                         do
172                         {
173                             fx = ::rtl::math::approxFloor( nCellVal);
174                             if (fx < 0.0)
175                             {
176                                 PushIllegalArgument();
177                                 return;
178                             }
179                             fy = ScGetGCD(fx, fy);
180                         } while (nErr == 0 && aValIter.GetNext(nCellVal, nErr));
181                     }
182                     SetError(nErr);
183                 }
184                 break;
185                 case svMatrix :
186                 {
187                     ScMatrixRef pMat = PopMatrix();
188                     if (pMat)
189                     {
190                         SCSIZE nC, nR;
191                         pMat->GetDimensions(nC, nR);
192                         if (nC == 0 || nR == 0)
193                             SetError(errIllegalArgument);
194                         else
195                         {
196                             SCSIZE nCount = nC * nR;
197                             for ( SCSIZE j = 0; j < nCount; j++ )
198                             {
199                                 if (!pMat->IsValue(j))
200                                 {
201                                     PushIllegalArgument();
202                                     return;
203                                 }
204                                 fx = ::rtl::math::approxFloor( pMat->GetDouble(j));
205                                 if (fx < 0.0)
206                                 {
207                                     PushIllegalArgument();
208                                     return;
209                                 }
210                                 fy = ScGetGCD(fx, fy);
211                             }
212                         }
213                     }
214                 }
215                 break;
216                 default : SetError(errIllegalParameter); break;
217             }
218         }
219         PushDouble(fy);
220     }
221 }
222 
ScLCM()223 void ScInterpreter:: ScLCM()
224 {
225     short nParamCount = GetByte();
226     if ( MustHaveParamCountMin( nParamCount, 1 ) )
227     {
228         double fx, fy = 1.0;
229         ScRange aRange;
230         size_t nRefInList = 0;
231         while (!nGlobalError && nParamCount-- > 0)
232         {
233             switch (GetStackType())
234             {
235                 case svDouble :
236                 case svString:
237                 case svSingleRef:
238                 {
239                     fx = ::rtl::math::approxFloor( GetDouble());
240                     if (fx < 0.0)
241                     {
242                         PushIllegalArgument();
243                         return;
244                     }
245                     if (fx == 0.0 || fy == 0.0)
246                         fy = 0.0;
247                     else
248                         fy = fx * fy / ScGetGCD(fx, fy);
249                 }
250                 break;
251                 case svDoubleRef :
252                 case svRefList :
253                 {
254                     sal_uInt16 nErr = 0;
255                     PopDoubleRef( aRange, nParamCount, nRefInList);
256                     double nCellVal;
257                     ScValueIterator aValIter(pDok, aRange, glSubTotal);
258                     if (aValIter.GetFirst(nCellVal, nErr))
259                     {
260                         do
261                         {
262                             fx = ::rtl::math::approxFloor( nCellVal);
263                             if (fx < 0.0)
264                             {
265                                 PushIllegalArgument();
266                                 return;
267                             }
268                             if (fx == 0.0 || fy == 0.0)
269                                 fy = 0.0;
270                             else
271                                 fy = fx * fy / ScGetGCD(fx, fy);
272                         } while (nErr == 0 && aValIter.GetNext(nCellVal, nErr));
273                     }
274                     SetError(nErr);
275                 }
276                 break;
277                 case svMatrix :
278                 {
279                     ScMatrixRef pMat = PopMatrix();
280                     if (pMat)
281                     {
282                         SCSIZE nC, nR;
283                         pMat->GetDimensions(nC, nR);
284                         if (nC == 0 || nR == 0)
285                             SetError(errIllegalArgument);
286                         else
287                         {
288                             SCSIZE nCount = nC * nR;
289                             for ( SCSIZE j = 0; j < nCount; j++ )
290                             {
291                                 if (!pMat->IsValue(j))
292                                 {
293                                     PushIllegalArgument();
294                                     return;
295                                 }
296                                 fx = ::rtl::math::approxFloor( pMat->GetDouble(j));
297                                 if (fx < 0.0)
298                                 {
299                                     PushIllegalArgument();
300                                     return;
301                                 }
302                                 if (fx == 0.0 || fy == 0.0)
303                                     fy = 0.0;
304                                 else
305                                     fy = fx * fy / ScGetGCD(fx, fy);
306                             }
307                         }
308                     }
309                 }
310                 break;
311                 default : SetError(errIllegalParameter); break;
312             }
313         }
314         PushDouble(fy);
315     }
316 }
317 
GetNewMat(SCSIZE nC,SCSIZE nR)318 ScMatrixRef ScInterpreter::GetNewMat(SCSIZE nC, SCSIZE nR)
319 {
320     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::GetNewMat" );
321     ScMatrix* pMat = new ScMatrix( nC, nR);
322     pMat->SetErrorInterpreter( this);
323     // A temporary matrix is mutable and ScMatrix::CloneIfConst() returns the
324     // very matrix.
325     pMat->SetImmutable( false);
326     SCSIZE nCols, nRows;
327     pMat->GetDimensions( nCols, nRows);
328     if ( nCols != nC || nRows != nR )
329     {   // arbitrary limit of elements exceeded
330         SetError( errStackOverflow);
331         pMat->Delete();
332         pMat = NULL;
333     }
334     return pMat;
335 }
336 
CreateMatrixFromDoubleRef(const FormulaToken * pToken,SCCOL nCol1,SCROW nRow1,SCTAB nTab1,SCCOL nCol2,SCROW nRow2,SCTAB nTab2)337 ScMatrixRef ScInterpreter::CreateMatrixFromDoubleRef( const FormulaToken* pToken,
338         SCCOL nCol1, SCROW nRow1, SCTAB nTab1,
339         SCCOL nCol2, SCROW nRow2, SCTAB nTab2 )
340 {
341     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::CreateMatrixFromDoubleRef" );
342     ScMatrixRef pMat = NULL;
343     if (nTab1 == nTab2 && !nGlobalError)
344     {
345         ScTokenMatrixMap::const_iterator aIter;
346         if ( static_cast<SCSIZE>(nRow2 - nRow1 + 1) *
347                 static_cast<SCSIZE>(nCol2 - nCol1 + 1) >
348                 ScMatrix::GetElementsMax() )
349             SetError(errStackOverflow);
350         else if (pTokenMatrixMap && ((aIter = pTokenMatrixMap->find( pToken))
351                     != pTokenMatrixMap->end()))
352             pMat = static_cast<ScToken*>((*aIter).second.get())->GetMatrix();
353         else
354         {
355             SCSIZE nMatCols = static_cast<SCSIZE>(nCol2 - nCol1 + 1);
356             SCSIZE nMatRows = static_cast<SCSIZE>(nRow2 - nRow1 + 1);
357             pMat = GetNewMat( nMatCols, nMatRows);
358             if (pMat && !nGlobalError)
359             {
360                 // Set position where the next entry is expected.
361                 SCROW nNextRow = nRow1;
362                 SCCOL nNextCol = nCol1;
363                 // Set last position as if there was a previous entry.
364                 SCROW nThisRow = nRow2;
365                 SCCOL nThisCol = nCol1 - 1;
366                 ScCellIterator aCellIter( pDok, nCol1, nRow1, nTab1, nCol2,
367                         nRow2, nTab2);
368                 for (ScBaseCell* pCell = aCellIter.GetFirst(); pCell; pCell =
369                         aCellIter.GetNext())
370                 {
371                     nThisCol = aCellIter.GetCol();
372                     nThisRow = aCellIter.GetRow();
373                     if (nThisCol != nNextCol || nThisRow != nNextRow)
374                     {
375                         // Fill empty between iterator's positions.
376                         for ( ; nNextCol <= nThisCol; ++nNextCol)
377                         {
378                             SCSIZE nC = nNextCol - nCol1;
379                             SCSIZE nMatStopRow = ((nNextCol < nThisCol) ?
380                                     nMatRows : nThisRow - nRow1);
381                             for (SCSIZE nR = nNextRow - nRow1; nR <
382                                     nMatStopRow; ++nR)
383                             {
384                                 pMat->PutEmpty( nC, nR);
385                             }
386                             nNextRow = nRow1;
387                         }
388                     }
389                     if (nThisRow == nRow2)
390                     {
391                         nNextCol = nThisCol + 1;
392                         nNextRow = nRow1;
393                     }
394                     else
395                     {
396                         nNextCol = nThisCol;
397                         nNextRow = nThisRow + 1;
398                     }
399                     if (HasCellEmptyData(pCell))
400                     {
401                         pMat->PutEmpty( static_cast<SCSIZE>(nThisCol-nCol1),
402                                 static_cast<SCSIZE>(nThisRow-nRow1));
403                     }
404                     else if (HasCellValueData(pCell))
405                     {
406                         ScAddress aAdr( nThisCol, nThisRow, nTab1);
407                         double fVal = GetCellValue( aAdr, pCell);
408                         if ( nGlobalError )
409                         {
410                             fVal = CreateDoubleError( nGlobalError);
411                             nGlobalError = 0;
412                         }
413                         pMat->PutDouble( fVal,
414                                 static_cast<SCSIZE>(nThisCol-nCol1),
415                                 static_cast<SCSIZE>(nThisRow-nRow1));
416                     }
417                     else
418                     {
419                         String aStr;
420                         GetCellString( aStr, pCell);
421                         if ( nGlobalError )
422                         {
423                             double fVal = CreateDoubleError( nGlobalError);
424                             nGlobalError = 0;
425                             pMat->PutDouble( fVal,
426                                     static_cast<SCSIZE>(nThisCol-nCol1),
427                                     static_cast<SCSIZE>(nThisRow-nRow1));
428                         }
429                         else
430                             pMat->PutString( aStr,
431                                     static_cast<SCSIZE>(nThisCol-nCol1),
432                                     static_cast<SCSIZE>(nThisRow-nRow1));
433                     }
434                 }
435                 // Fill empty if iterator's last position wasn't the end.
436                 if (nThisCol != nCol2 || nThisRow != nRow2)
437                 {
438                     for ( ; nNextCol <= nCol2; ++nNextCol)
439                     {
440                         SCSIZE nC = nNextCol - nCol1;
441                         for (SCSIZE nR = nNextRow - nRow1; nR < nMatRows; ++nR)
442                         {
443                             pMat->PutEmpty( nC, nR);
444                         }
445                         nNextRow = nRow1;
446                     }
447                 }
448                 if (pTokenMatrixMap)
449                     pTokenMatrixMap->insert( ScTokenMatrixMap::value_type(
450                                 pToken, new ScMatrixToken( pMat)));
451             }
452         }
453     }
454     else                                // not a 2D matrix
455         SetError(errIllegalParameter);
456     return pMat;
457 }
458 
459 
GetMatrix()460 ScMatrixRef ScInterpreter::GetMatrix()
461 {
462     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::GetMatrix" );
463     ScMatrixRef pMat = NULL;
464     switch (GetRawStackType())
465     {
466         case svSingleRef :
467         {
468             ScAddress aAdr;
469             PopSingleRef( aAdr );
470             pMat = GetNewMat(1, 1);
471             if (pMat)
472             {
473                 ScBaseCell* pCell = GetCell( aAdr );
474                 if (HasCellEmptyData(pCell))
475                     pMat->PutEmpty( 0 );
476                 else if (HasCellValueData(pCell))
477                     pMat->PutDouble(GetCellValue(aAdr, pCell), 0);
478                 else
479                 {
480                     String aStr;
481                     GetCellString(aStr, pCell);
482                     pMat->PutString(aStr, 0);
483                 }
484             }
485         }
486         break;
487         case svDoubleRef:
488         {
489             SCCOL nCol1, nCol2;
490             SCROW nRow1, nRow2;
491             SCTAB nTab1, nTab2;
492             const ScToken* p = sp ? static_cast<const ScToken*>(pStack[sp-1]) : NULL;
493             PopDoubleRef(nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
494             pMat = CreateMatrixFromDoubleRef( p, nCol1, nRow1, nTab1,
495                     nCol2, nRow2, nTab2);
496         }
497         break;
498         case svMatrix:
499             pMat = PopMatrix();
500         break;
501         case svError :
502         case svMissing :
503         case svDouble :
504         {
505             double fVal = GetDouble();
506             pMat = GetNewMat( 1, 1);
507             if ( pMat )
508             {
509                 if ( nGlobalError )
510                 {
511                     fVal = CreateDoubleError( nGlobalError);
512                     nGlobalError = 0;
513                 }
514                 pMat->PutDouble( fVal, 0);
515             }
516         }
517         break;
518         case svString :
519         {
520             String aStr = GetString();
521             pMat = GetNewMat( 1, 1);
522             if ( pMat )
523             {
524                 if ( nGlobalError )
525                 {
526                     double fVal = CreateDoubleError( nGlobalError);
527                     pMat->PutDouble( fVal, 0);
528                     nGlobalError = 0;
529                 }
530                 else
531                     pMat->PutString( aStr, 0);
532             }
533         }
534         break;
535         default:
536             PopError();
537             SetError( errIllegalArgument);
538         break;
539     }
540     return pMat;
541 }
542 
ScMatValue()543 void ScInterpreter::ScMatValue()
544 {
545     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMatValue" );
546     if ( MustHaveParamCount( GetByte(), 3 ) )
547     {
548         // 0 to count-1
549         SCSIZE nR = static_cast<SCSIZE>(::rtl::math::approxFloor(GetDouble()));
550         SCSIZE nC = static_cast<SCSIZE>(::rtl::math::approxFloor(GetDouble()));
551         switch (GetStackType())
552         {
553             case svSingleRef :
554             {
555                 ScAddress aAdr;
556                 PopSingleRef( aAdr );
557                 ScBaseCell* pCell = GetCell( aAdr );
558                 if (pCell && pCell->GetCellType() == CELLTYPE_FORMULA)
559                 {
560                     sal_uInt16 nErrCode = ((ScFormulaCell*)pCell)->GetErrCode();
561                     if (nErrCode != 0)
562                         PushError( nErrCode);
563                     else
564                     {
565                         const ScMatrix* pMat = ((ScFormulaCell*)pCell)->GetMatrix();
566                         CalculateMatrixValue(pMat,nC,nR);
567                     }
568                 }
569                 else
570                     PushIllegalParameter();
571             }
572             break;
573             case svDoubleRef :
574             {
575                 SCCOL nCol1;
576                 SCROW nRow1;
577                 SCTAB nTab1;
578                 SCCOL nCol2;
579                 SCROW nRow2;
580                 SCTAB nTab2;
581                 PopDoubleRef(nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
582                 if (nCol2 - nCol1 >= static_cast<SCCOL>(nR) &&
583                         nRow2 - nRow1 >= static_cast<SCROW>(nC) &&
584                         nTab1 == nTab2)
585                 {
586                     ScAddress aAdr( sal::static_int_cast<SCCOL>( nCol1 + nR ),
587                                     sal::static_int_cast<SCROW>( nRow1 + nC ), nTab1 );
588                     ScBaseCell* pCell = GetCell( aAdr );
589                     if (HasCellValueData(pCell))
590                         PushDouble(GetCellValue( aAdr, pCell ));
591                     else
592                     {
593                         String aStr;
594                         GetCellString(aStr, pCell);
595                         PushString(aStr);
596                     }
597                 }
598                 else
599                     PushNoValue();
600             }
601             break;
602             case svMatrix:
603             {
604                 ScMatrixRef pMat = PopMatrix();
605                 CalculateMatrixValue(pMat,nC,nR);
606             }
607             break;
608             default:
609                 PopError();
610                 PushIllegalParameter();
611             break;
612         }
613     }
614 }
CalculateMatrixValue(const ScMatrix * pMat,SCSIZE nC,SCSIZE nR)615 void ScInterpreter::CalculateMatrixValue(const ScMatrix* pMat,SCSIZE nC,SCSIZE nR)
616 {
617     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::CalculateMatrixValue" );
618     if (pMat)
619     {
620         SCSIZE nCl, nRw;
621         pMat->GetDimensions(nCl, nRw);
622         if (nC < nCl && nR < nRw)
623         {
624             ScMatValType nMatValType;
625             const ScMatrixValue* pMatVal = pMat->Get( nC, nR,nMatValType);
626             if (ScMatrix::IsNonValueType( nMatValType))
627                 PushString( pMatVal->GetString() );
628             else
629                 PushDouble(pMatVal->fVal);
630                 // also handles DoubleError
631         }
632         else
633             PushNoValue();
634     }
635     else
636         PushNoValue();
637 }
638 
ScEMat()639 void ScInterpreter::ScEMat()
640 {
641     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScEMat" );
642     if ( MustHaveParamCount( GetByte(), 1 ) )
643     {
644         SCSIZE nDim = static_cast<SCSIZE>(::rtl::math::approxFloor(GetDouble()));
645         if ( nDim * nDim > ScMatrix::GetElementsMax() || nDim == 0)
646             PushIllegalArgument();
647         else
648         {
649             ScMatrixRef pRMat = GetNewMat(nDim, nDim);
650             if (pRMat)
651             {
652                 MEMat(pRMat, nDim);
653                 PushMatrix(pRMat);
654             }
655             else
656                 PushIllegalArgument();
657         }
658     }
659 }
660 
MEMat(ScMatrix * mM,SCSIZE n)661 void ScInterpreter::MEMat(ScMatrix* mM, SCSIZE n)
662 {
663     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::MEMat" );
664     mM->FillDouble(0.0, 0, 0, n-1, n-1);
665     for (SCSIZE i = 0; i < n; i++)
666         mM->PutDouble(1.0, i, i);
667 }
668 
669 /* Matrix LUP decomposition according to the pseudocode of "Introduction to
670  * Algorithms" by Cormen, Leiserson, Rivest, Stein.
671  *
672  * Added scaling for numeric stability.
673  *
674  * Given an n x n nonsingular matrix A, find a permutation matrix P, a unit
675  * lower-triangular matrix L, and an upper-triangular matrix U such that PA=LU.
676  * Compute L and U "in place" in the matrix A, the original content is
677  * destroyed. Note that the diagonal elements of the U triangular matrix
678  * replace the diagonal elements of the L-unit matrix (that are each ==1). The
679  * permutation matrix P is an array, where P[i]=j means that the i-th row of P
680  * contains a 1 in column j. Additionally keep track of the number of
681  * permutations (row exchanges).
682  *
683  * Returns 0 if a singular matrix is encountered, else +1 if an even number of
684  * permutations occurred, or -1 if odd, which is the sign of the determinant.
685  * This may be used to calculate the determinant by multiplying the sign with
686  * the product of the diagonal elements of the LU matrix.
687  */
lcl_LUP_decompose(ScMatrix * mA,const SCSIZE n,::std::vector<SCSIZE> & P)688 static int lcl_LUP_decompose( ScMatrix* mA, const SCSIZE n,
689         ::std::vector< SCSIZE> & P )
690 {
691     int nSign = 1;
692     // Find scale of each row.
693     ::std::vector< double> aScale(n);
694     for (SCSIZE i=0; i < n; ++i)
695     {
696         double fMax = 0.0;
697         for (SCSIZE j=0; j < n; ++j)
698         {
699             double fTmp = fabs( mA->GetDouble( j, i));
700             if (fMax < fTmp)
701                 fMax = fTmp;
702         }
703         if (fMax == 0.0)
704             return 0;       // singular matrix
705         aScale[i] = 1.0 / fMax;
706     }
707     // Represent identity permutation, P[i]=i
708     for (SCSIZE i=0; i < n; ++i)
709         P[i] = i;
710     // "Recursion" on the diagonale.
711     SCSIZE l = n - 1;
712     for (SCSIZE k=0; k < l; ++k)
713     {
714         // Implicit pivoting. With the scale found for a row, compare values of
715         // a column and pick largest.
716         double fMax = 0.0;
717         double fScale = aScale[k];
718         SCSIZE kp = k;
719         for (SCSIZE i = k; i < n; ++i)
720         {
721             double fTmp = fScale * fabs( mA->GetDouble( k, i));
722             if (fMax < fTmp)
723             {
724                 fMax = fTmp;
725                 kp = i;
726             }
727         }
728         if (fMax == 0.0)
729             return 0;       // singular matrix
730         // Swap rows. The pivot element will be at mA[k,kp] (row,col notation)
731         if (k != kp)
732         {
733             // permutations
734             SCSIZE nTmp = P[k];
735             P[k]        = P[kp];
736             P[kp]       = nTmp;
737             nSign       = -nSign;
738             // scales
739             double fTmp = aScale[k];
740             aScale[k]   = aScale[kp];
741             aScale[kp]  = fTmp;
742             // elements
743             for (SCSIZE i=0; i < n; ++i)
744             {
745                 double fMatTmp = mA->GetDouble( i, k);
746                 mA->PutDouble( mA->GetDouble( i, kp), i, k);
747                 mA->PutDouble( fMatTmp, i, kp);
748             }
749         }
750         // Compute Schur complement.
751         for (SCSIZE i = k+1; i < n; ++i)
752         {
753             double fTmp = mA->GetDouble( k, i) / mA->GetDouble( k, k);
754             mA->PutDouble( fTmp, k, i);
755             for (SCSIZE j = k+1; j < n; ++j)
756                 mA->PutDouble( mA->GetDouble( j, i) - fTmp * mA->GetDouble( j,
757                             k), j, i);
758         }
759     }
760 #if OSL_DEBUG_LEVEL > 1
761     fprintf( stderr, "\n%s\n", "lcl_LUP_decompose(): LU");
762     for (SCSIZE i=0; i < n; ++i)
763     {
764         for (SCSIZE j=0; j < n; ++j)
765             fprintf( stderr, "%8.2g  ", mA->GetDouble( j, i));
766         fprintf( stderr, "\n%s\n", "");
767     }
768     fprintf( stderr, "\n%s\n", "lcl_LUP_decompose(): P");
769     for (SCSIZE j=0; j < n; ++j)
770         fprintf( stderr, "%5u ", (unsigned)P[j]);
771     fprintf( stderr, "\n%s\n", "");
772 #endif
773 
774     bool bSingular=false;
775     for (SCSIZE i=0; i < n && !bSingular; i++)
776         bSingular = (mA->GetDouble(i,i) == 0.0);
777     if (bSingular)
778         nSign = 0;
779 
780     return nSign;
781 }
782 
783 
784 /* Solve a LUP decomposed equation Ax=b. LU is a combined matrix of L and U
785  * triangulars and P the permutation vector as obtained from
786  * lcl_LUP_decompose(). B is the right-hand side input vector, X is used to
787  * return the solution vector.
788  */
lcl_LUP_solve(const ScMatrix * mLU,const SCSIZE n,const::std::vector<SCSIZE> & P,const::std::vector<double> & B,::std::vector<double> & X)789 static void lcl_LUP_solve( const ScMatrix* mLU, const SCSIZE n,
790         const ::std::vector< SCSIZE> & P, const ::std::vector< double> & B,
791         ::std::vector< double> & X )
792 {
793     SCSIZE nFirst = SCSIZE_MAX;
794     // Ax=b => PAx=Pb, with decomposition LUx=Pb.
795     // Define y=Ux and solve for y in Ly=Pb using forward substitution.
796     for (SCSIZE i=0; i < n; ++i)
797     {
798         double fSum = B[P[i]];
799         // Matrix inversion comes with a lot of zeros in the B vectors, we
800         // don't have to do all the computing with results multiplied by zero.
801         // Until then, simply lookout for the position of the first nonzero
802         // value.
803         if (nFirst != SCSIZE_MAX)
804         {
805             for (SCSIZE j = nFirst; j < i; ++j)
806                 fSum -= mLU->GetDouble( j, i) * X[j];   // X[j] === y[j]
807         }
808         else if (fSum)
809             nFirst = i;
810         X[i] = fSum;                                    // X[i] === y[i]
811     }
812     // Solve for x in Ux=y using back substitution.
813     for (SCSIZE i = n; i--; )
814     {
815         double fSum = X[i];                             // X[i] === y[i]
816         for (SCSIZE j = i+1; j < n; ++j)
817             fSum -= mLU->GetDouble( j, i) * X[j];       // X[j] === x[j]
818         X[i] = fSum / mLU->GetDouble( i, i);            // X[i] === x[i]
819     }
820 #if OSL_DEBUG_LEVEL >1
821     fprintf( stderr, "\n%s\n", "lcl_LUP_solve():");
822     for (SCSIZE i=0; i < n; ++i)
823         fprintf( stderr, "%8.2g  ", X[i]);
824     fprintf( stderr, "%s\n", "");
825 #endif
826 }
827 
828 
ScMatDet()829 void ScInterpreter::ScMatDet()
830 {
831     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMatDet" );
832     if ( MustHaveParamCount( GetByte(), 1 ) )
833     {
834         ScMatrixRef pMat = GetMatrix();
835         if (!pMat)
836         {
837             PushIllegalParameter();
838             return;
839         }
840         if ( !pMat->IsNumeric() )
841         {
842             PushNoValue();
843             return;
844         }
845         SCSIZE nC, nR;
846         pMat->GetDimensions(nC, nR);
847         if ( nC != nR || nC == 0 || (sal_uLong) nC * nC > ScMatrix::GetElementsMax() )
848             PushIllegalArgument();
849         else
850         {
851             // LUP decomposition is done inplace, use copy.
852             ScMatrixRef xLU = pMat->Clone();
853             if (!xLU)
854                 PushError( errCodeOverflow);
855             else
856             {
857                 ::std::vector< SCSIZE> P(nR);
858                 int nDetSign = lcl_LUP_decompose( xLU, nR, P);
859                 if (!nDetSign)
860                     PushInt(0);     // singular matrix
861                 else
862                 {
863                     // In an LU matrix the determinant is simply the product of
864                     // all diagonal elements.
865                     double fDet = nDetSign;
866                     ScMatrix* pLU = xLU;
867                     for (SCSIZE i=0; i < nR; ++i)
868                         fDet *= pLU->GetDouble( i, i);
869                     PushDouble( fDet);
870                 }
871             }
872         }
873     }
874 }
875 
ScMatInv()876 void ScInterpreter::ScMatInv()
877 {
878     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMatInv" );
879     if ( MustHaveParamCount( GetByte(), 1 ) )
880     {
881         ScMatrixRef pMat = GetMatrix();
882         if (!pMat)
883         {
884             PushIllegalParameter();
885             return;
886         }
887         if ( !pMat->IsNumeric() )
888         {
889             PushNoValue();
890             return;
891         }
892         SCSIZE nC, nR;
893         pMat->GetDimensions(nC, nR);
894         if ( nC != nR || nC == 0 || (sal_uLong) nC * nC > ScMatrix::GetElementsMax() )
895             PushIllegalArgument();
896         else
897         {
898             // LUP decomposition is done inplace, use copy.
899             ScMatrixRef xLU = pMat->Clone();
900             // The result matrix.
901             ScMatrixRef xY = GetNewMat( nR, nR);
902             if (!xLU || !xY)
903                 PushError( errCodeOverflow);
904             else
905             {
906                 ::std::vector< SCSIZE> P(nR);
907                 int nDetSign = lcl_LUP_decompose( xLU, nR, P);
908                 if (!nDetSign)
909                     PushIllegalArgument();
910                 else
911                 {
912                     // Solve equation for each column.
913                     ScMatrix* pY = xY;
914                     ::std::vector< double> B(nR);
915                     ::std::vector< double> X(nR);
916                     for (SCSIZE j=0; j < nR; ++j)
917                     {
918                         for (SCSIZE i=0; i < nR; ++i)
919                             B[i] = 0.0;
920                         B[j] = 1.0;
921                         lcl_LUP_solve( xLU, nR, P, B, X);
922                         for (SCSIZE i=0; i < nR; ++i)
923                             pY->PutDouble( X[i], j, i);
924                     }
925 #if 0
926                     /* Possible checks for ill-condition:
927                      * 1. Scale matrix, invert scaled matrix. If there are
928                      *    elements of the inverted matrix that are several
929                      *    orders of magnitude greater than 1 =>
930                      *    ill-conditioned.
931                      *    Just how much is "several orders"?
932                      * 2. Invert the inverted matrix and assess whether the
933                      *    result is sufficiently close to the original matrix.
934                      *    If not => ill-conditioned.
935                      *    Just what is sufficient?
936                      * 3. Multiplying the inverse by the original matrix should
937                      *    produce a result sufficiently close to the identity
938                      *    matrix.
939                      *    Just what is sufficient?
940                      *
941                      * The following is #3.
942                      */
943                     ScMatrixRef xR = GetNewMat( nR, nR);
944                     if (xR)
945                     {
946                         ScMatrix* pR = xR;
947                         lcl_MFastMult( pMat, pY, pR, nR, nR, nR);
948 #if OSL_DEBUG_LEVEL > 1
949                         fprintf( stderr, "\n%s\n", "ScMatInv(): mult-identity");
950 #endif
951                         for (SCSIZE i=0; i < nR; ++i)
952                         {
953                             for (SCSIZE j=0; j < nR; ++j)
954                             {
955                                 double fTmp = pR->GetDouble( j, i);
956 #if OSL_DEBUG_LEVEL > 1
957                                 fprintf( stderr, "%8.2g  ", fTmp);
958 #endif
959                                 if (fabs( fTmp - (i == j)) > fInvEpsilon)
960                                     SetError( errIllegalArgument);
961                             }
962 #if OSL_DEBUG_LEVEL > 1
963                         fprintf( stderr, "\n%s\n", "");
964 #endif
965                         }
966                     }
967 #endif
968                     if (nGlobalError)
969                         PushError( nGlobalError);
970                     else
971                         PushMatrix( pY);
972                 }
973             }
974         }
975     }
976 }
977 
ScMatMult()978 void ScInterpreter::ScMatMult()
979 {
980     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMatMult" );
981     if ( MustHaveParamCount( GetByte(), 2 ) )
982     {
983         ScMatrixRef pMat2 = GetMatrix();
984         ScMatrixRef pMat1 = GetMatrix();
985         ScMatrixRef pRMat;
986         if (pMat1 && pMat2)
987         {
988             if ( pMat1->IsNumeric() && pMat2->IsNumeric() )
989             {
990                 SCSIZE nC1, nC2;
991                 SCSIZE nR1, nR2;
992                 pMat1->GetDimensions(nC1, nR1);
993                 pMat2->GetDimensions(nC2, nR2);
994                 if (nC1 != nR2)
995                     PushIllegalArgument();
996                 else
997                 {
998                     pRMat = GetNewMat(nC2, nR1);
999                     if (pRMat)
1000                     {
1001                         double sum;
1002                         for (SCSIZE i = 0; i < nR1; i++)
1003                         {
1004                             for (SCSIZE j = 0; j < nC2; j++)
1005                             {
1006                                 sum = 0.0;
1007                                 for (SCSIZE k = 0; k < nC1; k++)
1008                                 {
1009                                     sum += pMat1->GetDouble(k,i)*pMat2->GetDouble(j,k);
1010                                 }
1011                                 pRMat->PutDouble(sum, j, i);
1012                             }
1013                         }
1014                         PushMatrix(pRMat);
1015                     }
1016                     else
1017                         PushIllegalArgument();
1018                 }
1019             }
1020             else
1021                 PushNoValue();
1022         }
1023         else
1024             PushIllegalParameter();
1025     }
1026 }
1027 
ScMatTrans()1028 void ScInterpreter::ScMatTrans()
1029 {
1030     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMatTrans" );
1031     if ( MustHaveParamCount( GetByte(), 1 ) )
1032     {
1033         ScMatrixRef pMat = GetMatrix();
1034         ScMatrixRef pRMat;
1035         if (pMat)
1036         {
1037             SCSIZE nC, nR;
1038             pMat->GetDimensions(nC, nR);
1039             pRMat = GetNewMat(nR, nC);
1040             if ( pRMat )
1041             {
1042                 pMat->MatTrans(*pRMat);
1043                 PushMatrix(pRMat);
1044             }
1045             else
1046                 PushIllegalArgument();
1047         }
1048         else
1049             PushIllegalParameter();
1050     }
1051 }
1052 
1053 
1054 /** Minimum extent of one result matrix dimension.
1055     For a row or column vector to be replicated the larger matrix dimension is
1056     returned, else the smaller dimension.
1057  */
lcl_GetMinExtent(SCSIZE n1,SCSIZE n2)1058 inline SCSIZE lcl_GetMinExtent( SCSIZE n1, SCSIZE n2 )
1059 {
1060     if (n1 == 1)
1061         return n2;
1062     else if (n2 == 1)
1063         return n1;
1064     else if (n1 < n2)
1065         return n1;
1066     else
1067         return n2;
1068 }
1069 
1070 template<class _Function>
lcl_MatrixCalculation(const _Function & _pOperation,ScMatrix * pMat1,ScMatrix * pMat2,ScInterpreter * _pIterpreter)1071 ScMatrixRef lcl_MatrixCalculation(const _Function& _pOperation,ScMatrix* pMat1, ScMatrix* pMat2,ScInterpreter* _pIterpreter)
1072 {
1073     SCSIZE nC1, nC2, nMinC;
1074     SCSIZE nR1, nR2, nMinR;
1075     SCSIZE i, j;
1076     pMat1->GetDimensions(nC1, nR1);
1077     pMat2->GetDimensions(nC2, nR2);
1078     nMinC = lcl_GetMinExtent( nC1, nC2);
1079     nMinR = lcl_GetMinExtent( nR1, nR2);
1080     ScMatrixRef xResMat = _pIterpreter->GetNewMat(nMinC, nMinR);
1081     if (xResMat)
1082     {
1083         ScMatrix* pResMat = xResMat;
1084         for (i = 0; i < nMinC; i++)
1085         {
1086             for (j = 0; j < nMinR; j++)
1087             {
1088                 if (pMat1->IsValueOrEmpty(i,j) && pMat2->IsValueOrEmpty(i,j))
1089                 {
1090                     double d = _pOperation(pMat1->GetDouble(i,j),pMat2->GetDouble(i,j));
1091                     pResMat->PutDouble( d, i, j);
1092                 }
1093                 else
1094                     pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i, j);
1095             }
1096         }
1097     }
1098     return xResMat;
1099 }
1100 
MatConcat(ScMatrix * pMat1,ScMatrix * pMat2)1101 ScMatrixRef ScInterpreter::MatConcat(ScMatrix* pMat1, ScMatrix* pMat2)
1102 {
1103     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::MatConcat" );
1104     SCSIZE nC1, nC2, nMinC;
1105     SCSIZE nR1, nR2, nMinR;
1106     SCSIZE i, j;
1107     pMat1->GetDimensions(nC1, nR1);
1108     pMat2->GetDimensions(nC2, nR2);
1109     nMinC = lcl_GetMinExtent( nC1, nC2);
1110     nMinR = lcl_GetMinExtent( nR1, nR2);
1111     ScMatrixRef xResMat = GetNewMat(nMinC, nMinR);
1112     if (xResMat)
1113     {
1114         ScMatrix* pResMat = xResMat;
1115         for (i = 0; i < nMinC; i++)
1116         {
1117             for (j = 0; j < nMinR; j++)
1118             {
1119                 sal_uInt16 nErr = pMat1->GetErrorIfNotString( i, j);
1120                 if (!nErr)
1121                     nErr = pMat2->GetErrorIfNotString( i, j);
1122                 if (nErr)
1123                     pResMat->PutError( nErr, i, j);
1124                 else
1125                 {
1126                     String aTmp( pMat1->GetString( *pFormatter, i, j));
1127                     aTmp += pMat2->GetString( *pFormatter, i, j);
1128                     pResMat->PutString( aTmp, i, j);
1129                 }
1130             }
1131         }
1132     }
1133     return xResMat;
1134 }
1135 
1136 
1137 // fuer DATE, TIME, DATETIME
lcl_GetDiffDateTimeFmtType(short & nFuncFmt,short nFmt1,short nFmt2)1138 void lcl_GetDiffDateTimeFmtType( short& nFuncFmt, short nFmt1, short nFmt2 )
1139 {
1140     if ( nFmt1 != NUMBERFORMAT_UNDEFINED || nFmt2 != NUMBERFORMAT_UNDEFINED )
1141     {
1142         if ( nFmt1 == nFmt2 )
1143         {
1144             if ( nFmt1 == NUMBERFORMAT_TIME || nFmt1 == NUMBERFORMAT_DATETIME )
1145                 nFuncFmt = NUMBERFORMAT_TIME;   // Zeiten ergeben Zeit
1146             // else: nichts besonderes, Zahl (Datum - Datum := Tage)
1147         }
1148         else if ( nFmt1 == NUMBERFORMAT_UNDEFINED )
1149             nFuncFmt = nFmt2;   // z.B. Datum + Tage := Datum
1150         else if ( nFmt2 == NUMBERFORMAT_UNDEFINED )
1151             nFuncFmt = nFmt1;
1152         else
1153         {
1154             if ( nFmt1 == NUMBERFORMAT_DATE || nFmt2 == NUMBERFORMAT_DATE ||
1155                 nFmt1 == NUMBERFORMAT_DATETIME || nFmt2 == NUMBERFORMAT_DATETIME )
1156             {
1157                 if ( nFmt1 == NUMBERFORMAT_TIME || nFmt2 == NUMBERFORMAT_TIME )
1158                     nFuncFmt = NUMBERFORMAT_DATETIME;   // Datum + Zeit
1159             }
1160         }
1161     }
1162 }
1163 
1164 
ScAdd()1165 void ScInterpreter::ScAdd()
1166 {
1167     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScAdd" );
1168     CalculateAddSub(sal_False);
1169 }
CalculateAddSub(sal_Bool _bSub)1170 void ScInterpreter::CalculateAddSub(sal_Bool _bSub)
1171 {
1172     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::CalculateAddSub" );
1173     ScMatrixRef pMat1 = NULL;
1174     ScMatrixRef pMat2 = NULL;
1175     double fVal1 = 0.0, fVal2 = 0.0;
1176     short nFmt1, nFmt2;
1177     nFmt1 = nFmt2 = NUMBERFORMAT_UNDEFINED;
1178     short nFmtCurrencyType = nCurFmtType;
1179     sal_uLong nFmtCurrencyIndex = nCurFmtIndex;
1180     short nFmtPercentType = nCurFmtType;
1181     if ( GetStackType() == svMatrix )
1182         pMat2 = GetMatrix();
1183     else
1184     {
1185         fVal2 = GetDouble();
1186         switch ( nCurFmtType )
1187         {
1188             case NUMBERFORMAT_DATE :
1189             case NUMBERFORMAT_TIME :
1190             case NUMBERFORMAT_DATETIME :
1191                 nFmt2 = nCurFmtType;
1192             break;
1193             case NUMBERFORMAT_CURRENCY :
1194                 nFmtCurrencyType = nCurFmtType;
1195                 nFmtCurrencyIndex = nCurFmtIndex;
1196             break;
1197             case NUMBERFORMAT_PERCENT :
1198                 nFmtPercentType = NUMBERFORMAT_PERCENT;
1199             break;
1200         }
1201     }
1202     if ( GetStackType() == svMatrix )
1203         pMat1 = GetMatrix();
1204     else
1205     {
1206         fVal1 = GetDouble();
1207         switch ( nCurFmtType )
1208         {
1209             case NUMBERFORMAT_DATE :
1210             case NUMBERFORMAT_TIME :
1211             case NUMBERFORMAT_DATETIME :
1212                 nFmt1 = nCurFmtType;
1213             break;
1214             case NUMBERFORMAT_CURRENCY :
1215                 nFmtCurrencyType = nCurFmtType;
1216                 nFmtCurrencyIndex = nCurFmtIndex;
1217             break;
1218             case NUMBERFORMAT_PERCENT :
1219                 nFmtPercentType = NUMBERFORMAT_PERCENT;
1220             break;
1221         }
1222     }
1223     if (pMat1 && pMat2)
1224     {
1225         ScMatrixRef pResMat;
1226         if ( _bSub )
1227         {
1228             MatrixSub aSub;
1229             pResMat = lcl_MatrixCalculation(aSub ,pMat1, pMat2,this);
1230         }
1231         else
1232         {
1233             MatrixAdd aAdd;
1234             pResMat = lcl_MatrixCalculation(aAdd ,pMat1, pMat2,this);
1235         }
1236 
1237         if (!pResMat)
1238             PushNoValue();
1239         else
1240             PushMatrix(pResMat);
1241     }
1242     else if (pMat1 || pMat2)
1243     {
1244         double fVal;
1245         sal_Bool bFlag;
1246         ScMatrixRef pMat = pMat1;
1247         if (!pMat)
1248         {
1249             fVal = fVal1;
1250             pMat = pMat2;
1251             bFlag = sal_True;           // double - Matrix
1252         }
1253         else
1254         {
1255             fVal = fVal2;
1256             bFlag = sal_False;          // Matrix - double
1257         }
1258         SCSIZE nC, nR;
1259         pMat->GetDimensions(nC, nR);
1260         ScMatrixRef pResMat = GetNewMat(nC, nR);
1261         if (pResMat)
1262         {
1263             SCSIZE nCount = nC * nR;
1264             if (bFlag || !_bSub )
1265             {
1266                 for ( SCSIZE i = 0; i < nCount; i++ )
1267                 {
1268                     if (pMat->IsValue(i))
1269                         pResMat->PutDouble( _bSub ? ::rtl::math::approxSub( fVal, pMat->GetDouble(i)) : ::rtl::math::approxAdd( pMat->GetDouble(i), fVal), i);
1270                     else
1271                         pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1272                 } // for ( SCSIZE i = 0; i < nCount; i++ )
1273             } // if (bFlag || !_bSub )
1274             else
1275             {
1276                 for ( SCSIZE i = 0; i < nCount; i++ )
1277                 {   if (pMat->IsValue(i))
1278                         pResMat->PutDouble( ::rtl::math::approxSub( pMat->GetDouble(i), fVal), i);
1279                     else
1280                         pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1281                 } // for ( SCSIZE i = 0; i < nCount; i++ )
1282             }
1283             PushMatrix(pResMat);
1284         }
1285         else
1286             PushIllegalArgument();
1287     }
1288     else if ( _bSub )
1289         PushDouble( ::rtl::math::approxSub( fVal1, fVal2 ) );
1290     else
1291         PushDouble( ::rtl::math::approxAdd( fVal1, fVal2 ) );
1292     if ( nFmtCurrencyType == NUMBERFORMAT_CURRENCY )
1293     {
1294         nFuncFmtType = nFmtCurrencyType;
1295         nFuncFmtIndex = nFmtCurrencyIndex;
1296     }
1297     else
1298     {
1299         lcl_GetDiffDateTimeFmtType( nFuncFmtType, nFmt1, nFmt2 );
1300         if ( nFmtPercentType == NUMBERFORMAT_PERCENT && nFuncFmtType == NUMBERFORMAT_NUMBER )
1301             nFuncFmtType = NUMBERFORMAT_PERCENT;
1302     }
1303 }
1304 
ScAmpersand()1305 void ScInterpreter::ScAmpersand()
1306 {
1307     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScAmpersand" );
1308     ScMatrixRef pMat1 = NULL;
1309     ScMatrixRef pMat2 = NULL;
1310     String sStr1, sStr2;
1311     if ( GetStackType() == svMatrix )
1312         pMat2 = GetMatrix();
1313     else
1314         sStr2 = GetString();
1315     if ( GetStackType() == svMatrix )
1316         pMat1 = GetMatrix();
1317     else
1318         sStr1 = GetString();
1319     if (pMat1 && pMat2)
1320     {
1321         ScMatrixRef pResMat = MatConcat(pMat1, pMat2);
1322         if (!pResMat)
1323             PushNoValue();
1324         else
1325             PushMatrix(pResMat);
1326     }
1327     else if (pMat1 || pMat2)
1328     {
1329         String sStr;
1330         sal_Bool bFlag;
1331         ScMatrixRef pMat = pMat1;
1332         if (!pMat)
1333         {
1334             sStr = sStr1;
1335             pMat = pMat2;
1336             bFlag = sal_True;           // double - Matrix
1337         }
1338         else
1339         {
1340             sStr = sStr2;
1341             bFlag = sal_False;          // Matrix - double
1342         }
1343         SCSIZE nC, nR;
1344         pMat->GetDimensions(nC, nR);
1345         ScMatrixRef pResMat = GetNewMat(nC, nR);
1346         if (pResMat)
1347         {
1348             SCSIZE nCount = nC * nR;
1349             if (nGlobalError)
1350             {
1351                 for ( SCSIZE i = 0; i < nCount; i++ )
1352                     pResMat->PutError( nGlobalError, i);
1353             }
1354             else if (bFlag)
1355             {
1356                 for ( SCSIZE i = 0; i < nCount; i++ )
1357                 {
1358                     sal_uInt16 nErr = pMat->GetErrorIfNotString( i);
1359                     if (nErr)
1360                         pResMat->PutError( nErr, i);
1361                     else
1362                     {
1363                         String aTmp( sStr);
1364                         aTmp += pMat->GetString( *pFormatter, i);
1365                         pResMat->PutString( aTmp, i);
1366                     }
1367                 }
1368             }
1369             else
1370             {
1371                 for ( SCSIZE i = 0; i < nCount; i++ )
1372                 {
1373                     sal_uInt16 nErr = pMat->GetErrorIfNotString( i);
1374                     if (nErr)
1375                         pResMat->PutError( nErr, i);
1376                     else
1377                     {
1378                         String aTmp( pMat->GetString( *pFormatter, i));
1379                         aTmp += sStr;
1380                         pResMat->PutString( aTmp, i);
1381                     }
1382                 }
1383             }
1384             PushMatrix(pResMat);
1385         }
1386         else
1387             PushIllegalArgument();
1388     }
1389     else
1390     {
1391         if ( CheckStringResultLen( sStr1, sStr2 ) )
1392             sStr1 += sStr2;
1393         PushString(sStr1);
1394     }
1395 }
1396 
ScSub()1397 void ScInterpreter::ScSub()
1398 {
1399     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScSub" );
1400     CalculateAddSub(sal_True);
1401 }
1402 
ScMul()1403 void ScInterpreter::ScMul()
1404 {
1405     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMul" );
1406     ScMatrixRef pMat1 = NULL;
1407     ScMatrixRef pMat2 = NULL;
1408     double fVal1 = 0.0, fVal2 = 0.0;
1409     short nFmtCurrencyType = nCurFmtType;
1410     sal_uLong nFmtCurrencyIndex = nCurFmtIndex;
1411     if ( GetStackType() == svMatrix )
1412         pMat2 = GetMatrix();
1413     else
1414     {
1415         fVal2 = GetDouble();
1416         switch ( nCurFmtType )
1417         {
1418             case NUMBERFORMAT_CURRENCY :
1419                 nFmtCurrencyType = nCurFmtType;
1420                 nFmtCurrencyIndex = nCurFmtIndex;
1421             break;
1422         }
1423     }
1424     if ( GetStackType() == svMatrix )
1425         pMat1 = GetMatrix();
1426     else
1427     {
1428         fVal1 = GetDouble();
1429         switch ( nCurFmtType )
1430         {
1431             case NUMBERFORMAT_CURRENCY :
1432                 nFmtCurrencyType = nCurFmtType;
1433                 nFmtCurrencyIndex = nCurFmtIndex;
1434             break;
1435         }
1436     }
1437     if (pMat1 && pMat2)
1438     {
1439         MatrixMul aMul;
1440         ScMatrixRef pResMat = lcl_MatrixCalculation(aMul,pMat1, pMat2,this);
1441         if (!pResMat)
1442             PushNoValue();
1443         else
1444             PushMatrix(pResMat);
1445     }
1446     else if (pMat1 || pMat2)
1447     {
1448         double fVal;
1449         ScMatrixRef pMat = pMat1;
1450         if (!pMat)
1451         {
1452             fVal = fVal1;
1453             pMat = pMat2;
1454         }
1455         else
1456             fVal = fVal2;
1457         SCSIZE nC, nR;
1458         pMat->GetDimensions(nC, nR);
1459         ScMatrixRef pResMat = GetNewMat(nC, nR);
1460         if (pResMat)
1461         {
1462             SCSIZE nCount = nC * nR;
1463             for ( SCSIZE i = 0; i < nCount; i++ )
1464                 if (pMat->IsValue(i))
1465                     pResMat->PutDouble(pMat->GetDouble(i)*fVal, i);
1466                 else
1467                     pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1468             PushMatrix(pResMat);
1469         }
1470         else
1471             PushIllegalArgument();
1472     }
1473     else
1474         PushDouble(fVal1 * fVal2);
1475     if ( nFmtCurrencyType == NUMBERFORMAT_CURRENCY )
1476     {
1477         nFuncFmtType = nFmtCurrencyType;
1478         nFuncFmtIndex = nFmtCurrencyIndex;
1479     }
1480 }
1481 
ScDiv()1482 void ScInterpreter::ScDiv()
1483 {
1484     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScDiv" );
1485     ScMatrixRef pMat1 = NULL;
1486     ScMatrixRef pMat2 = NULL;
1487     double fVal1 = 0.0, fVal2 = 0.0;
1488     short nFmtCurrencyType = nCurFmtType;
1489     sal_uLong nFmtCurrencyIndex = nCurFmtIndex;
1490     short nFmtCurrencyType2 = NUMBERFORMAT_UNDEFINED;
1491     if ( GetStackType() == svMatrix )
1492         pMat2 = GetMatrix();
1493     else
1494     {
1495         fVal2 = GetDouble();
1496         // hier kein Currency uebernehmen, 123kg/456DM sind nicht DM
1497         nFmtCurrencyType2 = nCurFmtType;
1498     }
1499     if ( GetStackType() == svMatrix )
1500         pMat1 = GetMatrix();
1501     else
1502     {
1503         fVal1 = GetDouble();
1504         switch ( nCurFmtType )
1505         {
1506             case NUMBERFORMAT_CURRENCY :
1507                 nFmtCurrencyType = nCurFmtType;
1508                 nFmtCurrencyIndex = nCurFmtIndex;
1509             break;
1510         }
1511     }
1512     if (pMat1 && pMat2)
1513     {
1514         MatrixDiv aDiv;
1515         ScMatrixRef pResMat = lcl_MatrixCalculation(aDiv,pMat1, pMat2,this);
1516         if (!pResMat)
1517             PushNoValue();
1518         else
1519             PushMatrix(pResMat);
1520     }
1521     else if (pMat1 || pMat2)
1522     {
1523         double fVal;
1524         sal_Bool bFlag;
1525         ScMatrixRef pMat = pMat1;
1526         if (!pMat)
1527         {
1528             fVal = fVal1;
1529             pMat = pMat2;
1530             bFlag = sal_True;           // double - Matrix
1531         }
1532         else
1533         {
1534             fVal = fVal2;
1535             bFlag = sal_False;          // Matrix - double
1536         }
1537         SCSIZE nC, nR;
1538         pMat->GetDimensions(nC, nR);
1539         ScMatrixRef pResMat = GetNewMat(nC, nR);
1540         if (pResMat)
1541         {
1542             SCSIZE nCount = nC * nR;
1543             if (bFlag)
1544             {   for ( SCSIZE i = 0; i < nCount; i++ )
1545                     if (pMat->IsValue(i))
1546                         pResMat->PutDouble( div( fVal, pMat->GetDouble(i)), i);
1547                     else
1548                         pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1549             }
1550             else
1551             {   for ( SCSIZE i = 0; i < nCount; i++ )
1552                     if (pMat->IsValue(i))
1553                         pResMat->PutDouble( div( pMat->GetDouble(i), fVal), i);
1554                     else
1555                         pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1556             }
1557             PushMatrix(pResMat);
1558         }
1559         else
1560             PushIllegalArgument();
1561     }
1562     else
1563     {
1564         PushDouble( div( fVal1, fVal2) );
1565     }
1566     if ( nFmtCurrencyType == NUMBERFORMAT_CURRENCY && nFmtCurrencyType2 != NUMBERFORMAT_CURRENCY )
1567     {   // auch DM/DM ist nicht DM bzw. DEM/EUR nicht DEM
1568         nFuncFmtType = nFmtCurrencyType;
1569         nFuncFmtIndex = nFmtCurrencyIndex;
1570     }
1571 }
1572 
ScPower()1573 void ScInterpreter::ScPower()
1574 {
1575     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScPower" );
1576     if ( MustHaveParamCount( GetByte(), 2 ) )
1577         ScPow();
1578 }
1579 
ScPow()1580 void ScInterpreter::ScPow()
1581 {
1582     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScPow" );
1583     ScMatrixRef pMat1 = NULL;
1584     ScMatrixRef pMat2 = NULL;
1585     double fVal1 = 0.0, fVal2 = 0.0;
1586     if ( GetStackType() == svMatrix )
1587         pMat2 = GetMatrix();
1588     else
1589         fVal2 = GetDouble();
1590     if ( GetStackType() == svMatrix )
1591         pMat1 = GetMatrix();
1592     else
1593         fVal1 = GetDouble();
1594     if (pMat1 && pMat2)
1595     {
1596         MatrixPow aPow;
1597         ScMatrixRef pResMat = lcl_MatrixCalculation(aPow,pMat1, pMat2,this);
1598         if (!pResMat)
1599             PushNoValue();
1600         else
1601             PushMatrix(pResMat);
1602     }
1603     else if (pMat1 || pMat2)
1604     {
1605         double fVal;
1606         sal_Bool bFlag;
1607         ScMatrixRef pMat = pMat1;
1608         if (!pMat)
1609         {
1610             fVal = fVal1;
1611             pMat = pMat2;
1612             bFlag = sal_True;           // double - Matrix
1613         }
1614         else
1615         {
1616             fVal = fVal2;
1617             bFlag = sal_False;          // Matrix - double
1618         }
1619         SCSIZE nC, nR;
1620         pMat->GetDimensions(nC, nR);
1621         ScMatrixRef pResMat = GetNewMat(nC, nR);
1622         if (pResMat)
1623         {
1624             SCSIZE nCount = nC * nR;
1625             if (bFlag)
1626             {   for ( SCSIZE i = 0; i < nCount; i++ )
1627                     if (pMat->IsValue(i))
1628                         pResMat->PutDouble(pow(fVal,pMat->GetDouble(i)), i);
1629                     else
1630                         pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1631             }
1632             else
1633             {   for ( SCSIZE i = 0; i < nCount; i++ )
1634                     if (pMat->IsValue(i))
1635                         pResMat->PutDouble(pow(pMat->GetDouble(i),fVal), i);
1636                     else
1637                         pResMat->PutString(ScGlobal::GetRscString(STR_NO_VALUE), i);
1638             }
1639             PushMatrix(pResMat);
1640         }
1641         else
1642             PushIllegalArgument();
1643     }
1644     else
1645         PushDouble(pow(fVal1,fVal2));
1646 }
1647 
ScSumProduct()1648 void ScInterpreter::ScSumProduct()
1649 {
1650     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScSumProduct" );
1651     sal_uInt8 nParamCount = GetByte();
1652     if ( !MustHaveParamCount( nParamCount, 1, 30 ) )
1653         return;
1654 
1655     ScMatrixRef pMat1 = NULL;
1656     ScMatrixRef pMat2 = NULL;
1657     ScMatrixRef pMat  = NULL;
1658     pMat2 = GetMatrix();
1659     if (!pMat2)
1660     {
1661         PushIllegalParameter();
1662         return;
1663     }
1664     SCSIZE nC, nC1;
1665     SCSIZE nR, nR1;
1666     pMat2->GetDimensions(nC, nR);
1667     pMat = pMat2;
1668     MatrixMul aMul;
1669     for (sal_uInt16 i = 1; i < nParamCount; i++)
1670     {
1671         pMat1 = GetMatrix();
1672         if (!pMat1)
1673         {
1674             PushIllegalParameter();
1675             return;
1676         }
1677         pMat1->GetDimensions(nC1, nR1);
1678         if (nC1 != nC || nR1 != nR)
1679         {
1680             PushNoValue();
1681             return;
1682         }
1683         ScMatrixRef pResMat = lcl_MatrixCalculation(aMul,pMat1, pMat,this);
1684         if (!pResMat)
1685         {
1686             PushNoValue();
1687             return;
1688         }
1689         else
1690             pMat = pResMat;
1691     }
1692     double fSum = 0.0;
1693     SCSIZE nCount = pMat->GetElementCount();
1694     for (SCSIZE j = 0; j < nCount; j++)
1695     {
1696         if (!pMat->IsString(j))
1697             fSum += pMat->GetDouble(j);
1698     }
1699     PushDouble(fSum);
1700 }
1701 
ScSumX2MY2()1702 void ScInterpreter::ScSumX2MY2()
1703 {
1704     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScSumX2MY2" );
1705     CalculateSumX2MY2SumX2DY2(sal_False);
1706 }
CalculateSumX2MY2SumX2DY2(sal_Bool _bSumX2DY2)1707 void ScInterpreter::CalculateSumX2MY2SumX2DY2(sal_Bool _bSumX2DY2)
1708 {
1709     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::CalculateSumX2MY2SumX2DY2" );
1710     if ( !MustHaveParamCount( GetByte(), 2 ) )
1711         return;
1712 
1713     ScMatrixRef pMat1 = NULL;
1714     ScMatrixRef pMat2 = NULL;
1715     SCSIZE i, j;
1716     pMat2 = GetMatrix();
1717     pMat1 = GetMatrix();
1718     if (!pMat2 || !pMat1)
1719     {
1720         PushIllegalParameter();
1721         return;
1722     }
1723     SCSIZE nC1, nC2;
1724     SCSIZE nR1, nR2;
1725     pMat2->GetDimensions(nC2, nR2);
1726     pMat1->GetDimensions(nC1, nR1);
1727     if (nC1 != nC2 || nR1 != nR2)
1728     {
1729         PushNoValue();
1730         return;
1731     }
1732     double fVal, fSum = 0.0;
1733     for (i = 0; i < nC1; i++)
1734         for (j = 0; j < nR1; j++)
1735             if (!pMat1->IsString(i,j) && !pMat2->IsString(i,j))
1736             {
1737                 fVal = pMat1->GetDouble(i,j);
1738                 fSum += fVal * fVal;
1739                 fVal = pMat2->GetDouble(i,j);
1740                 if ( _bSumX2DY2 )
1741                     fSum += fVal * fVal;
1742                 else
1743                     fSum -= fVal * fVal;
1744             }
1745     PushDouble(fSum);
1746 }
1747 
ScSumX2DY2()1748 void ScInterpreter::ScSumX2DY2()
1749 {
1750     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScSumX2DY2" );
1751     CalculateSumX2MY2SumX2DY2(sal_True);
1752 }
1753 
ScSumXMY2()1754 void ScInterpreter::ScSumXMY2()
1755 {
1756     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScSumXMY2" );
1757     if ( !MustHaveParamCount( GetByte(), 2 ) )
1758         return;
1759 
1760     ScMatrixRef pMat1 = NULL;
1761     ScMatrixRef pMat2 = NULL;
1762     pMat2 = GetMatrix();
1763     pMat1 = GetMatrix();
1764     if (!pMat2 || !pMat1)
1765     {
1766         PushIllegalParameter();
1767         return;
1768     }
1769     SCSIZE nC1, nC2;
1770     SCSIZE nR1, nR2;
1771     pMat2->GetDimensions(nC2, nR2);
1772     pMat1->GetDimensions(nC1, nR1);
1773     if (nC1 != nC2 || nR1 != nR2)
1774     {
1775         PushNoValue();
1776         return;
1777     } // if (nC1 != nC2 || nR1 != nR2)
1778     MatrixSub aSub;
1779     ScMatrixRef pResMat = lcl_MatrixCalculation(aSub,pMat1, pMat2,this);
1780     if (!pResMat)
1781     {
1782         PushNoValue();
1783     }
1784     else
1785     {
1786         double fVal, fSum = 0.0;
1787         SCSIZE nCount = pResMat->GetElementCount();
1788         for (SCSIZE i = 0; i < nCount; i++)
1789             if (!pResMat->IsString(i))
1790             {
1791                 fVal = pResMat->GetDouble(i);
1792                 fSum += fVal * fVal;
1793             }
1794         PushDouble(fSum);
1795     }
1796 }
1797 
ScFrequency()1798 void ScInterpreter::ScFrequency()
1799 {
1800     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScFrequency" );
1801     if ( !MustHaveParamCount( GetByte(), 2 ) )
1802         return;
1803 
1804     vector<double>  aBinArray;
1805     vector<long>    aBinIndexOrder;
1806 
1807     GetSortArray(1, aBinArray, &aBinIndexOrder);
1808     SCSIZE nBinSize = aBinArray.size();
1809     if (nGlobalError)
1810     {
1811         PushNoValue();
1812         return;
1813     }
1814 
1815     vector<double>  aDataArray;
1816     GetSortArray(1, aDataArray);
1817     SCSIZE nDataSize = aDataArray.size();
1818 
1819     if (aDataArray.empty() || nGlobalError)
1820     {
1821         PushNoValue();
1822         return;
1823     }
1824     ScMatrixRef pResMat = GetNewMat(1, nBinSize+1);
1825     if (!pResMat)
1826     {
1827         PushIllegalArgument();
1828         return;
1829     }
1830 
1831     if (nBinSize != aBinIndexOrder.size())
1832     {
1833         PushIllegalArgument();
1834         return;
1835     }
1836 
1837     SCSIZE j;
1838     SCSIZE i = 0;
1839     for (j = 0; j < nBinSize; ++j)
1840     {
1841         SCSIZE nCount = 0;
1842         while (i < nDataSize && aDataArray[i] <= aBinArray[j])
1843         {
1844             ++nCount;
1845             ++i;
1846         }
1847         pResMat->PutDouble(static_cast<double>(nCount), aBinIndexOrder[j]);
1848     }
1849     pResMat->PutDouble(static_cast<double>(nDataSize-i), j);
1850     PushMatrix(pResMat);
1851 }
1852 
1853 // -----------------------------------------------------------------------------
1854 // Helper methods for LINEST/LOGEST and TREND/GROWTH
1855 // All matrices must already exist and have the needed size, no control tests
1856 // done. Those methodes, which names start with lcl_T, are adapted to case 3,
1857 // where Y (=observed values) is given as row.
1858 // Remember, ScMatrix matrices are zero based, index access (column,row).
1859 // -----------------------------------------------------------------------------
1860 
1861 // Multiply n x m Mat A with m x l Mat B to n x l Mat R
lcl_MFastMult(ScMatrixRef pA,ScMatrixRef pB,ScMatrixRef pR,SCSIZE n,SCSIZE m,SCSIZE l)1862 void lcl_MFastMult( ScMatrixRef pA, ScMatrixRef pB, ScMatrixRef pR, SCSIZE n, SCSIZE m, SCSIZE l )
1863 {
1864     double sum;
1865     for (SCSIZE row = 0; row < n; row++)
1866     {
1867         for (SCSIZE col = 0; col < l; col++)
1868         {   // result element(col, row) =sum[ (row of A) * (column of B)]
1869             sum = 0.0;
1870             for (SCSIZE k = 0; k < m; k++)
1871                 sum += pA->GetDouble(k,row) * pB->GetDouble(col,k);
1872             pR->PutDouble(sum, col, row);
1873         }
1874     }
1875 }
1876 
1877 // <A;B> over all elements; uses the matrices as vectors of length M
lcl_GetSumProduct(ScMatrixRef pMatA,ScMatrixRef pMatB,SCSIZE nM)1878 double lcl_GetSumProduct( ScMatrixRef pMatA, ScMatrixRef pMatB, SCSIZE nM )
1879 {
1880     double fSum = 0.0;
1881     for (SCSIZE i=0; i<nM; i++)
1882         fSum += pMatA->GetDouble(i) * pMatB->GetDouble(i);
1883     return fSum;
1884 }
1885 
1886 // Special version for use within QR decomposition.
1887 // Euclidean norm of column index C starting in row index R;
1888 // matrix A has count N rows.
lcl_GetColumnEuclideanNorm(ScMatrixRef pMatA,SCSIZE nC,SCSIZE nR,SCSIZE nN)1889 double lcl_GetColumnEuclideanNorm( ScMatrixRef pMatA, SCSIZE nC, SCSIZE nR, SCSIZE nN )
1890 {
1891     double fNorm = 0.0;
1892     for (SCSIZE row=nR; row<nN; row++)
1893         fNorm  += (pMatA->GetDouble(nC,row)) * (pMatA->GetDouble(nC,row));
1894     return sqrt(fNorm);
1895 }
1896 
1897 // Euclidean norm of row index R starting in column index C;
1898 // matrix A has count N columns.
lcl_TGetColumnEuclideanNorm(ScMatrixRef pMatA,SCSIZE nR,SCSIZE nC,SCSIZE nN)1899 double lcl_TGetColumnEuclideanNorm( ScMatrixRef pMatA, SCSIZE nR, SCSIZE nC, SCSIZE nN )
1900 {
1901     double fNorm = 0.0;
1902     for (SCSIZE col=nC; col<nN; col++)
1903         fNorm  += (pMatA->GetDouble(col,nR)) * (pMatA->GetDouble(col,nR));
1904     return sqrt(fNorm);
1905             }
1906 
1907 // Special version for use within QR decomposition.
1908 // Maximum norm of column index C starting in row index R;
1909 // matrix A has count N rows.
lcl_GetColumnMaximumNorm(ScMatrixRef pMatA,SCSIZE nC,SCSIZE nR,SCSIZE nN)1910 double lcl_GetColumnMaximumNorm( ScMatrixRef pMatA, SCSIZE nC, SCSIZE nR, SCSIZE nN )
1911 {
1912     double fNorm = 0.0;
1913     for (SCSIZE row=nR; row<nN; row++)
1914         if (fNorm < fabs(pMatA->GetDouble(nC,row)))
1915             fNorm = fabs(pMatA->GetDouble(nC,row));
1916     return fNorm;
1917 }
1918 
1919 // Maximum norm of row index R starting in col index C;
1920 // matrix A has count N columns.
lcl_TGetColumnMaximumNorm(ScMatrixRef pMatA,SCSIZE nR,SCSIZE nC,SCSIZE nN)1921 double lcl_TGetColumnMaximumNorm( ScMatrixRef pMatA, SCSIZE nR, SCSIZE nC, SCSIZE nN )
1922 {
1923     double fNorm = 0.0;
1924     for (SCSIZE col=nC; col<nN; col++)
1925         if (fNorm < fabs(pMatA->GetDouble(col,nR)))
1926             fNorm = fabs(pMatA->GetDouble(col,nR));
1927     return fNorm;
1928 }
1929 
1930 // Special version for use within QR decomposition.
1931 // <A(Ca);B(Cb)> starting in row index R;
1932 // Ca and Cb are indices of columns, matrices A and B have count N rows.
lcl_GetColumnSumProduct(ScMatrixRef pMatA,SCSIZE nCa,ScMatrixRef pMatB,SCSIZE nCb,SCSIZE nR,SCSIZE nN)1933 double lcl_GetColumnSumProduct( ScMatrixRef pMatA, SCSIZE nCa, ScMatrixRef pMatB,
1934         SCSIZE nCb, SCSIZE nR, SCSIZE nN )
1935 {
1936     double fResult = 0.0;
1937     for (SCSIZE row=nR; row<nN; row++)
1938         fResult += pMatA->GetDouble(nCa,row) * pMatB->GetDouble(nCb,row);
1939     return fResult;
1940 }
1941 
1942 // <A(Ra);B(Rb)> starting in column index C;
1943 // Ra and Rb are indices of rows, matrices A and B have count N columns.
lcl_TGetColumnSumProduct(ScMatrixRef pMatA,SCSIZE nRa,ScMatrixRef pMatB,SCSIZE nRb,SCSIZE nC,SCSIZE nN)1944 double lcl_TGetColumnSumProduct( ScMatrixRef pMatA, SCSIZE nRa,
1945         ScMatrixRef pMatB, SCSIZE nRb, SCSIZE nC, SCSIZE nN )
1946 {
1947     double fResult = 0.0;
1948     for (SCSIZE col=nC; col<nN; col++)
1949         fResult += pMatA->GetDouble(col,nRa) * pMatB->GetDouble(col,nRb);
1950     return fResult;
1951 }
1952 
1953 // #118029# no mathematical signum, but used to switch between adding and subtracting
lcl_GetSign(double fValue)1954 double lcl_GetSign(double fValue)
1955 {
1956     return (fValue >= 0.0 ? 1.0 : -1.0 );
1957 }
1958 
1959 /* Calculates a QR decomposition with Householder reflection.
1960  * For each NxK matrix A exists a decomposition A=Q*R with an orthogonal
1961  * NxN matrix Q and a NxK matrix R.
1962  * Q=H1*H2*...*Hk with Householder matrices H. Such a householder matrix can
1963  * be build from a vector u by H=I-(2/u'u)*(u u'). This vectors u are returned
1964  * in the columns of matrix A, overwriting the old content.
1965  * The matrix R has a quadric upper part KxK with values in the upper right
1966  * triangle and zeros in all other elements. Here the diagonal elements of R
1967  * are stored in the vector R and the other upper right elements in the upper
1968  * right of the matrix A.
1969  * The function returns false, if calculation breaks. But because of round-off
1970  * errors singularity is often not detected.
1971  */
lcl_CalculateQRdecomposition(ScMatrixRef pMatA,::std::vector<double> & pVecR,SCSIZE nK,SCSIZE nN)1972 bool lcl_CalculateQRdecomposition(ScMatrixRef pMatA,
1973                     ::std::vector< double>& pVecR, SCSIZE nK, SCSIZE nN)
1974 {
1975     double fScale ;
1976     double fEuclid ;
1977     double fFactor ;
1978     double fSignum ;
1979     double fSum ;
1980     // ScMatrix matrices are zero based, index access (column,row)
1981     for (SCSIZE col = 0; col <nK; col++)
1982     {
1983         // calculate vector u of the householder transformation
1984         fScale = lcl_GetColumnMaximumNorm(pMatA, col, col, nN);
1985         if (fScale == 0.0)
1986             // A is singular
1987             return false;
1988 
1989         for (SCSIZE row = col; row <nN; row++)
1990             pMatA->PutDouble( pMatA->GetDouble(col,row)/fScale, col, row);
1991 
1992         fEuclid = lcl_GetColumnEuclideanNorm(pMatA, col, col, nN);
1993         fFactor = 1.0/fEuclid/(fEuclid + fabs(pMatA->GetDouble(col,col)));
1994         fSignum = lcl_GetSign(pMatA->GetDouble(col,col));
1995         pMatA->PutDouble( pMatA->GetDouble(col,col) + fSignum*fEuclid, col,col);
1996         pVecR[col] = -fSignum * fScale * fEuclid;
1997 
1998         // apply Householder transformation to A
1999         for (SCSIZE c=col+1; c<nK; c++)
2000         {
2001             fSum =lcl_GetColumnSumProduct(pMatA, col, pMatA, c, col, nN);
2002             for (SCSIZE row = col; row <nN; row++)
2003                 pMatA->PutDouble( pMatA->GetDouble(c,row)
2004                         - fSum * fFactor * pMatA->GetDouble(col,row), c, row);
2005         }
2006     }
2007     return true;
2008 }
2009 
2010 // same with transposed matrix A, N is count of columns, K count of rows
lcl_TCalculateQRdecomposition(ScMatrixRef pMatA,::std::vector<double> & pVecR,SCSIZE nK,SCSIZE nN)2011 bool lcl_TCalculateQRdecomposition(ScMatrixRef pMatA,
2012                     ::std::vector< double>& pVecR, SCSIZE nK, SCSIZE nN)
2013 {
2014     double fScale ;
2015     double fEuclid ;
2016     double fFactor ;
2017     double fSignum ;
2018     double fSum ;
2019     // ScMatrix matrices are zero based, index access (column,row)
2020     for (SCSIZE row = 0; row <nK; row++)
2021     {
2022         // calculate vector u of the householder transformation
2023         fScale = lcl_TGetColumnMaximumNorm(pMatA, row, row, nN);
2024         if (fScale == 0.0)
2025             // A is singular
2026             return false;
2027 
2028         for (SCSIZE col = row; col <nN; col++)
2029             pMatA->PutDouble( pMatA->GetDouble(col,row)/fScale, col, row);
2030 
2031         fEuclid = lcl_TGetColumnEuclideanNorm(pMatA, row, row, nN);
2032         fFactor = 1.0/fEuclid/(fEuclid + fabs(pMatA->GetDouble(row,row)));
2033         fSignum = lcl_GetSign(pMatA->GetDouble(row,row));
2034         pMatA->PutDouble( pMatA->GetDouble(row,row) + fSignum*fEuclid, row,row);
2035         pVecR[row] = -fSignum * fScale * fEuclid;
2036 
2037         // apply Householder transformation to A
2038         for (SCSIZE r=row+1; r<nK; r++)
2039         {
2040             fSum =lcl_TGetColumnSumProduct(pMatA, row, pMatA, r, row, nN);
2041             for (SCSIZE col = row; col <nN; col++)
2042                 pMatA->PutDouble( pMatA->GetDouble(col,r)
2043                         - fSum * fFactor * pMatA->GetDouble(col,row), col, r);
2044         }
2045     }
2046     return true;
2047 }
2048 
2049 
2050 /* Applies a Householder transformation to a column vector Y with is given as
2051  * Nx1 Matrix. The Vektor u, from which the Householder transformation is build,
2052  * is the column part in matrix A, with column index C, starting with row
2053  * index C. A is the result of the QR decomposition as obtained from
2054  * lcl_CaluclateQRdecomposition.
2055  */
lcl_ApplyHouseholderTransformation(ScMatrixRef pMatA,SCSIZE nC,ScMatrixRef pMatY,SCSIZE nN)2056 void lcl_ApplyHouseholderTransformation(ScMatrixRef pMatA, SCSIZE nC,
2057                                           ScMatrixRef pMatY, SCSIZE nN)
2058 {
2059     // ScMatrix matrices are zero based, index access (column,row)
2060     double fDenominator = lcl_GetColumnSumProduct(pMatA, nC, pMatA, nC, nC, nN);
2061     double fNumerator = lcl_GetColumnSumProduct(pMatA, nC, pMatY, 0, nC, nN);
2062     double fFactor = 2.0 * (fNumerator/fDenominator);
2063     for (SCSIZE row = nC; row < nN; row++)
2064         pMatY->PutDouble(
2065                 pMatY->GetDouble(row) - fFactor * pMatA->GetDouble(nC,row), row);
2066 }
2067 
2068 // Same with transposed matrices A and Y.
lcl_TApplyHouseholderTransformation(ScMatrixRef pMatA,SCSIZE nR,ScMatrixRef pMatY,SCSIZE nN)2069 void lcl_TApplyHouseholderTransformation(ScMatrixRef pMatA, SCSIZE nR,
2070                                           ScMatrixRef pMatY, SCSIZE nN)
2071 {
2072     // ScMatrix matrices are zero based, index access (column,row)
2073     double fDenominator = lcl_TGetColumnSumProduct(pMatA, nR, pMatA, nR, nR, nN);
2074     double fNumerator = lcl_TGetColumnSumProduct(pMatA, nR, pMatY, 0, nR, nN);
2075     double fFactor = 2.0 * (fNumerator/fDenominator);
2076     for (SCSIZE col = nR; col < nN; col++)
2077         pMatY->PutDouble(
2078           pMatY->GetDouble(col) - fFactor * pMatA->GetDouble(col,nR), col);
2079 }
2080 
2081 /* Solve for X in R*X=S using back substitution. The solution X overwrites S.
2082  * Uses R from the result of the QR decomposition of a NxK matrix A.
2083  * S is a column vector given as matrix, with at least elements on index
2084  * 0 to K-1; elements on index>=K are ignored. Vector R must not have zero
2085  * elements, no check is done.
2086  */
lcl_SolveWithUpperRightTriangle(ScMatrixRef pMatA,::std::vector<double> & pVecR,ScMatrixRef pMatS,SCSIZE nK,bool bIsTransposed)2087 void lcl_SolveWithUpperRightTriangle(ScMatrixRef pMatA,
2088                         ::std::vector< double>& pVecR, ScMatrixRef pMatS,
2089                         SCSIZE nK, bool bIsTransposed)
2090 {
2091     // ScMatrix matrices are zero based, index access (column,row)
2092     double fSum;
2093     SCSIZE row;
2094     // SCSIZE is never negative, therefore test with rowp1=row+1
2095     for (SCSIZE rowp1 = nK; rowp1>0; rowp1--)
2096     {
2097         row = rowp1-1;
2098         fSum = pMatS->GetDouble(row);
2099         for (SCSIZE col = rowp1; col<nK ; col++)
2100             if (bIsTransposed)
2101                 fSum -= pMatA->GetDouble(row,col) * pMatS->GetDouble(col);
2102             else
2103                 fSum -= pMatA->GetDouble(col,row) * pMatS->GetDouble(col);
2104         pMatS->PutDouble( fSum / pVecR[row] , row);
2105     }
2106 }
2107 
2108 /* Solve for X in R' * X= T using forward substitution. The solution X
2109  * overwrites T. Uses R from the result of the QR decomposition of a NxK
2110  * matrix A. T is a column vectors given as matrix, with at least elements on
2111  * index 0 to K-1; elements on index>=K are ignored. Vector R must not have
2112  * zero elements, no check is done.
2113  */
lcl_SolveWithLowerLeftTriangle(ScMatrixRef pMatA,::std::vector<double> & pVecR,ScMatrixRef pMatT,SCSIZE nK,bool bIsTransposed)2114 void lcl_SolveWithLowerLeftTriangle(ScMatrixRef pMatA,
2115                     ::std::vector< double>& pVecR, ScMatrixRef pMatT,
2116                     SCSIZE nK, bool bIsTransposed)
2117 {
2118     // ScMatrix matrices are zero based, index access (column,row)
2119     double fSum;
2120     for (SCSIZE row = 0; row < nK; row++)
2121     {
2122         fSum = pMatT -> GetDouble(row);
2123         for (SCSIZE col=0; col < row; col++)
2124         {
2125             if (bIsTransposed)
2126                 fSum -= pMatA->GetDouble(col,row) * pMatT->GetDouble(col);
2127             else
2128                 fSum -= pMatA->GetDouble(row,col) * pMatT->GetDouble(col);
2129         }
2130         pMatT->PutDouble( fSum / pVecR[row] , row);
2131     }
2132 }
2133 
2134 /* Calculates Z = R * B
2135  * R is given in matrix A and vector VecR as obtained from the QR
2136  * decomposition in lcl_CalculateQRdecomposition. B and Z are column vectors
2137  * given as matrix with at least index 0 to K-1; elements on index>=K are
2138  * not used.
2139  */
lcl_ApplyUpperRightTriangle(ScMatrixRef pMatA,::std::vector<double> & pVecR,ScMatrixRef pMatB,ScMatrixRef pMatZ,SCSIZE nK,bool bIsTransposed)2140 void lcl_ApplyUpperRightTriangle(ScMatrixRef pMatA,
2141                         ::std::vector< double>& pVecR, ScMatrixRef pMatB,
2142                         ScMatrixRef pMatZ, SCSIZE nK, bool bIsTransposed)
2143 {
2144     // ScMatrix matrices are zero based, index access (column,row)
2145     double fSum;
2146     for (SCSIZE row = 0; row < nK; row++)
2147     {
2148         fSum = pVecR[row] * pMatB->GetDouble(row);
2149         for (SCSIZE col = row+1; col < nK; col++)
2150             if (bIsTransposed)
2151                 fSum += pMatA->GetDouble(row,col) * pMatB->GetDouble(col);
2152             else
2153                 fSum += pMatA->GetDouble(col,row) * pMatB->GetDouble(col);
2154         pMatZ->PutDouble( fSum, row);
2155     }
2156 }
2157 
2158 
2159 
lcl_GetMeanOverAll(ScMatrixRef pMat,SCSIZE nN)2160 double lcl_GetMeanOverAll(ScMatrixRef pMat, SCSIZE nN)
2161 {
2162     double fSum = 0.0;
2163     for (SCSIZE i=0 ; i<nN; i++)
2164         fSum += pMat->GetDouble(i);
2165     return fSum/static_cast<double>(nN);
2166 }
2167 
2168 // Calculates means of the columns of matrix X. X is a RxC matrix;
2169 // ResMat is a 1xC matrix (=row).
lcl_CalculateColumnMeans(ScMatrixRef pX,ScMatrixRef pResMat,SCSIZE nC,SCSIZE nR)2170 void lcl_CalculateColumnMeans(ScMatrixRef pX, ScMatrixRef pResMat,
2171                                  SCSIZE nC, SCSIZE nR)
2172 {
2173     double fSum = 0.0;
2174     for (SCSIZE i=0; i < nC; i++)
2175     {
2176         fSum =0.0;
2177         for (SCSIZE k=0; k < nR; k++)
2178             fSum += pX->GetDouble(i,k);   // GetDouble(Column,Row)
2179         pResMat ->PutDouble( fSum/static_cast<double>(nR),i);
2180     }
2181 }
2182 
2183 // Calculates means of the rows of matrix X. X is a RxC matrix;
2184 // ResMat is a Rx1 matrix (=column).
lcl_CalculateRowMeans(ScMatrixRef pX,ScMatrixRef pResMat,SCSIZE nC,SCSIZE nR)2185 void lcl_CalculateRowMeans(ScMatrixRef pX, ScMatrixRef pResMat,
2186                              SCSIZE nC, SCSIZE nR)
2187 {
2188     double fSum = 0.0;
2189     for (SCSIZE k=0; k < nR; k++)
2190     {
2191         fSum =0.0;
2192         for (SCSIZE i=0; i < nC; i++)
2193             fSum += pX->GetDouble(i,k);   // GetDouble(Column,Row)
2194         pResMat ->PutDouble( fSum/static_cast<double>(nC),k);
2195     }
2196 }
2197 
lcl_CalculateColumnsDelta(ScMatrixRef pMat,ScMatrixRef pColumnMeans,SCSIZE nC,SCSIZE nR)2198 void lcl_CalculateColumnsDelta(ScMatrixRef pMat, ScMatrixRef pColumnMeans,
2199                                  SCSIZE nC, SCSIZE nR)
2200 {
2201     for (SCSIZE i = 0; i < nC; i++)
2202         for (SCSIZE k = 0; k < nR; k++)
2203             pMat->PutDouble( ::rtl::math::approxSub
2204                     (pMat->GetDouble(i,k) , pColumnMeans->GetDouble(i) ) , i, k);
2205 }
2206 
lcl_CalculateRowsDelta(ScMatrixRef pMat,ScMatrixRef pRowMeans,SCSIZE nC,SCSIZE nR)2207 void lcl_CalculateRowsDelta(ScMatrixRef pMat, ScMatrixRef pRowMeans,
2208                              SCSIZE nC, SCSIZE nR)
2209 {
2210     for (SCSIZE k = 0; k < nR; k++)
2211         for (SCSIZE i = 0; i < nC; i++)
2212             pMat->PutDouble( ::rtl::math::approxSub
2213                     ( pMat->GetDouble(i,k) , pRowMeans->GetDouble(k) ) , i, k);
2214 }
2215 
2216 // Case1 = simple regression
2217 // MatX = X - MeanX, MatY = Y - MeanY, y - haty = (y - MeanY) - (haty - MeanY)
2218 // = (y-MeanY)-((slope*x+a)-(slope*MeanX+a)) = (y-MeanY)-slope*(x-MeanX)
lcl_GetSSresid(ScMatrixRef pMatX,ScMatrixRef pMatY,double fSlope,SCSIZE nN)2219 double lcl_GetSSresid(ScMatrixRef pMatX, ScMatrixRef pMatY, double fSlope,
2220                          SCSIZE nN)
2221 {
2222     double fSum = 0.0;
2223     double fTemp = 0.0;
2224     for (SCSIZE i=0; i<nN; i++)
2225     {
2226         fTemp = pMatY->GetDouble(i) - fSlope * pMatX->GetDouble(i);
2227         fSum += fTemp * fTemp;
2228     }
2229     return fSum;
2230 }
2231 
2232 // Fill default values in matrix X, transform Y to log(Y) in case LOGEST|GROWTH,
2233 // determine sizes of matrices X and Y, determine kind of regression, clone
2234 // Y in case LOGEST|GROWTH, if constant.
CheckMatrix(bool _bLOG,sal_uInt8 & nCase,SCSIZE & nCX,SCSIZE & nCY,SCSIZE & nRX,SCSIZE & nRY,SCSIZE & M,SCSIZE & N,ScMatrixRef & pMatX,ScMatrixRef & pMatY)2235 bool ScInterpreter::CheckMatrix(bool _bLOG, sal_uInt8& nCase, SCSIZE& nCX,
2236                         SCSIZE& nCY, SCSIZE& nRX, SCSIZE& nRY, SCSIZE& M,
2237                         SCSIZE& N, ScMatrixRef& pMatX, ScMatrixRef& pMatY)
2238 {
2239 
2240     nCX = 0;
2241     nCY = 0;
2242     nRX = 0;
2243     nRY = 0;
2244     M = 0;
2245     N = 0;
2246     pMatY->GetDimensions(nCY, nRY);
2247     const SCSIZE nCountY = nCY * nRY;
2248     for ( SCSIZE i = 0; i < nCountY; i++ )
2249     {
2250         if (!pMatY->IsValue(i))
2251         {
2252             PushIllegalArgument();
2253             return false;
2254         }
2255     }
2256 
2257     if ( _bLOG )
2258     {
2259         ScMatrixRef pNewY = pMatY->CloneIfConst();
2260         for (SCSIZE nElem = 0; nElem < nCountY; nElem++)
2261         {
2262             const double fVal = pNewY->GetDouble(nElem);
2263             if (fVal <= 0.0)
2264             {
2265                 PushIllegalArgument();
2266                 return false;
2267             }
2268             else
2269                 pNewY->PutDouble(log(fVal), nElem);
2270         }
2271         pMatY = pNewY;
2272     }
2273 
2274     if (pMatX)
2275     {
2276         pMatX->GetDimensions(nCX, nRX);
2277         const SCSIZE nCountX = nCX * nRX;
2278         for ( SCSIZE i = 0; i < nCountX; i++ )
2279             if (!pMatX->IsValue(i))
2280             {
2281                 PushIllegalArgument();
2282                 return false;
2283             }
2284         if (nCX == nCY && nRX == nRY)
2285         {
2286             nCase = 1;                  // simple regression
2287             M = 1;
2288             N = nCountY;
2289         }
2290         else if (nCY != 1 && nRY != 1)
2291         {
2292             PushIllegalArgument();
2293             return false;
2294         }
2295         else if (nCY == 1)
2296         {
2297             if (nRX != nRY)
2298             {
2299                 PushIllegalArgument();
2300                 return false;
2301             }
2302             else
2303             {
2304                 nCase = 2;              // Y is column
2305                 N = nRY;
2306                 M = nCX;
2307             }
2308         }
2309         else if (nCX != nCY)
2310         {
2311             PushIllegalArgument();
2312             return false;
2313         }
2314         else
2315         {
2316             nCase = 3;                  // Y is row
2317             N = nCY;
2318             M = nRX;
2319         }
2320     }
2321     else
2322     {
2323         pMatX = GetNewMat(nCY, nRY);
2324         nCX = nCY;
2325         nRX = nRY;
2326         if (!pMatX)
2327         {
2328             PushIllegalArgument();
2329             return false;
2330         }
2331         for ( SCSIZE i = 1; i <= nCountY; i++ )
2332             pMatX->PutDouble(static_cast<double>(i), i-1);
2333         nCase = 1;
2334         N = nCountY;
2335         M = 1;
2336     }
2337     return true;
2338 }
2339 // -----------------------------------------------------------------------------
2340 
2341 // LINEST
ScRGP()2342 void ScInterpreter::ScRGP()
2343 {
2344     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRGP" );
2345     CalulateRGPRKP(false);
2346 }
2347 
2348 // LOGEST
ScRKP()2349 void ScInterpreter::ScRKP()
2350 {
2351     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRKP" );
2352     CalulateRGPRKP(true);
2353 }
2354 
CalulateRGPRKP(bool _bRKP)2355 void ScInterpreter::CalulateRGPRKP(bool _bRKP)
2356 {
2357     sal_uInt8 nParamCount = GetByte();
2358     if ( !MustHaveParamCount( nParamCount, 1, 4 ) )
2359         return;
2360     bool bConstant, bStats;
2361 
2362     // optional forth parameter
2363     if (nParamCount == 4)
2364         bStats = GetBool();
2365     else
2366         bStats = false;
2367 
2368     // The third parameter may not be missing in ODF, if the forth parameter
2369     // is present. But Excel allows it with default true, we too.
2370     if (nParamCount >= 3)
2371     {
2372         if (IsMissing())
2373         {
2374             Pop();
2375             bConstant = true;
2376             //            PushIllegalParameter(); if ODF behavior is desired
2377             //            return;
2378         }
2379         else
2380             bConstant = GetBool();
2381     }
2382     else
2383         bConstant = true;
2384 
2385     ScMatrixRef pMatX;
2386     if (nParamCount >= 2)
2387     {
2388         if (IsMissing())
2389         {
2390             // In ODF1.2 empty second parameter (which is two ;; ) is allowed
2391             Pop();
2392             pMatX = NULL;
2393         }
2394         else
2395         {
2396             pMatX = GetMatrix();
2397         }
2398     }
2399     else
2400         pMatX = NULL;
2401 
2402     ScMatrixRef pMatY;
2403     pMatY = GetMatrix();
2404     if (!pMatY)
2405     {
2406         PushIllegalParameter();
2407         return;
2408     }
2409 
2410     // 1 = simple; 2 = multiple with Y as column; 3 = multiple with Y as row
2411     sal_uInt8 nCase;
2412 
2413     SCSIZE nCX, nCY;     // number of columns
2414     SCSIZE nRX, nRY;     // number of rows
2415     SCSIZE K = 0, N = 0; // K=number of variables X, N=number of data samples
2416     if ( !CheckMatrix(_bRKP,nCase,nCX,nCY,nRX,nRY,K,N,pMatX,pMatY) )
2417     {
2418         PushIllegalParameter();
2419         return;
2420     }
2421 
2422     // Enough data samples?
2423     if ( (bConstant && (N<K+1)) || (!bConstant && (N<K)) || (N<1) || (K<1) )
2424     {
2425         PushIllegalParameter();
2426         return;
2427     }
2428 
2429     ScMatrixRef pResMat;
2430     if (bStats)
2431         pResMat = GetNewMat(K+1,5);
2432     else
2433         pResMat = GetNewMat(K+1,1);
2434     if (!pResMat)
2435     {
2436         PushError(errCodeOverflow);
2437         return;
2438     }
2439     // Fill unused cells in pResMat; order (column,row)
2440     if (bStats)
2441     {
2442         for (SCSIZE i=2; i<K+1; i++)
2443         {
2444             pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), i, 2 );
2445             pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), i, 3 );
2446             pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), i, 4 );
2447         }
2448     }
2449 
2450     // Uses sum(x-MeanX)^2 and not [sum x^2]-N * MeanX^2 in case bConstant.
2451     // Clone constant matrices, so that Mat = Mat - Mean is possible.
2452     double fMeanY = 0.0;
2453     if (bConstant)
2454     {
2455         ScMatrixRef pNewX = pMatX->CloneIfConst();
2456         ScMatrixRef pNewY = pMatY->CloneIfConst();
2457         if (!pNewX || !pNewY)
2458         {
2459             PushError(errCodeOverflow);
2460             return;
2461         }
2462         pMatX = pNewX;
2463         pMatY = pNewY;
2464         // DeltaY is possible here; DeltaX depends on nCase, so later
2465         fMeanY = lcl_GetMeanOverAll(pMatY, N);
2466         for (SCSIZE i=0; i<N; i++)
2467         {
2468             pMatY->PutDouble( ::rtl::math::approxSub(pMatY->GetDouble(i),fMeanY), i );
2469         }
2470     }
2471 
2472     if (nCase==1)
2473     {
2474         // calculate simple regression
2475         double fMeanX = 0.0;
2476         if (bConstant)
2477         {   // Mat = Mat - Mean
2478             fMeanX = lcl_GetMeanOverAll(pMatX, N);
2479             for (SCSIZE i=0; i<N; i++)
2480             {
2481                 pMatX->PutDouble( ::rtl::math::approxSub(pMatX->GetDouble(i),fMeanX), i );
2482             }
2483         }
2484         double fSumXY = lcl_GetSumProduct(pMatX,pMatY,N);
2485         double fSumX2 = lcl_GetSumProduct(pMatX,pMatX,N);
2486         if (fSumX2==0.0)
2487         {
2488             PushNoValue(); // all x-values are identical
2489             return;
2490         }
2491         double fSlope = fSumXY / fSumX2;
2492         double fIntercept = 0.0;
2493         if (bConstant)
2494             fIntercept = fMeanY - fSlope * fMeanX;
2495         pResMat->PutDouble(_bRKP ? exp(fIntercept) : fIntercept, 1, 0); //order (column,row)
2496         pResMat->PutDouble(_bRKP ? exp(fSlope) : fSlope, 0, 0);
2497 
2498         if (bStats)
2499         {
2500             double fSSreg = fSlope * fSlope * fSumX2;
2501             pResMat->PutDouble(fSSreg, 0, 4);
2502 
2503             double fDegreesFreedom =static_cast<double>( (bConstant) ? N-2 : N-1 );
2504             pResMat->PutDouble(fDegreesFreedom, 1, 3);
2505 
2506             double fSSresid = lcl_GetSSresid(pMatX,pMatY,fSlope,N);
2507             pResMat->PutDouble(fSSresid, 1, 4);
2508 
2509             if (fDegreesFreedom == 0.0 || fSSresid == 0.0 || fSSreg == 0.0)
2510             {   // exact fit; test SSreg too, because SSresid might be
2511                 // unequal zero due to round of errors
2512                 pResMat->PutDouble(0.0, 1, 4); // SSresid
2513                 pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), 0, 3); // F
2514                 pResMat->PutDouble(0.0, 1, 2); // RMSE
2515                 pResMat->PutDouble(0.0, 0, 1); // SigmaSlope
2516                 if (bConstant)
2517                     pResMat->PutDouble(0.0, 1, 1); //SigmaIntercept
2518                 else
2519                     pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), 1, 1);
2520                 pResMat->PutDouble(1.0, 0, 2); // R^2
2521             }
2522             else
2523             {
2524                 double fFstatistic = (fSSreg / static_cast<double>(K))
2525                     / (fSSresid / fDegreesFreedom);
2526                 pResMat->PutDouble(fFstatistic, 0, 3);
2527 
2528                 // standard error of estimate
2529                 double fRMSE = sqrt(fSSresid / fDegreesFreedom);
2530                 pResMat->PutDouble(fRMSE, 1, 2);
2531 
2532                 double fSigmaSlope = fRMSE / sqrt(fSumX2);
2533                 pResMat->PutDouble(fSigmaSlope, 0, 1);
2534 
2535                 if (bConstant)
2536                 {
2537                     double fSigmaIntercept = fRMSE
2538                         * sqrt(fMeanX*fMeanX/fSumX2 + 1.0/static_cast<double>(N));
2539                     pResMat->PutDouble(fSigmaIntercept, 1, 1);
2540                 }
2541                 else
2542                 {
2543                     pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), 1, 1);
2544                 }
2545 
2546                 double fR2 = fSSreg / (fSSreg + fSSresid);
2547                 pResMat->PutDouble(fR2, 0, 2);
2548             }
2549         }
2550         PushMatrix(pResMat);
2551     }
2552     else // calculate multiple regression;
2553     {
2554         // Uses a QR decomposition X = QR. The solution B = (X'X)^(-1) * X' * Y
2555         // becomes B = R^(-1) * Q' * Y
2556         if (nCase ==2) // Y is column
2557         {
2558             ::std::vector< double> aVecR(N); // for QR decomposition
2559             // Enough memory for needed matrices?
2560             ScMatrixRef pMeans = GetNewMat(K, 1); // mean of each column
2561             ScMatrixRef pMatZ; // for Q' * Y , inter alia
2562             if (bStats)
2563                 pMatZ = pMatY->Clone(); // Y is used in statistic, keep it
2564             else
2565                 pMatZ = pMatY; // Y can be overwritten
2566             ScMatrixRef pSlopes = GetNewMat(1,K); // from b1 to bK
2567             if (!pMeans || !pMatZ || !pSlopes)
2568             {
2569                 PushError(errCodeOverflow);
2570                 return;
2571             }
2572             if (bConstant)
2573             {
2574                 lcl_CalculateColumnMeans(pMatX, pMeans, K, N);
2575                 lcl_CalculateColumnsDelta(pMatX, pMeans, K, N);
2576             }
2577             if (!lcl_CalculateQRdecomposition(pMatX, aVecR, K, N))
2578             {
2579                 PushNoValue();
2580                 return;
2581             }
2582             // Later on we will divide by elements of aVecR, so make sure
2583             // that they aren't zero.
2584             bool bIsSingular=false;
2585             for (SCSIZE row=0; row < K && !bIsSingular; row++)
2586                 bIsSingular = bIsSingular || aVecR[row]==0.0;
2587             if (bIsSingular)
2588             {
2589                 PushNoValue();
2590                 return;
2591             }
2592             // Z = Q' Y;
2593             for (SCSIZE col = 0; col < K; col++)
2594             {
2595                 lcl_ApplyHouseholderTransformation(pMatX, col, pMatZ, N);
2596             }
2597             // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
2598             // result Z should have zeros for index>=K; if not, ignore values
2599             for (SCSIZE col = 0; col < K ; col++)
2600             {
2601                 pSlopes->PutDouble( pMatZ->GetDouble(col), col);
2602             }
2603             lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, false);
2604             double fIntercept = 0.0;
2605             if (bConstant)
2606                 fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
2607             // Fill first line in result matrix
2608             pResMat->PutDouble(_bRKP ? exp(fIntercept) : fIntercept, K, 0 );
2609             for (SCSIZE i = 0; i < K; i++)
2610                 pResMat->PutDouble(_bRKP ? exp(pSlopes->GetDouble(i))
2611                         : pSlopes->GetDouble(i) , K-1-i, 0);
2612 
2613 
2614             if (bStats)
2615             {
2616                 double fSSreg = 0.0;
2617                 double fSSresid = 0.0;
2618                 // re-use memory of Z;
2619                 pMatZ->FillDouble(0.0, 0, 0, 0, N-1);
2620                 // Z = R * Slopes
2621                 lcl_ApplyUpperRightTriangle(pMatX, aVecR, pSlopes, pMatZ, K, false);
2622                 // Z = Q * Z, that is Q * R * Slopes = X * Slopes
2623                 for (SCSIZE colp1 = K; colp1 > 0; colp1--)
2624                 {
2625                     lcl_ApplyHouseholderTransformation(pMatX, colp1-1, pMatZ,N);
2626                 }
2627                 fSSreg =lcl_GetSumProduct(pMatZ, pMatZ, N);
2628                 // re-use Y for residuals, Y = Y-Z
2629                 for (SCSIZE row = 0; row < N; row++)
2630                     pMatY->PutDouble(pMatY->GetDouble(row) - pMatZ->GetDouble(row), row);
2631                 fSSresid = lcl_GetSumProduct(pMatY, pMatY, N);
2632                 pResMat->PutDouble(fSSreg, 0, 4);
2633                 pResMat->PutDouble(fSSresid, 1, 4);
2634 
2635                 double fDegreesFreedom =static_cast<double>( (bConstant) ? N-K-1 : N-K );
2636                 pResMat->PutDouble(fDegreesFreedom, 1, 3);
2637 
2638                 if (fDegreesFreedom == 0.0 || fSSresid == 0.0 || fSSreg == 0.0)
2639                 {   // exact fit; incl. observed values Y are identical
2640                     pResMat->PutDouble(0.0, 1, 4); // SSresid
2641                     // F = (SSreg/K) / (SSresid/df) = #DIV/0!
2642                     pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), 0, 3); // F
2643                     // RMSE = sqrt(SSresid / df) = sqrt(0 / df) = 0
2644                     pResMat->PutDouble(0.0, 1, 2); // RMSE
2645                     // SigmaSlope[i] = RMSE * sqrt(matrix[i,i]) = 0 * sqrt(...) = 0
2646                     for (SCSIZE i=0; i<K; i++)
2647                         pResMat->PutDouble(0.0, K-1-i, 1);
2648 
2649                     // SigmaIntercept = RMSE * sqrt(...) = 0
2650                     if (bConstant)
2651                         pResMat->PutDouble(0.0, K, 1); //SigmaIntercept
2652                     else
2653                         pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), K, 1);
2654 
2655                     //  R^2 = SSreg / (SSreg + SSresid) = 1.0
2656                     pResMat->PutDouble(1.0, 0, 2); // R^2
2657                 }
2658                 else
2659                 {
2660                     double fFstatistic = (fSSreg / static_cast<double>(K))
2661                         / (fSSresid / fDegreesFreedom);
2662                     pResMat->PutDouble(fFstatistic, 0, 3);
2663 
2664                     // standard error of estimate = root mean SSE
2665                     double fRMSE = sqrt(fSSresid / fDegreesFreedom);
2666                     pResMat->PutDouble(fRMSE, 1, 2);
2667 
2668                     // standard error of slopes
2669                     // = RMSE * sqrt(diagonal element of (R' R)^(-1) )
2670                     // standard error of intercept
2671                     // = RMSE * sqrt( Xmean * (R' R)^(-1) * Xmean' + 1/N)
2672                     // (R' R)^(-1) = R^(-1) * (R')^(-1). Do not calculate it as
2673                     // a whole matrix, but iterate over unit vectors.
2674                     double fSigmaSlope = 0.0;
2675                     double fSigmaIntercept = 0.0;
2676                     double fPart; // for Xmean * single column of (R' R)^(-1)
2677                     for (SCSIZE col = 0; col < K; col++)
2678                     {
2679                         //re-use memory of MatZ
2680                         pMatZ->FillDouble(0.0,0,0,0,K-1); // Z = unit vector e
2681                         pMatZ->PutDouble(1.0, col);
2682                         //Solve R' * Z = e
2683                         lcl_SolveWithLowerLeftTriangle(pMatX, aVecR, pMatZ, K, false);
2684                         // Solve R * Znew = Zold
2685                         lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pMatZ, K, false);
2686                         // now Z is column col in (R' R)^(-1)
2687                         fSigmaSlope = fRMSE * sqrt(pMatZ->GetDouble(col));
2688                         pResMat->PutDouble(fSigmaSlope, K-1-col, 1);
2689                         // (R' R) ^(-1) is symmetric
2690                         if (bConstant)
2691                         {
2692                             fPart = lcl_GetSumProduct(pMeans, pMatZ, K);
2693                             fSigmaIntercept += fPart * pMeans->GetDouble(col);
2694                         }
2695                     }
2696                     if (bConstant)
2697                     {
2698                         fSigmaIntercept = fRMSE
2699                             * sqrt(fSigmaIntercept + 1.0 / static_cast<double>(N));
2700                         pResMat->PutDouble(fSigmaIntercept, K, 1);
2701                     }
2702                     else
2703                     {
2704                         pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), K, 1);
2705                     }
2706 
2707                     double fR2 = fSSreg / (fSSreg + fSSresid);
2708                     pResMat->PutDouble(fR2, 0, 2);
2709                 }
2710             }
2711             PushMatrix(pResMat);
2712         }
2713         else  // nCase == 3, Y is row, all matrices are transposed
2714         {
2715             ::std::vector< double> aVecR(N); // for QR decomposition
2716             // Enough memory for needed matrices?
2717             ScMatrixRef pMeans = GetNewMat(1, K); // mean of each row
2718             ScMatrixRef pMatZ; // for Q' * Y , inter alia
2719             if (bStats)
2720                 pMatZ = pMatY->Clone(); // Y is used in statistic, keep it
2721             else
2722                 pMatZ = pMatY; // Y can be overwritten
2723             ScMatrixRef pSlopes = GetNewMat(K,1); // from b1 to bK
2724             if (!pMeans || !pMatZ || !pSlopes)
2725             {
2726                 PushError(errCodeOverflow);
2727                 return;
2728             }
2729             if (bConstant)
2730             {
2731                 lcl_CalculateRowMeans(pMatX, pMeans, N, K);
2732                 lcl_CalculateRowsDelta(pMatX, pMeans, N, K);
2733             }
2734 
2735             if (!lcl_TCalculateQRdecomposition(pMatX, aVecR, K, N))
2736             {
2737                 PushNoValue();
2738                 return;
2739             }
2740 
2741             // Later on we will divide by elements of aVecR, so make sure
2742             // that they aren't zero.
2743             bool bIsSingular=false;
2744             for (SCSIZE row=0; row < K && !bIsSingular; row++)
2745                 bIsSingular = bIsSingular || aVecR[row]==0.0;
2746             if (bIsSingular)
2747             {
2748                 PushNoValue();
2749                 return;
2750             }
2751             // Z = Q' Y
2752             for (SCSIZE row = 0; row < K; row++)
2753             {
2754                 lcl_TApplyHouseholderTransformation(pMatX, row, pMatZ, N);
2755             }
2756             // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
2757             // result Z should have zeros for index>=K; if not, ignore values
2758             for (SCSIZE col = 0; col < K ; col++)
2759             {
2760                 pSlopes->PutDouble( pMatZ->GetDouble(col), col);
2761             }
2762             lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, true);
2763             double fIntercept = 0.0;
2764             if (bConstant)
2765                 fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
2766             // Fill first line in result matrix
2767             pResMat->PutDouble(_bRKP ? exp(fIntercept) : fIntercept, K, 0 );
2768             for (SCSIZE i = 0; i < K; i++)
2769                 pResMat->PutDouble(_bRKP ? exp(pSlopes->GetDouble(i))
2770                         : pSlopes->GetDouble(i) , K-1-i, 0);
2771 
2772 
2773             if (bStats)
2774             {
2775                 double fSSreg = 0.0;
2776                 double fSSresid = 0.0;
2777                 // re-use memory of Z;
2778                 pMatZ->FillDouble(0.0, 0, 0, N-1, 0);
2779                 // Z = R * Slopes
2780                 lcl_ApplyUpperRightTriangle(pMatX, aVecR, pSlopes, pMatZ, K, true);
2781                 // Z = Q * Z, that is Q * R * Slopes = X * Slopes
2782                 for (SCSIZE rowp1 = K; rowp1 > 0; rowp1--)
2783                 {
2784                     lcl_TApplyHouseholderTransformation(pMatX, rowp1-1, pMatZ,N);
2785                 }
2786                 fSSreg =lcl_GetSumProduct(pMatZ, pMatZ, N);
2787                 // re-use Y for residuals, Y = Y-Z
2788                 for (SCSIZE col = 0; col < N; col++)
2789                     pMatY->PutDouble(pMatY->GetDouble(col) - pMatZ->GetDouble(col), col);
2790                 fSSresid = lcl_GetSumProduct(pMatY, pMatY, N);
2791                 pResMat->PutDouble(fSSreg, 0, 4);
2792                 pResMat->PutDouble(fSSresid, 1, 4);
2793 
2794                 double fDegreesFreedom =static_cast<double>( (bConstant) ? N-K-1 : N-K );
2795                 pResMat->PutDouble(fDegreesFreedom, 1, 3);
2796 
2797                 if (fDegreesFreedom == 0.0 || fSSresid == 0.0 || fSSreg == 0.0)
2798                 {   // exact fit; incl. case observed values Y are identical
2799                     pResMat->PutDouble(0.0, 1, 4); // SSresid
2800                     // F = (SSreg/K) / (SSresid/df) = #DIV/0!
2801                     pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), 0, 3); // F
2802                     // RMSE = sqrt(SSresid / df) = sqrt(0 / df) = 0
2803                     pResMat->PutDouble(0.0, 1, 2); // RMSE
2804                     // SigmaSlope[i] = RMSE * sqrt(matrix[i,i]) = 0 * sqrt(...) = 0
2805                     for (SCSIZE i=0; i<K; i++)
2806                         pResMat->PutDouble(0.0, K-1-i, 1);
2807 
2808                     // SigmaIntercept = RMSE * sqrt(...) = 0
2809                     if (bConstant)
2810                         pResMat->PutDouble(0.0, K, 1); //SigmaIntercept
2811                     else
2812                         pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), K, 1);
2813 
2814                     //  R^2 = SSreg / (SSreg + SSresid) = 1.0
2815                     pResMat->PutDouble(1.0, 0, 2); // R^2
2816                 }
2817                 else
2818                 {
2819                     double fFstatistic = (fSSreg / static_cast<double>(K))
2820                         / (fSSresid / fDegreesFreedom);
2821                     pResMat->PutDouble(fFstatistic, 0, 3);
2822 
2823                     // standard error of estimate = root mean SSE
2824                     double fRMSE = sqrt(fSSresid / fDegreesFreedom);
2825                     pResMat->PutDouble(fRMSE, 1, 2);
2826 
2827                     // standard error of slopes
2828                     // = RMSE * sqrt(diagonal element of (R' R)^(-1) )
2829                     // standard error of intercept
2830                     // = RMSE * sqrt( Xmean * (R' R)^(-1) * Xmean' + 1/N)
2831                     // (R' R)^(-1) = R^(-1) * (R')^(-1). Do not calculate it as
2832                     // a whole matrix, but iterate over unit vectors.
2833                     // (R' R) ^(-1) is symmetric
2834                     double fSigmaSlope = 0.0;
2835                     double fSigmaIntercept = 0.0;
2836                     double fPart; // for Xmean * single col of (R' R)^(-1)
2837                     for (SCSIZE row = 0; row < K; row++)
2838                     {
2839                         //re-use memory of MatZ
2840                         pMatZ->FillDouble(0.0,0,0,K-1,0); // Z = unit vector e
2841                         pMatZ->PutDouble(1.0, row);
2842                         //Solve R' * Z = e
2843                         lcl_SolveWithLowerLeftTriangle(pMatX, aVecR, pMatZ, K, true);
2844                         // Solve R * Znew = Zold
2845                         lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pMatZ, K, true);
2846                         // now Z is column col in (R' R)^(-1)
2847                         fSigmaSlope = fRMSE * sqrt(pMatZ->GetDouble(row));
2848                         pResMat->PutDouble(fSigmaSlope, K-1-row, 1);
2849                         if (bConstant)
2850                         {
2851                             fPart = lcl_GetSumProduct(pMeans, pMatZ, K);
2852                             fSigmaIntercept += fPart * pMeans->GetDouble(row);
2853                         }
2854                     }
2855                     if (bConstant)
2856                     {
2857                         fSigmaIntercept = fRMSE
2858                             * sqrt(fSigmaIntercept + 1.0 / static_cast<double>(N));
2859                         pResMat->PutDouble(fSigmaIntercept, K, 1);
2860                     }
2861                     else
2862                     {
2863                         pResMat->PutString(ScGlobal::GetRscString(STR_NV_STR), K, 1);
2864                     }
2865 
2866                     double fR2 = fSSreg / (fSSreg + fSSresid);
2867                     pResMat->PutDouble(fR2, 0, 2);
2868                 }
2869             }
2870             PushMatrix(pResMat);
2871         }
2872     }
2873     return;
2874 }
2875 
ScTrend()2876 void ScInterpreter::ScTrend()
2877 {
2878     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScTrend" );
2879     CalculateTrendGrowth(false);
2880 }
2881 
ScGrowth()2882 void ScInterpreter::ScGrowth()
2883 {
2884     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGrowth" );
2885     CalculateTrendGrowth(true);
2886 }
2887 
CalculateTrendGrowth(bool _bGrowth)2888 void ScInterpreter::CalculateTrendGrowth(bool _bGrowth)
2889 {
2890     sal_uInt8 nParamCount = GetByte();
2891     if ( !MustHaveParamCount( nParamCount, 1, 4 ) )
2892         return;
2893 
2894     // optional fourth parameter
2895     bool bConstant;
2896     if (nParamCount == 4)
2897         bConstant = GetBool();
2898     else
2899         bConstant = true;
2900 
2901     // The third parameter may be missing in ODF, although the fourth parameter
2902     // is present. Default values depend on data not yet read.
2903     ScMatrixRef pMatNewX;
2904     if (nParamCount >= 3)
2905     {
2906         if (IsMissing())
2907         {
2908             Pop();
2909             pMatNewX = NULL;
2910         }
2911         else
2912             pMatNewX = GetMatrix();
2913     }
2914     else
2915         pMatNewX = NULL;
2916 
2917     // In ODF1.2 empty second parameter (which is two ;; ) is allowed.
2918     // Defaults will be set in CheckMatrix.
2919     ScMatrixRef pMatX;
2920     if (nParamCount >= 2)
2921     {
2922         if (IsMissing())
2923         {
2924             Pop();
2925             pMatX = NULL;
2926         }
2927         else
2928         {
2929             pMatX = GetMatrix();
2930         }
2931     }
2932     else
2933         pMatX = NULL;
2934 
2935     ScMatrixRef pMatY;
2936     pMatY = GetMatrix();
2937     if (!pMatY)
2938     {
2939         PushIllegalParameter();
2940         return;
2941     }
2942 
2943     // 1 = simple; 2 = multiple with Y as column; 3 = multiple with Y as row
2944     sal_uInt8 nCase;
2945 
2946     SCSIZE nCX, nCY;     // number of columns
2947     SCSIZE nRX, nRY;     // number of rows
2948     SCSIZE K = 0, N = 0; // K=number of variables X, N=number of data samples
2949     if ( !CheckMatrix(_bGrowth,nCase,nCX,nCY,nRX,nRY,K,N,pMatX,pMatY) )
2950     {
2951         PushIllegalParameter();
2952         return;
2953     }
2954 
2955     // Enough data samples?
2956     if ( (bConstant && (N<K+1)) || (!bConstant && (N<K)) || (N<1) || (K<1) )
2957     {
2958         PushIllegalParameter();
2959         return;
2960     }
2961 
2962     // Set default pMatNewX if necessary
2963     SCSIZE nCXN, nRXN;
2964     SCSIZE nCountXN;
2965     if (!pMatNewX)
2966     {
2967         nCXN = nCX;
2968         nRXN = nRX;
2969         nCountXN = nCXN * nRXN;
2970         pMatNewX = pMatX->Clone(); // pMatX will be changed to X-meanX
2971     }
2972     else
2973     {
2974         pMatNewX->GetDimensions(nCXN, nRXN);
2975         if ((nCase == 2 && K != nCXN) || (nCase == 3 && K != nRXN))
2976         {
2977             PushIllegalArgument();
2978             return;
2979         }
2980         nCountXN = nCXN * nRXN;
2981         for ( SCSIZE i = 0; i < nCountXN; i++ )
2982             if (!pMatNewX->IsValue(i))
2983             {
2984                 PushIllegalArgument();
2985                 return;
2986             }
2987     }
2988     ScMatrixRef pResMat; // size depends on nCase
2989     if (nCase == 1)
2990         pResMat = GetNewMat(nCXN,nRXN);
2991     else
2992     {
2993         if (nCase==2)
2994             pResMat = GetNewMat(1,nRXN);
2995         else
2996             pResMat = GetNewMat(nCXN,1);
2997     }
2998     if (!pResMat)
2999     {
3000         PushError(errCodeOverflow);
3001         return;
3002     }
3003     // Uses sum(x-MeanX)^2 and not [sum x^2]-N * MeanX^2 in case bConstant.
3004     // Clone constant matrices, so that Mat = Mat - Mean is possible.
3005     double fMeanY = 0.0;
3006     if (bConstant)
3007     {
3008         ScMatrixRef pCopyX = pMatX->CloneIfConst();
3009         ScMatrixRef pCopyY = pMatY->CloneIfConst();
3010         if (!pCopyX || !pCopyY)
3011         {
3012             PushError(errStackOverflow);
3013             return;
3014         }
3015         pMatX = pCopyX;
3016         pMatY = pCopyY;
3017         // DeltaY is possible here; DeltaX depends on nCase, so later
3018         fMeanY = lcl_GetMeanOverAll(pMatY, N);
3019         for (SCSIZE i=0; i<N; i++)
3020         {
3021             pMatY->PutDouble( ::rtl::math::approxSub(pMatY->GetDouble(i),fMeanY), i );
3022         }
3023     }
3024 
3025     if (nCase==1)
3026     {
3027         // calculate simple regression
3028         double fMeanX = 0.0;
3029         if (bConstant)
3030         {   // Mat = Mat - Mean
3031             fMeanX = lcl_GetMeanOverAll(pMatX, N);
3032             for (SCSIZE i=0; i<N; i++)
3033             {
3034                 pMatX->PutDouble( ::rtl::math::approxSub(pMatX->GetDouble(i),fMeanX), i );
3035             }
3036         }
3037         double fSumXY = lcl_GetSumProduct(pMatX,pMatY,N);
3038         double fSumX2 = lcl_GetSumProduct(pMatX,pMatX,N);
3039         if (fSumX2==0.0)
3040         {
3041             PushNoValue(); // all x-values are identical
3042             return;
3043         }
3044         double fSlope = fSumXY / fSumX2;
3045         double fIntercept = 0.0;
3046         double fHelp;
3047         if (bConstant)
3048         {
3049             fIntercept = fMeanY - fSlope * fMeanX;
3050             for (SCSIZE i = 0; i < nCountXN; i++)
3051             {
3052                 fHelp = pMatNewX->GetDouble(i)*fSlope + fIntercept;
3053                 pResMat->PutDouble(_bGrowth ? exp(fHelp) : fHelp, i);
3054             }
3055         }
3056         else
3057         {
3058             for (SCSIZE i = 0; i < nCountXN; i++)
3059             {
3060                 fHelp = pMatNewX->GetDouble(i)*fSlope;
3061                 pResMat->PutDouble(_bGrowth ? exp(fHelp) : fHelp, i);
3062             }
3063         }
3064     }
3065     else // calculate multiple regression;
3066     {
3067         if (nCase ==2) // Y is column
3068         {
3069             ::std::vector< double> aVecR(N); // for QR decomposition
3070             // Enough memory for needed matrices?
3071             ScMatrixRef pMeans = GetNewMat(K, 1); // mean of each column
3072             ScMatrixRef pSlopes = GetNewMat(1,K); // from b1 to bK
3073             if (!pMeans || !pSlopes)
3074             {
3075                 PushError(errCodeOverflow);
3076                 return;
3077             }
3078             if (bConstant)
3079             {
3080                 lcl_CalculateColumnMeans(pMatX, pMeans, K, N);
3081                 lcl_CalculateColumnsDelta(pMatX, pMeans, K, N);
3082             }
3083             if (!lcl_CalculateQRdecomposition(pMatX, aVecR, K, N))
3084             {
3085                 PushNoValue();
3086                 return;
3087             }
3088             // Later on we will divide by elements of aVecR, so make sure
3089             // that they aren't zero.
3090             bool bIsSingular=false;
3091             for (SCSIZE row=0; row < K && !bIsSingular; row++)
3092                 bIsSingular = bIsSingular || aVecR[row]==0.0;
3093             if (bIsSingular)
3094             {
3095                 PushNoValue();
3096                 return;
3097             }
3098             // Z := Q' Y; Y is overwritten with result Z
3099             for (SCSIZE col = 0; col < K; col++)
3100             {
3101                 lcl_ApplyHouseholderTransformation(pMatX, col, pMatY, N);
3102             }
3103             // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
3104             // result Z should have zeros for index>=K; if not, ignore values
3105             for (SCSIZE col = 0; col < K ; col++)
3106             {
3107                 pSlopes->PutDouble( pMatY->GetDouble(col), col);
3108             }
3109             lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, false);
3110 
3111             // Fill result matrix
3112             lcl_MFastMult(pMatNewX,pSlopes,pResMat,nRXN,K,1);
3113             if (bConstant)
3114             {
3115                 double fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
3116                 for (SCSIZE row = 0; row < nRXN; row++)
3117                     pResMat->PutDouble(pResMat->GetDouble(row)+fIntercept, row);
3118             }
3119             if (_bGrowth)
3120             {
3121                 for (SCSIZE i = 0; i < nRXN; i++)
3122                     pResMat->PutDouble(exp(pResMat->GetDouble(i)), i);
3123             }
3124         }
3125         else
3126         {   // nCase == 3, Y is row, all matrices are transposed
3127 
3128             ::std::vector< double> aVecR(N); // for QR decomposition
3129             // Enough memory for needed matrices?
3130             ScMatrixRef pMeans = GetNewMat(1, K); // mean of each row
3131             ScMatrixRef pSlopes = GetNewMat(K,1); // row from b1 to bK
3132             if (!pMeans || !pSlopes)
3133             {
3134                 PushError(errCodeOverflow);
3135                 return;
3136             }
3137             if (bConstant)
3138             {
3139                 lcl_CalculateRowMeans(pMatX, pMeans, N, K);
3140                 lcl_CalculateRowsDelta(pMatX, pMeans, N, K);
3141             }
3142             if (!lcl_TCalculateQRdecomposition(pMatX, aVecR, K, N))
3143             {
3144                 PushNoValue();
3145                 return;
3146             }
3147             // Later on we will divide by elements of aVecR, so make sure
3148             // that they aren't zero.
3149             bool bIsSingular=false;
3150             for (SCSIZE row=0; row < K && !bIsSingular; row++)
3151                 bIsSingular = bIsSingular || aVecR[row]==0.0;
3152             if (bIsSingular)
3153             {
3154                 PushNoValue();
3155                 return;
3156             }
3157             // Z := Q' Y; Y is overwritten with result Z
3158             for (SCSIZE row = 0; row < K; row++)
3159             {
3160                 lcl_TApplyHouseholderTransformation(pMatX, row, pMatY, N);
3161             }
3162             // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
3163             // result Z should have zeros for index>=K; if not, ignore values
3164             for (SCSIZE col = 0; col < K ; col++)
3165             {
3166                 pSlopes->PutDouble( pMatY->GetDouble(col), col);
3167             }
3168             lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, true);
3169 
3170             // Fill result matrix
3171             lcl_MFastMult(pSlopes,pMatNewX,pResMat,1,K,nCXN);
3172             if (bConstant)
3173             {
3174                 double fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
3175                 for (SCSIZE col = 0; col < nCXN; col++)
3176                     pResMat->PutDouble(pResMat->GetDouble(col)+fIntercept, col);
3177             }
3178             if (_bGrowth)
3179             {
3180                 for (SCSIZE i = 0; i < nCXN; i++)
3181                     pResMat->PutDouble(exp(pResMat->GetDouble(i)), i);
3182             }
3183         }
3184     }
3185     PushMatrix(pResMat);
3186     return;
3187 }
3188 
ScMatRef()3189 void ScInterpreter::ScMatRef()
3190 {
3191     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMatRef" );
3192     // Falls Deltarefs drin sind...
3193     Push( (FormulaToken&)*pCur );
3194     ScAddress aAdr;
3195     PopSingleRef( aAdr );
3196     ScFormulaCell* pCell = (ScFormulaCell*) GetCell( aAdr );
3197     if( pCell && pCell->GetCellType() == CELLTYPE_FORMULA )
3198     {
3199         const ScMatrix* pMat = pCell->GetMatrix();
3200         if( pMat )
3201         {
3202             SCSIZE nCols, nRows;
3203             pMat->GetDimensions( nCols, nRows );
3204             SCSIZE nC = static_cast<SCSIZE>(aPos.Col() - aAdr.Col());
3205             SCSIZE nR = static_cast<SCSIZE>(aPos.Row() - aAdr.Row());
3206             if ((nCols <= nC && nCols != 1) || (nRows <= nR && nRows != 1))
3207                 PushNA();
3208             else
3209             {
3210                 ScMatValType nMatValType;
3211                 const ScMatrixValue* pMatVal = pMat->Get( nC, nR, nMatValType);
3212                 if (ScMatrix::IsNonValueType( nMatValType))
3213                 {
3214                     if (ScMatrix::IsEmptyPathType( nMatValType))
3215                     {   // result of empty sal_False jump path
3216                         nFuncFmtType = NUMBERFORMAT_LOGICAL;
3217                         PushInt(0);
3218                     }
3219                     else if (ScMatrix::IsEmptyType( nMatValType))
3220                     {
3221                         // Not inherited (really?) and display as empty string, not 0.
3222                         PushTempToken( new ScEmptyCellToken( false, true));
3223                     }
3224                     else
3225                         PushString( pMatVal->GetString() );
3226                 }
3227                 else
3228                 {
3229                     PushDouble(pMatVal->fVal);  // handles DoubleError
3230                     pDok->GetNumberFormatInfo( nCurFmtType, nCurFmtIndex, aAdr, pCell );
3231                     nFuncFmtType = nCurFmtType;
3232                     nFuncFmtIndex = nCurFmtIndex;
3233                 }
3234             }
3235         }
3236         else
3237         {
3238             // If not a result matrix, obtain the cell value.
3239             sal_uInt16 nErr = pCell->GetErrCode();
3240             if (nErr)
3241                 PushError( nErr );
3242             else if( pCell->IsValue() )
3243                 PushDouble( pCell->GetValue() );
3244             else
3245             {
3246                 String aVal;
3247                 pCell->GetString( aVal );
3248                 PushString( aVal );
3249             }
3250             pDok->GetNumberFormatInfo( nCurFmtType, nCurFmtIndex, aAdr, pCell );
3251             nFuncFmtType = nCurFmtType;
3252             nFuncFmtIndex = nCurFmtIndex;
3253         }
3254     }
3255     else
3256         PushError( errNoRef );
3257 }
3258 
ScInfo()3259 void ScInterpreter::ScInfo()
3260 {
3261     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScInfo" );
3262     if( MustHaveParamCount( GetByte(), 1 ) )
3263     {
3264         String aStr = GetString();
3265         ScCellKeywordTranslator::transKeyword(aStr, ScGlobal::GetLocale(), ocInfo);
3266         if( aStr.EqualsAscii( "SYSTEM" ) )
3267             PushString( String( RTL_CONSTASCII_USTRINGPARAM( SC_INFO_OSVERSION ) ) );
3268         else if( aStr.EqualsAscii( "OSVERSION" ) )
3269             PushString( String( RTL_CONSTASCII_USTRINGPARAM( "Windows (32-bit) NT 5.01" ) ) );
3270         else if( aStr.EqualsAscii( "RELEASE" ) )
3271             PushString( ::utl::Bootstrap::getBuildIdData( ::rtl::OUString() ) );
3272         else if( aStr.EqualsAscii( "NUMFILE" ) )
3273             PushDouble( 1 );
3274         else if( aStr.EqualsAscii( "RECALC" ) )
3275             PushString( ScGlobal::GetRscString( pDok->GetAutoCalc() ? STR_RECALC_AUTO : STR_RECALC_MANUAL ) );
3276         else
3277             PushIllegalArgument();
3278     }
3279 }
3280