LanguageTool: don't crash if REST protocol isn't set
[LibreOffice.git] / sc / inc / scmatrix.hxx
blob9026288c55cffef182da9e5ceca6738870035e0b
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #pragma once
22 #include "address.hxx"
23 #include "matrixoperators.hxx"
24 #include "types.hxx"
25 #include <formula/errorcodes.hxx>
26 #include "scdllapi.h"
27 #include <svl/sharedstring.hxx>
28 #include <svl/sharedstringpool.hxx>
30 #include <memory>
31 #include <utility>
32 #include <vector>
34 #define DEBUG_MATRIX 0
36 class ScInterpreter;
37 class SvNumberFormatter;
38 class ScMatrixImpl;
39 enum class FormulaError : sal_uInt16;
41 namespace sc {
43 struct Compare;
44 struct CompareOptions;
48 /**
49 * Try NOT to use this struct. This struct should go away in a hopefully
50 * not so distant future.
52 struct ScMatrixValue
54 double fVal;
55 svl::SharedString aStr;
56 ScMatValType nType;
58 /// Only valid if ScMatrix methods indicate so!
59 const svl::SharedString& GetString() const { return aStr; }
61 /// Only valid if ScMatrix methods indicate that this is no string!
62 FormulaError GetError() const { return GetDoubleErrorValue(fVal); }
64 /// Only valid if ScMatrix methods indicate that this is a boolean
65 bool GetBoolean() const { return fVal != 0.0; }
67 ScMatrixValue() : fVal(0.0), nType(ScMatValType::Empty) {}
69 ScMatrixValue(const ScMatrixValue& r) :
70 fVal(r.fVal), aStr(r.aStr), nType(r.nType) {}
72 bool operator== (const ScMatrixValue& r) const
74 if (nType != r.nType)
75 return false;
77 switch (nType)
79 case ScMatValType::Value:
80 case ScMatValType::Boolean:
81 return fVal == r.fVal;
82 break;
83 default:
87 return aStr == r.aStr;
90 bool operator!= (const ScMatrixValue& r) const
92 return !operator==(r);
95 ScMatrixValue& operator= (const ScMatrixValue& r)
97 if (this == &r)
98 return *this;
100 nType = r.nType;
101 fVal = r.fVal;
102 aStr = r.aStr;
103 return *this;
108 * Matrix data type that can store values of mixed types. Each element can
109 * be one of the following types: numeric, string, boolean, empty, and empty
110 * path.
112 class SC_DLLPUBLIC ScMatrix final
114 friend class ScMatrixImpl;
116 mutable size_t nRefCnt; // reference count
117 mutable bool mbCloneIfConst; // Whether the matrix is cloned with a CloneIfConst() call.
118 std::unique_ptr<ScMatrixImpl> pImpl;
120 ScMatrix( const ScMatrix& ) = delete;
121 ScMatrix& operator=( const ScMatrix&) = delete;
123 public:
124 ScMatrix(SCSIZE nC, SCSIZE nR);
125 ScMatrix(SCSIZE nC, SCSIZE nR, double fInitVal);
126 ScMatrix( size_t nC, size_t nR, const std::vector<double>& rInitVals );
127 ~ScMatrix();
129 typedef std::function<void(size_t, size_t, double)> DoubleOpFunction;
130 typedef std::function<void(size_t, size_t, bool)> BoolOpFunction;
131 typedef std::function<void(size_t, size_t, svl::SharedString)> StringOpFunction;
132 typedef std::function<void(size_t, size_t)> EmptyOpFunction;
135 * When adding all numerical matrix elements for a scalar result such as
136 * summation, the interpreter wants to separate the first non-zero value
137 * with the rest of the summed values. This is necessary for better
138 * numerical stability, unless we sort all by absolute values before
139 * summing (not really an option) or use another algorithm, e.g. Kahan's
140 * summation algorithm,
141 * https://en.wikipedia.org/wiki/Kahan_summation_algorithm
143 template<typename tRes>
144 struct IterateResultMultiple
146 std::vector<tRes> maAccumulator;
147 size_t mnCount;
149 IterateResultMultiple(size_t nCount) :
150 maAccumulator(0), mnCount(nCount) {}
152 typedef IterateResultMultiple<KahanSum> KahanIterateResultMultiple;
153 typedef IterateResultMultiple<double> DoubleIterateResultMultiple;
156 * Iterator for executing one operation with the matrix data.
158 template<typename tRes>
159 struct IterateResult
161 tRes maAccumulator;
162 size_t mnCount;
164 IterateResult(tRes fAccumulator, size_t nCount)
165 : maAccumulator(fAccumulator), mnCount(nCount) {}
167 typedef IterateResult<KahanSum> KahanIterateResult;
168 typedef IterateResult<double> DoubleIterateResult;
171 /** Checks nC or nR for zero and uses GetElementsMax() whether a matrix of
172 the size of nC*nR could be allocated. A zero size (both nC and nR zero)
173 matrix is allowed for later resize.
175 bool static IsSizeAllocatable( SCSIZE nC, SCSIZE nR );
177 /// Value or boolean.
178 static bool IsValueType( ScMatValType nType )
180 return nType <= ScMatValType::Boolean;
183 /// Boolean.
184 static bool IsBooleanType( ScMatValType nType )
186 return nType == ScMatValType::Boolean;
189 /// String, empty or empty path, but not value nor boolean.
190 static bool IsNonValueType( ScMatValType nType )
192 return bool(nType & ScMatValType::NonvalueMask);
195 /** String, but not empty or empty path or any other type.
196 Not named IsStringType to prevent confusion because previously
197 IsNonValueType was named IsStringType. */
198 static bool IsRealStringType( ScMatValType nType )
200 return (nType & ScMatValType::NonvalueMask) == ScMatValType::String;
203 /// Empty, but not empty path or any other type.
204 static bool IsEmptyType( ScMatValType nType )
206 return (nType & ScMatValType::NonvalueMask) == ScMatValType::Empty;
209 /// Empty path, but not empty or any other type.
210 static bool IsEmptyPathType( ScMatValType nType )
212 return (nType & ScMatValType::NonvalueMask) == ScMatValType::EmptyPath;
215 /** Clone the matrix. */
216 ScMatrix* Clone() const;
218 /** Clone the matrix if mbCloneIfConst (immutable) is set, otherwise
219 return _this_ matrix, to be assigned to a ScMatrixRef. */
220 ScMatrix* CloneIfConst();
222 /** Set the matrix to mutable for CloneIfConst(), only the interpreter
223 should do this and know the consequences. */
224 void SetMutable();
226 /** Set the matrix to immutable for CloneIfConst(), only the interpreter
227 should do this and know the consequences. */
228 void SetImmutable() const;
231 * Resize the matrix to specified new dimension.
233 void Resize(SCSIZE nC, SCSIZE nR);
235 void Resize(SCSIZE nC, SCSIZE nR, double fVal);
237 /** Clone the matrix and extend it to the new size. nNewCols and nNewRows
238 MUST be at least of the size of the original matrix. */
239 ScMatrix* CloneAndExtend(SCSIZE nNewCols, SCSIZE nNewRows) const;
241 void IncRef() const;
242 void DecRef() const;
244 void SetErrorInterpreter( ScInterpreter* p);
245 void GetDimensions( SCSIZE& rC, SCSIZE& rR) const;
246 SCSIZE GetElementCount() const;
247 bool ValidColRow( SCSIZE nC, SCSIZE nR) const;
249 /** For a row vector or column vector, if the position does not point into
250 the vector but is a valid column or row offset it is adapted such that
251 it points to an element to be replicated, same column row 0 for a row
252 vector, same row column 0 for a column vector. Else, for a 2D matrix,
253 returns false.
255 bool ValidColRowReplicated( SCSIZE & rC, SCSIZE & rR ) const;
257 /** Checks if the matrix position is within the matrix. If it is not, for a
258 row vector or column vector the position is adapted such that it points
259 to an element to be replicated, same column row 0 for a row vector,
260 same row column 0 for a column vector. Else, for a 2D matrix and
261 position not within matrix, returns false.
263 bool ValidColRowOrReplicated( SCSIZE & rC, SCSIZE & rR ) const;
265 void PutDouble( double fVal, SCSIZE nC, SCSIZE nR);
266 void PutDouble( double fVal, SCSIZE nIndex);
267 void PutDouble(const double* pArray, size_t nLen, SCSIZE nC, SCSIZE nR);
269 void PutString( const svl::SharedString& rStr, SCSIZE nC, SCSIZE nR) ;
270 void PutString( const svl::SharedString& rStr, SCSIZE nIndex) ;
271 void PutString( const svl::SharedString* pArray, size_t nLen, SCSIZE nC, SCSIZE nR) ;
273 void PutEmpty( SCSIZE nC, SCSIZE nR);
275 /// Jump sal_False without path
276 void PutEmptyPath( SCSIZE nC, SCSIZE nR) ;
277 void PutError( FormulaError nErrorCode, SCSIZE nC, SCSIZE nR ) ;
278 void PutBoolean( bool bVal, SCSIZE nC, SCSIZE nR) ;
280 void FillDouble( double fVal,
281 SCSIZE nC1, SCSIZE nR1, SCSIZE nC2, SCSIZE nR2 ) ;
283 /** Put a column vector of doubles, starting at row nR, must fit into dimensions. */
284 void PutDoubleVector( const ::std::vector< double > & rVec, SCSIZE nC, SCSIZE nR ) ;
286 /** Put a column vector of strings, starting at row nR, must fit into dimensions. */
287 void PutStringVector( const ::std::vector< svl::SharedString > & rVec, SCSIZE nC, SCSIZE nR ) ;
289 /** Put a column vector of empties, starting at row nR, must fit into dimensions. */
290 void PutEmptyVector( SCSIZE nCount, SCSIZE nC, SCSIZE nR ) ;
292 /** Put a column vector of empty results, starting at row nR, must fit into dimensions. */
293 void PutEmptyResultVector( SCSIZE nCount, SCSIZE nC, SCSIZE nR ) ;
295 /** Put a column vector of empty paths, starting at row nR, must fit into dimensions. */
296 void PutEmptyPathVector( SCSIZE nCount, SCSIZE nC, SCSIZE nR ) ;
298 /** May be used before obtaining the double value of an element to avoid
299 passing its NAN around.
300 @ATTENTION: MUST NOT be used if the element is a string!
301 Use GetErrorIfNotString() instead if not sure.
302 @returns 0 if no error, else one of err... constants */
303 FormulaError GetError( SCSIZE nC, SCSIZE nR) const ;
305 /** Use in ScInterpreter to obtain the error code, if any.
306 @returns 0 if no error or string element, else one of err... constants */
307 FormulaError GetErrorIfNotString( SCSIZE nC, SCSIZE nR) const
308 { return IsValue( nC, nR) ? GetError( nC, nR) : FormulaError::NONE; }
310 /// @return 0.0 if empty or empty path, else value or DoubleError.
311 double GetDouble( SCSIZE nC, SCSIZE nR) const ;
312 /// @return 0.0 if empty or empty path, else value or DoubleError.
313 double GetDouble( SCSIZE nIndex) const ;
314 /// @return value or DoubleError or string converted to value.
315 double GetDoubleWithStringConversion( SCSIZE nC, SCSIZE nR ) const ;
317 /// @return empty string if empty or empty path, else string content.
318 svl::SharedString GetString( SCSIZE nC, SCSIZE nR) const ;
319 /// @return empty string if empty or empty path, else string content.
320 svl::SharedString GetString( SCSIZE nIndex) const ;
322 /** @returns the matrix element's string if one is present, otherwise the
323 numerical value formatted as string, or in case of an error the error
324 string is returned; an empty string for empty, a "FALSE" string for
325 empty path. */
326 svl::SharedString GetString( SvNumberFormatter& rFormatter, SCSIZE nC, SCSIZE nR) const ;
328 /// @ATTENTION: If bString the ScMatrixValue->pS may still be NULL to indicate
329 /// an empty string!
330 ScMatrixValue Get( SCSIZE nC, SCSIZE nR) const ;
332 /** @return <TRUE/> if string or any empty, empty cell, empty result, empty
333 path, in fact non-value. */
334 bool IsStringOrEmpty( SCSIZE nIndex ) const ;
336 /** @return <TRUE/> if string or any empty, empty cell, empty result, empty
337 path, in fact non-value. */
338 bool IsStringOrEmpty( SCSIZE nC, SCSIZE nR ) const ;
340 /// @return <TRUE/> if empty or empty cell or empty result, not empty path.
341 bool IsEmpty( SCSIZE nC, SCSIZE nR ) const ;
343 /// @return <TRUE/> if empty cell, not empty or empty result or empty path.
344 bool IsEmptyCell( SCSIZE nC, SCSIZE nR ) const ;
346 /// @return <TRUE/> if empty result, not empty or empty cell or empty path.
347 bool IsEmptyResult( SCSIZE nC, SCSIZE nR ) const ;
349 /// @return <TRUE/> if empty path, not empty or empty cell or empty result.
350 bool IsEmptyPath( SCSIZE nC, SCSIZE nR ) const ;
352 /// @return <TRUE/> if value or boolean.
353 bool IsValue( SCSIZE nIndex ) const ;
355 /// @return <TRUE/> if value or boolean.
356 bool IsValue( SCSIZE nC, SCSIZE nR ) const ;
358 /// @return <TRUE/> if value or boolean or empty or empty path.
359 bool IsValueOrEmpty( SCSIZE nC, SCSIZE nR ) const ;
361 /// @return <TRUE/> if boolean.
362 bool IsBoolean( SCSIZE nC, SCSIZE nR ) const ;
364 /// @return <TRUE/> if entire matrix is numeric, including booleans, with no strings or empties
365 bool IsNumeric() const ;
367 void MatTrans( const ScMatrix& mRes) const ;
368 void MatCopy ( const ScMatrix& mRes) const ;
370 // Convert ScInterpreter::CompareMat values (-1,0,1) to boolean values
371 void CompareEqual() ;
372 void CompareNotEqual() ;
373 void CompareLess() ;
374 void CompareGreater() ;
375 void CompareLessEqual() ;
376 void CompareGreaterEqual() ;
378 double And() const ; // logical AND of all matrix values, or NAN
379 double Or() const ; // logical OR of all matrix values, or NAN
380 double Xor() const ; // logical XOR of all matrix values, or NAN
382 KahanIterateResult Sum( bool bTextAsZero, bool bIgnoreErrorValues = false ) const ;
383 KahanIterateResult SumSquare( bool bTextAsZero, bool bIgnoreErrorValues = false ) const ;
384 DoubleIterateResult Product( bool bTextAsZero, bool bIgnoreErrorValues = false ) const ;
385 size_t Count(bool bCountStrings, bool bCountErrors, bool bIgnoreEmptyStrings = false) const ;
386 size_t MatchDoubleInColumns(double fValue, size_t nCol1, size_t nCol2) const ;
387 size_t MatchStringInColumns(const svl::SharedString& rStr, size_t nCol1, size_t nCol2) const ;
389 double GetMaxValue( bool bTextAsZero, bool bIgnoreErrorValues = false ) const ;
390 double GetMinValue( bool bTextAsZero, bool bIgnoreErrorValues = false ) const ;
391 double GetGcd() const ;
392 double GetLcm() const ;
394 ScMatrixRef CompareMatrix(
395 sc::Compare& rComp, size_t nMatPos, sc::CompareOptions* pOptions ) const ;
398 * Convert the content of matrix into a linear array of numeric values.
399 * String elements are mapped to NaN's and empty elements are mapped to
400 * either NaN or zero values.
402 * @param bEmptyAsZero if true empty elements are mapped to zero values,
403 * otherwise they become NaN values.
405 void GetDoubleArray( std::vector<double>& rArray, bool bEmptyAsZero = true ) const ;
406 void MergeDoubleArrayMultiply( std::vector<double>& rArray ) const ;
408 void NotOp(const ScMatrix& rMat) ;
409 void NegOp(const ScMatrix& rMat) ;
410 void AddOp(double fVal, const ScMatrix& rMat) ;
411 void SubOp(bool bFlag, double fVal, const ScMatrix& rMat) ;
412 void MulOp(double fVal, const ScMatrix& rMat) ;
413 void DivOp(bool bFlag, double fVal, const ScMatrix& rMat) ;
414 void PowOp(bool bFlag, double fVal, const ScMatrix& rMat) ;
416 KahanIterateResultMultiple CollectKahan(const std::vector<sc::op::kOp>& aOp) ;
418 void ExecuteOperation(const std::pair<size_t, size_t>& rStartPos, const std::pair<size_t, size_t>& rEndPos,
419 DoubleOpFunction aDoubleFunc, BoolOpFunction aBoolFunc, StringOpFunction aStringFunc,
420 EmptyOpFunction aEmptyFunc) const ;
422 void MatConcat(SCSIZE nMaxCol, SCSIZE nMaxRow, const ScMatrixRef& xMat1, const ScMatrixRef& xMat2,
423 SvNumberFormatter& rFormatter, svl::SharedStringPool& rPool) ;
425 #if DEBUG_MATRIX
426 void Dump() const;
427 #endif
430 inline void intrusive_ptr_add_ref(const ScMatrix* p)
432 p->IncRef();
435 inline void intrusive_ptr_release(const ScMatrix* p)
437 p->DecRef();
440 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */