1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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 .
21 #include <CoinError.hpp>
23 #include "SolverComponent.hxx"
24 #include <strings.hrc>
26 #include <com/sun/star/frame/XModel.hpp>
27 #include <com/sun/star/table/CellAddress.hpp>
29 #include <rtl/math.hxx>
34 namespace com::sun::star::uno
{ class XComponentContext
; }
36 using namespace com::sun::star
;
40 class CoinMPSolver
: public SolverComponent
46 virtual void SAL_CALL
solve() override
;
47 virtual OUString SAL_CALL
getImplementationName() override
49 return "com.sun.star.comp.Calc.CoinMPSolver";
51 virtual OUString SAL_CALL
getComponentDescription() override
53 return SolverComponent::GetResourceString( RID_COINMP_SOLVER_COMPONENT
);
59 void SAL_CALL
CoinMPSolver::solve()
61 uno::Reference
<frame::XModel
> xModel( mxDoc
, uno::UNO_QUERY_THROW
);
66 xModel
->lockControllers();
68 // collect variables in vector (?)
70 auto aVariableCells
= comphelper::sequenceToContainer
<std::vector
<table::CellAddress
>>(maVariables
);
71 size_t nVariables
= aVariableCells
.size();
74 // collect all dependent cells
76 ScSolverCellHashMap aCellsHash
;
77 aCellsHash
[maObjective
].reserve( nVariables
+ 1 ); // objective function
79 for (const auto& rConstr
: std::as_const(maConstraints
))
81 table::CellAddress aCellAddr
= rConstr
.Left
;
82 aCellsHash
[aCellAddr
].reserve( nVariables
+ 1 ); // constraints: left hand side
84 if ( rConstr
.Right
>>= aCellAddr
)
85 aCellsHash
[aCellAddr
].reserve( nVariables
+ 1 ); // constraints: right hand side
88 // set all variables to zero
90 //! use old values as initial values?
91 for ( const auto& rVarCell
: aVariableCells
)
93 SolverComponent::SetValue( mxDoc
, rVarCell
, 0.0 );
96 // read initial values from all dependent cells
97 for ( auto& rEntry
: aCellsHash
)
99 double fValue
= SolverComponent::GetValue( mxDoc
, rEntry
.first
);
100 rEntry
.second
.push_back( fValue
); // store as first element, as-is
103 // loop through variables
104 for ( const auto& rVarCell
: aVariableCells
)
106 SolverComponent::SetValue( mxDoc
, rVarCell
, 1.0 ); // set to 1 to examine influence
108 // read value change from all dependent cells
109 for ( auto& rEntry
: aCellsHash
)
111 double fChanged
= SolverComponent::GetValue( mxDoc
, rEntry
.first
);
112 double fInitial
= rEntry
.second
.front();
113 rEntry
.second
.push_back( fChanged
- fInitial
);
116 SolverComponent::SetValue( mxDoc
, rVarCell
, 2.0 ); // minimal test for linearity
118 for ( const auto& rEntry
: aCellsHash
)
120 double fInitial
= rEntry
.second
.front();
121 double fCoeff
= rEntry
.second
.back(); // last appended: coefficient for this variable
122 double fTwo
= SolverComponent::GetValue( mxDoc
, rEntry
.first
);
124 bool bLinear
= rtl::math::approxEqual( fTwo
, fInitial
+ 2.0 * fCoeff
) ||
125 rtl::math::approxEqual( fInitial
, fTwo
- 2.0 * fCoeff
);
126 // second comparison is needed in case fTwo is zero
128 maStatus
= SolverComponent::GetResourceString( RID_ERROR_NONLINEAR
);
131 SolverComponent::SetValue( mxDoc
, rVarCell
, 0.0 ); // set back to zero for examining next variable
134 xModel
->unlockControllers();
136 if ( !maStatus
.isEmpty() )
140 // build parameter arrays for CoinMP
143 // set objective function
145 const std::vector
<double>& rObjCoeff
= aCellsHash
[maObjective
];
146 std::unique_ptr
<double[]> pObjectCoeffs(new double[nVariables
]);
147 for (nVar
=0; nVar
<nVariables
; nVar
++)
148 pObjectCoeffs
[nVar
] = rObjCoeff
[nVar
+1];
149 double nObjectConst
= rObjCoeff
[0]; // constant term of objective
153 size_t nRows
= maConstraints
.getLength();
154 size_t nCompSize
= nVariables
* nRows
;
155 std::unique_ptr
<double[]> pCompMatrix(new double[nCompSize
]); // first collect all coefficients, row-wise
156 for (size_t i
=0; i
<nCompSize
; i
++)
157 pCompMatrix
[i
] = 0.0;
159 std::unique_ptr
<double[]> pRHS(new double[nRows
]);
160 std::unique_ptr
<char[]> pRowType(new char[nRows
]);
161 for (size_t i
=0; i
<nRows
; i
++)
167 for (sal_Int32 nConstrPos
= 0; nConstrPos
< maConstraints
.getLength(); ++nConstrPos
)
169 // integer constraints are set later
170 sheet::SolverConstraintOperator eOp
= maConstraints
[nConstrPos
].Operator
;
171 if ( eOp
== sheet::SolverConstraintOperator_LESS_EQUAL
||
172 eOp
== sheet::SolverConstraintOperator_GREATER_EQUAL
||
173 eOp
== sheet::SolverConstraintOperator_EQUAL
)
175 double fDirectValue
= 0.0;
176 bool bRightCell
= false;
177 table::CellAddress aRightAddr
;
178 const uno::Any
& rRightAny
= maConstraints
[nConstrPos
].Right
;
179 if ( rRightAny
>>= aRightAddr
)
180 bRightCell
= true; // cell specified as right-hand side
182 rRightAny
>>= fDirectValue
; // constant value
184 table::CellAddress aLeftAddr
= maConstraints
[nConstrPos
].Left
;
186 const std::vector
<double>& rLeftCoeff
= aCellsHash
[aLeftAddr
];
187 double* pValues
= &pCompMatrix
[nConstrPos
* nVariables
];
188 for (nVar
=0; nVar
<nVariables
; nVar
++)
189 pValues
[nVar
] = rLeftCoeff
[nVar
+1];
191 // if left hand cell has a constant term, put into rhs value
192 double fRightValue
= -rLeftCoeff
[0];
196 const std::vector
<double>& rRightCoeff
= aCellsHash
[aRightAddr
];
197 // modify pValues with rhs coefficients
198 for (nVar
=0; nVar
<nVariables
; nVar
++)
199 pValues
[nVar
] -= rRightCoeff
[nVar
+1];
201 fRightValue
+= rRightCoeff
[0]; // constant term
204 fRightValue
+= fDirectValue
;
208 case sheet::SolverConstraintOperator_LESS_EQUAL
: pRowType
[nConstrPos
] = 'L'; break;
209 case sheet::SolverConstraintOperator_GREATER_EQUAL
: pRowType
[nConstrPos
] = 'G'; break;
210 case sheet::SolverConstraintOperator_EQUAL
: pRowType
[nConstrPos
] = 'E'; break;
212 OSL_ENSURE( false, "unexpected enum type" );
214 pRHS
[nConstrPos
] = fRightValue
;
218 // Find non-zero coefficients, column-wise
220 std::unique_ptr
<int[]> pMatrixBegin(new int[nVariables
+1]);
221 std::unique_ptr
<int[]> pMatrixCount(new int[nVariables
]);
222 std::unique_ptr
<double[]> pMatrix(new double[nCompSize
]); // not always completely used
223 std::unique_ptr
<int[]> pMatrixIndex(new int[nCompSize
]);
225 for (nVar
=0; nVar
<nVariables
; nVar
++)
227 int nBegin
= nMatrixPos
;
228 for (size_t nRow
=0; nRow
<nRows
; nRow
++)
230 double fCoeff
= pCompMatrix
[ nRow
* nVariables
+ nVar
]; // row-wise
233 pMatrix
[nMatrixPos
] = fCoeff
;
234 pMatrixIndex
[nMatrixPos
] = nRow
;
238 pMatrixBegin
[nVar
] = nBegin
;
239 pMatrixCount
[nVar
] = nMatrixPos
- nBegin
;
241 pMatrixBegin
[nVariables
] = nMatrixPos
;
244 // apply settings to all variables
246 std::unique_ptr
<double[]> pLowerBounds(new double[nVariables
]);
247 std::unique_ptr
<double[]> pUpperBounds(new double[nVariables
]);
248 for (nVar
=0; nVar
<nVariables
; nVar
++)
250 pLowerBounds
[nVar
] = mbNonNegative
? 0.0 : -DBL_MAX
;
251 pUpperBounds
[nVar
] = DBL_MAX
;
253 // bounds could possibly be further restricted from single-cell constraints
256 std::unique_ptr
<char[]> pColType(new char[nVariables
]);
257 for (nVar
=0; nVar
<nVariables
; nVar
++)
258 pColType
[nVar
] = mbInteger
? 'I' : 'C';
260 // apply single-var integer constraints
262 for (const auto& rConstr
: std::as_const(maConstraints
))
264 sheet::SolverConstraintOperator eOp
= rConstr
.Operator
;
265 if ( eOp
== sheet::SolverConstraintOperator_INTEGER
||
266 eOp
== sheet::SolverConstraintOperator_BINARY
)
268 table::CellAddress aLeftAddr
= rConstr
.Left
;
269 // find variable index for cell
270 for (nVar
=0; nVar
<nVariables
; nVar
++)
271 if ( AddressEqual( aVariableCells
[nVar
], aLeftAddr
) )
273 if ( eOp
== sheet::SolverConstraintOperator_INTEGER
)
274 pColType
[nVar
] = 'I';
277 pColType
[nVar
] = 'B';
278 pLowerBounds
[nVar
] = 0.0;
279 pUpperBounds
[nVar
] = 1.0;
285 int nObjectSense
= mbMaximize
? SOLV_OBJSENS_MAX
: SOLV_OBJSENS_MIN
;
287 HPROB hProb
= CoinCreateProblem("");
288 int nResult
= CoinLoadProblem( hProb
, nVariables
, nRows
, nMatrixPos
, 0,
289 nObjectSense
, nObjectConst
, pObjectCoeffs
.get(),
290 pLowerBounds
.get(), pUpperBounds
.get(), pRowType
.get(), pRHS
.get(), nullptr,
291 pMatrixBegin
.get(), pMatrixCount
.get(), pMatrixIndex
.get(), pMatrix
.get(),
292 nullptr, nullptr, nullptr );
293 if (nResult
== SOLV_CALL_SUCCESS
)
295 nResult
= CoinLoadInteger( hProb
, pColType
.get() );
299 pMatrixIndex
.reset();
301 pMatrixCount
.reset();
302 pMatrixBegin
.reset();
303 pUpperBounds
.reset();
304 pLowerBounds
.reset();
307 pObjectCoeffs
.reset();
309 CoinSetRealOption( hProb
, COIN_REAL_MAXSECONDS
, mnTimeout
);
310 CoinSetRealOption( hProb
, COIN_REAL_MIPMAXSEC
, mnTimeout
);
312 // TODO: handle (or remove) settings: epsilon, B&B depth
316 if (nResult
== SOLV_CALL_SUCCESS
)
318 nResult
= CoinCheckProblem( hProb
);
321 if (nResult
== SOLV_CALL_SUCCESS
)
325 nResult
= CoinOptimizeProblem( hProb
, 0 );
327 catch (const CoinError
& e
)
329 throw std::runtime_error(e
.message());
333 mbSuccess
= ( nResult
== SOLV_CALL_SUCCESS
);
338 maSolution
.realloc( nVariables
);
339 CoinGetSolutionValues( hProb
, maSolution
.getArray(), nullptr, nullptr, nullptr );
340 mfResultValue
= CoinGetObjectValue( hProb
);
344 int nSolutionStatus
= CoinGetSolutionStatus( hProb
);
345 if ( nSolutionStatus
== 1 )
346 maStatus
= SolverComponent::GetResourceString( RID_ERROR_INFEASIBLE
);
347 else if ( nSolutionStatus
== 2 )
348 maStatus
= SolverComponent::GetResourceString( RID_ERROR_UNBOUNDED
);
349 // TODO: detect timeout condition and report as RID_ERROR_TIMEOUT
350 // (currently reported as infeasible)
353 CoinUnloadProblem( hProb
);
356 extern "C" SAL_DLLPUBLIC_EXPORT
css::uno::XInterface
*
357 com_sun_star_comp_Calc_CoinMPSolver_get_implementation(
358 css::uno::XComponentContext
*,
359 css::uno::Sequence
<css::uno::Any
> const &)
361 return cppu::acquire(new CoinMPSolver());
364 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */