Line data Source code
1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /*
3 : * This file is part of the LibreOffice project.
4 : *
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/.
8 : *
9 : * This file incorporates work covered by the following license notice:
10 : *
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 .
18 : */
19 :
20 : #include <CoinMP.h>
21 : #include <CoinError.hpp>
22 :
23 : #include "SolverComponent.hxx"
24 : #include "solver.hrc"
25 :
26 : #include <com/sun/star/frame/XModel.hpp>
27 : #include <com/sun/star/table/CellAddress.hpp>
28 : #include <com/sun/star/uno/XComponentContext.hpp>
29 :
30 : #include <rtl/math.hxx>
31 : #include <vector>
32 :
33 : using namespace com::sun::star;
34 :
35 : class CoinMPSolver : public SolverComponent
36 : {
37 : public:
38 2 : CoinMPSolver() {}
39 4 : virtual ~CoinMPSolver() {}
40 :
41 : private:
42 : virtual void SAL_CALL solve() throw(css::uno::RuntimeException, std::exception) SAL_OVERRIDE;
43 0 : virtual OUString SAL_CALL getImplementationName()
44 : throw(css::uno::RuntimeException, std::exception) SAL_OVERRIDE
45 : {
46 0 : return OUString("com.sun.star.comp.Calc.CoinMPSolver");
47 : }
48 0 : virtual OUString SAL_CALL getComponentDescription()
49 : throw (uno::RuntimeException, std::exception) SAL_OVERRIDE
50 : {
51 0 : return SolverComponent::GetResourceString( RID_COINMP_SOLVER_COMPONENT );
52 : }
53 : };
54 :
55 0 : void SAL_CALL CoinMPSolver::solve() throw(uno::RuntimeException, std::exception)
56 : {
57 0 : uno::Reference<frame::XModel> xModel( mxDoc, uno::UNO_QUERY );
58 0 : if ( !xModel.is() )
59 0 : throw uno::RuntimeException();
60 :
61 0 : maStatus = "";
62 0 : mbSuccess = false;
63 :
64 0 : xModel->lockControllers();
65 :
66 : // collect variables in vector (?)
67 :
68 0 : std::vector<table::CellAddress> aVariableCells;
69 0 : for (sal_Int32 nPos=0; nPos<maVariables.getLength(); nPos++)
70 0 : aVariableCells.push_back( maVariables[nPos] );
71 0 : size_t nVariables = aVariableCells.size();
72 0 : size_t nVar = 0;
73 :
74 : // collect all dependent cells
75 :
76 0 : ScSolverCellHashMap aCellsHash;
77 0 : aCellsHash[maObjective].reserve( nVariables + 1 ); // objective function
78 :
79 0 : for (sal_Int32 nConstrPos = 0; nConstrPos < maConstraints.getLength(); ++nConstrPos)
80 : {
81 0 : table::CellAddress aCellAddr = maConstraints[nConstrPos].Left;
82 0 : aCellsHash[aCellAddr].reserve( nVariables + 1 ); // constraints: left hand side
83 :
84 0 : if ( maConstraints[nConstrPos].Right >>= aCellAddr )
85 0 : aCellsHash[aCellAddr].reserve( nVariables + 1 ); // constraints: right hand side
86 : }
87 :
88 : // set all variables to zero
89 : //! store old values?
90 : //! use old values as initial values?
91 0 : std::vector<table::CellAddress>::const_iterator aVarIter;
92 0 : for ( aVarIter = aVariableCells.begin(); aVarIter != aVariableCells.end(); ++aVarIter )
93 : {
94 0 : SolverComponent::SetValue( mxDoc, *aVarIter, 0.0 );
95 : }
96 :
97 : // read initial values from all dependent cells
98 0 : ScSolverCellHashMap::iterator aCellsIter;
99 0 : for ( aCellsIter = aCellsHash.begin(); aCellsIter != aCellsHash.end(); ++aCellsIter )
100 : {
101 0 : double fValue = SolverComponent::GetValue( mxDoc, aCellsIter->first );
102 0 : aCellsIter->second.push_back( fValue ); // store as first element, as-is
103 : }
104 :
105 : // loop through variables
106 0 : for ( aVarIter = aVariableCells.begin(); aVarIter != aVariableCells.end(); ++aVarIter )
107 : {
108 0 : SolverComponent::SetValue( mxDoc, *aVarIter, 1.0 ); // set to 1 to examine influence
109 :
110 : // read value change from all dependent cells
111 0 : for ( aCellsIter = aCellsHash.begin(); aCellsIter != aCellsHash.end(); ++aCellsIter )
112 : {
113 0 : double fChanged = SolverComponent::GetValue( mxDoc, aCellsIter->first );
114 0 : double fInitial = aCellsIter->second.front();
115 0 : aCellsIter->second.push_back( fChanged - fInitial );
116 : }
117 :
118 0 : SolverComponent::SetValue( mxDoc, *aVarIter, 2.0 ); // minimal test for linearity
119 :
120 0 : for ( aCellsIter = aCellsHash.begin(); aCellsIter != aCellsHash.end(); ++aCellsIter )
121 : {
122 0 : double fInitial = aCellsIter->second.front();
123 0 : double fCoeff = aCellsIter->second.back(); // last appended: coefficient for this variable
124 0 : double fTwo = SolverComponent::GetValue( mxDoc, aCellsIter->first );
125 :
126 0 : bool bLinear = rtl::math::approxEqual( fTwo, fInitial + 2.0 * fCoeff ) ||
127 0 : rtl::math::approxEqual( fInitial, fTwo - 2.0 * fCoeff );
128 : // second comparison is needed in case fTwo is zero
129 0 : if ( !bLinear )
130 0 : maStatus = SolverComponent::GetResourceString( RID_ERROR_NONLINEAR );
131 : }
132 :
133 0 : SolverComponent::SetValue( mxDoc, *aVarIter, 0.0 ); // set back to zero for examining next variable
134 : }
135 :
136 0 : xModel->unlockControllers();
137 :
138 0 : if ( !maStatus.isEmpty() )
139 0 : return;
140 :
141 : //
142 : // build parameter arrays for CoinMP
143 : //
144 :
145 : // set objective function
146 :
147 0 : const std::vector<double>& rObjCoeff = aCellsHash[maObjective];
148 0 : double* pObjectCoeffs = new double[nVariables];
149 0 : for (nVar=0; nVar<nVariables; nVar++)
150 0 : pObjectCoeffs[nVar] = rObjCoeff[nVar+1];
151 0 : double nObjectConst = rObjCoeff[0]; // constant term of objective
152 :
153 : // add rows
154 :
155 0 : size_t nRows = maConstraints.getLength();
156 0 : size_t nCompSize = nVariables * nRows;
157 0 : double* pCompMatrix = new double[nCompSize]; // first collect all coefficients, row-wise
158 0 : for (size_t i=0; i<nCompSize; i++)
159 0 : pCompMatrix[i] = 0.0;
160 :
161 0 : double* pRHS = new double[nRows];
162 0 : char* pRowType = new char[nRows];
163 0 : for (size_t i=0; i<nRows; i++)
164 : {
165 0 : pRHS[i] = 0.0;
166 0 : pRowType[i] = 'N';
167 : }
168 :
169 0 : for (sal_Int32 nConstrPos = 0; nConstrPos < maConstraints.getLength(); ++nConstrPos)
170 : {
171 : // integer constraints are set later
172 0 : sheet::SolverConstraintOperator eOp = maConstraints[nConstrPos].Operator;
173 0 : if ( eOp == sheet::SolverConstraintOperator_LESS_EQUAL ||
174 0 : eOp == sheet::SolverConstraintOperator_GREATER_EQUAL ||
175 : eOp == sheet::SolverConstraintOperator_EQUAL )
176 : {
177 0 : double fDirectValue = 0.0;
178 0 : bool bRightCell = false;
179 0 : table::CellAddress aRightAddr;
180 0 : const uno::Any& rRightAny = maConstraints[nConstrPos].Right;
181 0 : if ( rRightAny >>= aRightAddr )
182 0 : bRightCell = true; // cell specified as right-hand side
183 : else
184 0 : rRightAny >>= fDirectValue; // constant value
185 :
186 0 : table::CellAddress aLeftAddr = maConstraints[nConstrPos].Left;
187 :
188 0 : const std::vector<double>& rLeftCoeff = aCellsHash[aLeftAddr];
189 0 : double* pValues = &pCompMatrix[nConstrPos * nVariables];
190 0 : for (nVar=0; nVar<nVariables; nVar++)
191 0 : pValues[nVar] = rLeftCoeff[nVar+1];
192 :
193 : // if left hand cell has a constant term, put into rhs value
194 0 : double fRightValue = -rLeftCoeff[0];
195 :
196 0 : if ( bRightCell )
197 : {
198 0 : const std::vector<double>& rRightCoeff = aCellsHash[aRightAddr];
199 : // modify pValues with rhs coefficients
200 0 : for (nVar=0; nVar<nVariables; nVar++)
201 0 : pValues[nVar] -= rRightCoeff[nVar+1];
202 :
203 0 : fRightValue += rRightCoeff[0]; // constant term
204 : }
205 : else
206 0 : fRightValue += fDirectValue;
207 :
208 0 : switch ( eOp )
209 : {
210 0 : case sheet::SolverConstraintOperator_LESS_EQUAL: pRowType[nConstrPos] = 'L'; break;
211 0 : case sheet::SolverConstraintOperator_GREATER_EQUAL: pRowType[nConstrPos] = 'G'; break;
212 0 : case sheet::SolverConstraintOperator_EQUAL: pRowType[nConstrPos] = 'E'; break;
213 : default:
214 : OSL_ENSURE( false, "unexpected enum type" );
215 : }
216 0 : pRHS[nConstrPos] = fRightValue;
217 : }
218 : }
219 :
220 : // Find non-zero coefficients, column-wise
221 :
222 0 : int* pMatrixBegin = new int[nVariables+1];
223 0 : int* pMatrixCount = new int[nVariables];
224 0 : double* pMatrix = new double[nCompSize]; // not always completely used
225 0 : int* pMatrixIndex = new int[nCompSize];
226 0 : int nMatrixPos = 0;
227 0 : for (nVar=0; nVar<nVariables; nVar++)
228 : {
229 0 : int nBegin = nMatrixPos;
230 0 : for (size_t nRow=0; nRow<nRows; nRow++)
231 : {
232 0 : double fCoeff = pCompMatrix[ nRow * nVariables + nVar ]; // row-wise
233 0 : if ( fCoeff != 0.0 )
234 : {
235 0 : pMatrix[nMatrixPos] = fCoeff;
236 0 : pMatrixIndex[nMatrixPos] = nRow;
237 0 : ++nMatrixPos;
238 : }
239 : }
240 0 : pMatrixBegin[nVar] = nBegin;
241 0 : pMatrixCount[nVar] = nMatrixPos - nBegin;
242 : }
243 0 : pMatrixBegin[nVariables] = nMatrixPos;
244 0 : delete[] pCompMatrix;
245 0 : pCompMatrix = NULL;
246 :
247 : // apply settings to all variables
248 :
249 0 : double* pLowerBounds = new double[nVariables];
250 0 : double* pUpperBounds = new double[nVariables];
251 0 : for (nVar=0; nVar<nVariables; nVar++)
252 : {
253 0 : pLowerBounds[nVar] = mbNonNegative ? 0.0 : -DBL_MAX;
254 0 : pUpperBounds[nVar] = DBL_MAX;
255 :
256 : // bounds could possibly be further restricted from single-cell constraints
257 : }
258 :
259 0 : char* pColType = new char[nVariables];
260 0 : for (nVar=0; nVar<nVariables; nVar++)
261 0 : pColType[nVar] = mbInteger ? 'I' : 'C';
262 :
263 : // apply single-var integer constraints
264 :
265 0 : for (sal_Int32 nConstrPos = 0; nConstrPos < maConstraints.getLength(); ++nConstrPos)
266 : {
267 0 : sheet::SolverConstraintOperator eOp = maConstraints[nConstrPos].Operator;
268 0 : if ( eOp == sheet::SolverConstraintOperator_INTEGER ||
269 : eOp == sheet::SolverConstraintOperator_BINARY )
270 : {
271 0 : table::CellAddress aLeftAddr = maConstraints[nConstrPos].Left;
272 : // find variable index for cell
273 0 : for (nVar=0; nVar<nVariables; nVar++)
274 0 : if ( AddressEqual( aVariableCells[nVar], aLeftAddr ) )
275 : {
276 0 : if ( eOp == sheet::SolverConstraintOperator_INTEGER )
277 0 : pColType[nVar] = 'I';
278 : else
279 : {
280 0 : pColType[nVar] = 'B';
281 0 : pLowerBounds[nVar] = 0.0;
282 0 : pUpperBounds[nVar] = 1.0;
283 : }
284 : }
285 : }
286 : }
287 :
288 0 : int nObjectSense = mbMaximize ? SOLV_OBJSENS_MAX : SOLV_OBJSENS_MIN;
289 :
290 0 : HPROB hProb = CoinCreateProblem("");
291 : int nResult = CoinLoadProblem( hProb, nVariables, nRows, nMatrixPos, 0,
292 : nObjectSense, nObjectConst, pObjectCoeffs,
293 : pLowerBounds, pUpperBounds, pRowType, pRHS, NULL,
294 : pMatrixBegin, pMatrixCount, pMatrixIndex, pMatrix,
295 0 : NULL, NULL, NULL );
296 0 : nResult = CoinLoadInteger( hProb, pColType );
297 :
298 0 : delete[] pColType;
299 0 : delete[] pMatrixIndex;
300 0 : delete[] pMatrix;
301 0 : delete[] pMatrixCount;
302 0 : delete[] pMatrixBegin;
303 0 : delete[] pUpperBounds;
304 0 : delete[] pLowerBounds;
305 0 : delete[] pRowType;
306 0 : delete[] pRHS;
307 0 : delete[] pObjectCoeffs;
308 :
309 0 : CoinSetRealOption( hProb, COIN_REAL_MAXSECONDS, mnTimeout );
310 0 : CoinSetRealOption( hProb, COIN_REAL_MIPMAXSEC, mnTimeout );
311 :
312 : // TODO: handle (or remove) settings: epsilon, B&B depth
313 :
314 : // solve model
315 :
316 0 : nResult = CoinCheckProblem( hProb );
317 :
318 : try
319 : {
320 0 : nResult = CoinOptimizeProblem( hProb, 0 );
321 : }
322 0 : catch (const CoinError& e)
323 : {
324 0 : throw std::runtime_error(e.message());
325 : }
326 :
327 0 : mbSuccess = ( nResult == SOLV_CALL_SUCCESS );
328 0 : if ( mbSuccess )
329 : {
330 : // get solution
331 :
332 0 : maSolution.realloc( nVariables );
333 0 : CoinGetSolutionValues( hProb, maSolution.getArray(), NULL, NULL, NULL );
334 0 : mfResultValue = CoinGetObjectValue( hProb );
335 : }
336 : else
337 : {
338 0 : int nSolutionStatus = CoinGetSolutionStatus( hProb );
339 0 : if ( nSolutionStatus == 1 )
340 0 : maStatus = SolverComponent::GetResourceString( RID_ERROR_INFEASIBLE );
341 0 : else if ( nSolutionStatus == 2 )
342 0 : maStatus = SolverComponent::GetResourceString( RID_ERROR_UNBOUNDED );
343 : // TODO: detect timeout condition and report as RID_ERROR_TIMEOUT
344 : // (currently reported as infeasible)
345 : }
346 :
347 0 : CoinUnloadProblem( hProb );
348 : }
349 :
350 : extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface * SAL_CALL
351 2 : com_sun_star_comp_Calc_CoinMPSolver_get_implementation(
352 : css::uno::XComponentContext *,
353 : css::uno::Sequence<css::uno::Any> const &)
354 : {
355 2 : return cppu::acquire(new CoinMPSolver());
356 6 : }
357 :
358 : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|