SQP.C
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | www.openfoam.com
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8  Copyright (C) 2007-2019 PCOpt/NTUA
9  Copyright (C) 2013-2019 FOSS GP
10  Copyright (C) 2019 OpenCFD Ltd.
11 -------------------------------------------------------------------------------
12 License
13  This file is part of OpenFOAM.
14 
15  OpenFOAM is free software: you can redistribute it and/or modify it
16  under the terms of the GNU General Public License as published by
17  the Free Software Foundation, either version 3 of the License, or
18  (at your option) any later version.
19 
20  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
21  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
22  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
23  for more details.
24 
25  You should have received a copy of the GNU General Public License
26  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
27 
28 \*---------------------------------------------------------------------------*/
29 
30 #include "SQP.H"
31 #include "IOmanip.H"
33 
34 // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
35 
36 namespace Foam
37 {
38  defineTypeNameAndDebug(SQP, 1);
40  (
41  updateMethod,
42  SQP,
43  dictionary
44  );
46  (
47  constrainedOptimisationMethod,
48  SQP,
49  dictionary
50  );
51 }
52 
53 
54 // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
55 
56 void Foam::SQP::allocateMatrices()
57 {
58  // Set active design variables, if necessary
59  if (activeDesignVars_.empty())
60  {
63  {
64  activeDesignVars_[dvI] = dvI;
65  }
66  }
67 
68  // Set previous Hessian to be a diagonal matrix
69  SquareMatrix<scalar> temp(activeDesignVars_.size(), I);
70 
71  // Allocate correct size and content to Hessian matrices
72  // Has a max. capability of approximately 34000 variables.
73  HessianOld_ = temp;
74  Hessian_ = temp;
75 
76  // Set size of Lagrange multipliers
77  lamdas_.setSize(constraintDerivatives_.size());
78  lamdas_ = Zero;
79 
80  // Set corerction size
81  correction_.setSize(objectiveDerivatives_.size());
82  correction_ = Zero;
83 }
84 
85 
86 void Foam::SQP::updateHessian()
87 {
88  // Vectors needed to construct the (inverse) Hessian matrix
89  scalarField y(activeDesignVars_.size(), Zero);
90  scalarField s(activeDesignVars_.size(), Zero);
91  scalarField LagrangianDerivativesOld = objectiveDerivativesOld_;
92  forAll(constraintDerivatives_, cI)
93  {
94  LagrangianDerivatives_ -= lamdas_[cI] * constraintDerivatives_[cI];
95  LagrangianDerivativesOld -= lamdas_[cI] * constraintDerivativesOld_[cI];
96  }
97  y.map(LagrangianDerivatives_ - LagrangianDerivativesOld, activeDesignVars_);
98  s.map(correctionOld_, activeDesignVars_);
99 
100  scalar ys = globalSum(s*y);
101  if (counter_ == 1 && scaleFirstHessian_)
102  {
103  if (ys > scalar(0))
104  {
105  scalar scaleFactor = ys/globalSum(y*y);
106  Info<< "Scaling Hessian with factor " << scaleFactor << endl;
107  forAll(activeDesignVars_, varI)
108  {
109  HessianOld_[varI][varI] /= scaleFactor;
110  }
111  }
112  else
113  {
115  << " y*s is negative. Skipping the scaling of the first Hessian"
116  << endl;
117  }
118  }
119  scalar sBs = globalSum(leftMult(s, HessianOld_)*s);
120 
121  // Check curvature condition
122  scalar theta(1);
123  if (ys < dumpingThreshold_*sBs)
124  {
126  << " y*s is below threshold. Using damped form" << endl;
127  theta = (1 - dumpingThreshold_)*sBs/(sBs - ys);
128  }
129  scalarField r(theta*y + (scalar(1) - theta)*rightMult(HessianOld_, s));
130  DebugInfo
131  << "Unmodified Hessian curvature index " << ys << endl;
132  DebugInfo
133  << "Modified Hessian curvature index " << globalSum(r*s) << endl;
134 
135  // Update the Hessian
136  Hessian_ =
137  HessianOld_
138  - outerProd(rightMult(HessianOld_, s), leftMult(s/sBs, HessianOld_))
139  + outerProd(r, r/globalSum(s*r));
140 }
141 
142 
143 void Foam::SQP::computeLagrangeMultipliersAndCorrect()
144 {
145  SquareMatrix<scalar> HessianInv = inv(Hessian_); //also denoted below as W
146  if (debug > 1)
147  {
148  Info<< "Hessian " << Hessian_ << endl;
149  Info<< "HessianInv " << HessianInv << endl;
150  label n = Hessian_.n();
151  SquareMatrix<scalar> test(n, Zero);
152  for (label k = 0; k < n; k++)
153  {
154  for (label l = 0; l < n; l++)
155  {
156  scalar elem(Zero);
157  for (label i = 0; i < n; i++)
158  {
159  elem += Hessian_[k][i] * HessianInv[i][l];
160  }
161  test[k][l]=elem;
162  }
163  }
164  Info<< "Validation " << test << endl;
165  }
166 
167  // Compute new Lagrange multipliers
168  label nc = constraintDerivatives_.size();
169  scalarField activeDerivs(activeDesignVars_.size(), Zero);
170 
171  // activeDerivs.map(objectiveDerivatives_, activeDesignVars_);
172  activeDerivs.map(LagrangianDerivatives_, activeDesignVars_);
173  scalarField WgradL = rightMult(HessianInv, activeDerivs);
174 
175  scalarField lamdaRHS(nc, Zero);
176  forAll(lamdaRHS, cI)
177  {
178  scalarField activeConsDerivs(activeDesignVars_.size(), Zero);
179  activeConsDerivs.map(constraintDerivatives_[cI], activeDesignVars_);
180  lamdaRHS[cI] = globalSum(activeConsDerivs * WgradL) - cValues_[cI];
181  if (debug > 1)
182  {
183  Info<< "lamdaRHS total|deriv part|constraint part "
184  << lamdaRHS[cI] << " " << globalSum(activeConsDerivs * WgradL)
185  << " " << cValues_[cI] << endl;
186  }
187  }
188 
189  // lhs for the lamda system
190  SquareMatrix<scalar> AWA(nc, Zero);
191  PtrList<scalarField> WA(nc);
192  for (label j = 0; j < nc; j++)
193  {
194  scalarField gradcJ(activeDesignVars_.size(), Zero);
195  gradcJ.map(constraintDerivatives_[j], activeDesignVars_);
196  WA.set(j, new scalarField(rightMult(HessianInv, gradcJ)));
197  for (label i = 0; i < nc; i++)
198  {
199  scalarField gradcI(activeDesignVars_.size(), Zero);
200  gradcI.map(constraintDerivatives_[i], activeDesignVars_);
201  AWA[i][j] = globalSum(gradcI * WA[j]);
202  }
203  }
204  SquareMatrix<scalar> invAWA = inv(AWA);
205  scalarField deltaLamda = rightMult(invAWA, lamdaRHS);
206  if (debug > 1)
207  {
208  Info<< "AWA " << AWA << endl;
209  Info<< "AWAInv " << invAWA << endl;
210  Info<< "lamda update " << deltaLamda << endl;
211  }
212  lamdas_ += deltaLamda;
213 
214  // Compute design variables correction
215  scalarField activeCorrection(-WgradL);
216  forAll(WA, cI)
217  {
218  activeCorrection += WA[cI]*deltaLamda[cI];
219  }
220  activeCorrection *= etaHessian_;
221  // Transfer correction to the global list
222  correction_ = Zero;
223  forAll(activeDesignVars_, varI)
224  {
225  correction_[activeDesignVars_[varI]] = activeCorrection[varI];
226  }
227  if (counter_ == 0)
228  {
229  correction_ *= eta_;
230  }
231 }
232 
233 
234 void Foam::SQP::storeOldFields()
235 {
236  objectiveDerivativesOld_ = objectiveDerivatives_;
237  if (constraintDerivativesOld_.empty())
238  {
239  constraintDerivativesOld_.setSize(constraintDerivatives_.size());
240  }
241  forAll(constraintDerivativesOld_, cI)
242  {
243  constraintDerivativesOld_[cI] = constraintDerivatives_[cI];
244  }
245  correctionOld_ = correction_;
246  HessianOld_ = Hessian_;
247 }
248 
249 
250 void Foam::SQP::readFromDict()
251 {
252  if (optMethodIODict_.headerOk())
253  {
254  optMethodIODict_.readEntry("Hessian", Hessian_);
255  optMethodIODict_.readEntry("HessianOld", HessianOld_);
256  optMethodIODict_.readEntry
257  (
258  "objectiveDerivativesOld",
259  objectiveDerivativesOld_
260  );
261  optMethodIODict_.readEntry
262  (
263  "constraintDerivativesOld",
264  constraintDerivativesOld_
265  );
266  optMethodIODict_.readEntry("correctionOld", correctionOld_);
267  optMethodIODict_.readEntry("lamdas", lamdas_);
268  optMethodIODict_.readEntry("counter", counter_);
269  optMethodIODict_.readEntry("eta", eta_);
270 
271  correction_ = scalarField(correctionOld_.size(), Zero);
272  }
273 }
274 
275 
276 // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
277 
278 Foam::SQP::SQP(const fvMesh& mesh, const dictionary& dict)
279 :
281 
282  etaHessian_
283  (
284  coeffsDict().lookupOrDefault<scalar>("etaHessian", 1)
285  ),
286  activeDesignVars_(0),
287  scaleFirstHessian_
288  (
289  coeffsDict().lookupOrDefault<bool>("scaleFirstHessian", false)
290  ),
291  dumpingThreshold_
292  (
293  coeffsDict().lookupOrDefault<scalar>("dumpingThreshold", 0.2)
294  ),
295  LagrangianDerivatives_(0),
296  Hessian_(), // construct null matrix since we dont know the dimension yet
297  HessianOld_(),
298  objectiveDerivativesOld_(0),
299  constraintDerivativesOld_(0),
300  correctionOld_(0),
301  lamdas_(0),
302  counter_(0),
303  objFunctionFolder_
304  (
305  mesh_.time().globalPath()/"optimisation"/"objective"/
306  mesh_.time().timeName()
307  ),
308  meritFunctionFile_(nullptr),
309  mu_(Zero),
310  delta_
311  (
312  coeffsDict().lookupOrDefault<scalar>("delta", 0.1)
313  )
314 {
315  if
316  (
317  !coeffsDict().readIfPresent("activeDesignVariables", activeDesignVars_)
318  )
319  {
320  // If not, all available design variables will be used. Number is not
321  // know at the moment
322  Info<< "\t Did not find explicit definition of active design "
323  << "variables. Treating all available ones as active " << endl;
324  }
325 
326  // Create folder to merit function
327  if (Pstream::master())
328  {
330  }
331 
332  // Read old hessian, correction and derivatives, if present
333  readFromDict();
334 }
335 
336 
337 // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
338 
340 {
341  // Allocate correct sizes in first update
342  if (counter_ == 0)
343  {
344  allocateMatrices();
345  }
346 
347  // The first iteration uses a unitary Hessian. No need to update
348  LagrangianDerivatives_ = objectiveDerivatives_;
349  if (counter_ != 0)
350  {
351  updateHessian();
352  }
353 
354  // Update lamdas and desing vars
355  computeLagrangeMultipliersAndCorrect();
356 
357  // Store fields for the next iteration and write them to file
358  storeOldFields();
359 
360  counter_++;
361 }
362 
363 
365 {
366  // If condition is not met, update mu value
367  if (mu_ < max(mag(lamdas_)) + delta_)
368  {
369  mu_ = max(mag(lamdas_)) + 2*delta_;
370  if (debug > 1)
371  {
372  Info<< "Updated mu value to " << mu_ << endl;
373  }
374  }
375  scalar L = objectiveValue_ + mu_*sum(mag(cValues_));
376 
377  return L;
378 }
379 
380 
382 {
383  scalar deriv =
384  globalSum(objectiveDerivatives_*correction_)
385  - mu_*sum(mag(cValues_));
386 
387  return deriv;
388 }
389 
390 
391 void Foam::SQP::updateOldCorrection(const scalarField& oldCorrection)
392 {
393  updateMethod::updateOldCorrection(oldCorrection);
394  correctionOld_ = oldCorrection;
395 }
396 
397 
399 {
400  // Write updateMethod dictionary
401  optMethodIODict_.add<SquareMatrix<scalar>>("Hessian", Hessian_, true);
402  optMethodIODict_.add<SquareMatrix<scalar>>("HessianOld", HessianOld_, true);
403  optMethodIODict_.
404  add<scalarField>
405  (
406  "objectiveDerivativesOld", objectiveDerivativesOld_, true
407  );
408  optMethodIODict_.
409  add<List<scalarField>>
410  (
411  "constraintDerivativesOld", constraintDerivativesOld_, true
412  );
413  optMethodIODict_.add<scalarField>("correctionOld", correctionOld_, true);
414  optMethodIODict_.add<scalarField>("lamdas", lamdas_, true);
415  optMethodIODict_.add<label>("counter", counter_, true);
416 
418 
419  // Write merit function
420  scalar constraintPart = sum(mag(cValues_));
421  scalar merit = objectiveValue_ + mu_*constraintPart;
422  if (Pstream::master())
423  {
424  unsigned int width = IOstream::defaultPrecision() + 6;
425  unsigned int constraintsSize = lamdas_.size();
426  constraintsSize = constraintsSize*(width + 1) + 2;
427 
428  // Open file and write header
429  if (meritFunctionFile_.empty())
430  {
431  meritFunctionFile_.reset
432  (
433  new OFstream(objFunctionFolder_/word("meritFunction"))
434  );
435 
436  meritFunctionFile_()
437  << setw(1) << "#" << " "
438  << setw(width) << "merit" << " "
439  << setw(width) << "J" << " "
440  << setw(constraintsSize) << "lamdas" << " "
441  << setw(constraintsSize) << "constraints" << " "
442  << setw(width) << "mu" << " "
443  << setw(width) << "constraintContr" << endl;
444 
445  }
446 
447  meritFunctionFile_()
448  << setw(1) << mesh_.time().value() -1 << " "
449  << setw(width) << merit << " "
450  << setw(width) << objectiveValue_ << " "
451  << setw(1) << "(";
452 
453  forAll(lamdas_, cI)
454  {
455  meritFunctionFile_()
456  << setw(width) << lamdas_[cI] << setw(1) << " ";
457  }
458  meritFunctionFile_() << setw(3) << ")(";
459  forAll(cValues_, cI)
460  {
461  meritFunctionFile_()
462  << setw(width) << cValues_[cI] << setw(1) << " ";
463  }
464  meritFunctionFile_() << setw(2) << ") ";
465  meritFunctionFile_() << setw(width) << mu_ << " ";
466  meritFunctionFile_() << setw(width) << constraintPart << endl;
467  }
468 }
469 
470 
471 // ************************************************************************* //
Foam::expressions::patchExpr::debug
int debug
Static debugging option.
Foam::addToRunTimeSelectionTable
addToRunTimeSelectionTable(decompositionMethod, kahipDecomp, dictionary)
Foam::scalarField
Field< scalar > scalarField
Specialisation of Field<T> for scalar.
Definition: primitiveFieldsFwd.H:52
L
const vector L(dict.get< vector >("L"))
Foam::SQP::Hessian_
SquareMatrix< scalar > Hessian_
Definition: SQP.H:79
SQP.H
Foam::word
A class for handling words, derived from Foam::string.
Definition: word.H:62
s
gmvFile<< "tracers "<< particles.size()<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().x()<< " ";}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().y()<< " ";}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().z()<< " ";}gmvFile<< nl;forAll(lagrangianScalarNames, i){ word name=lagrangianScalarNames[i];IOField< scalar > s(IOobject(name, runTime.timeName(), cloud::prefix, mesh, IOobject::MUST_READ, IOobject::NO_WRITE))
Definition: gmvOutputSpray.H:25
Foam::Zero
static constexpr const zero Zero
Global zero.
Definition: zero.H:128
Foam::SQP::computeMeritFunction
virtual scalar computeMeritFunction()
Definition: SQP.C:364
Foam::updateMethod::constraintDerivatives_
PtrList< scalarField > constraintDerivatives_
Derivatives of the constraints.
Definition: updateMethod.H:71
Foam::SQP::computeCorrection
void computeCorrection()
Compute design variables correction.
Definition: SQP.C:339
Foam::endl
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition: Ostream.H:337
Foam::SQP::HessianOld_
SquareMatrix< scalar > HessianOld_
The previous Hessian inverse.
Definition: SQP.H:82
forAll
#define forAll(list, i)
Loop across all elements in list.
Definition: stdFoam.H:290
Foam::Field::map
void map(const UList< Type > &mapF, const labelUList &mapAddressing)
1 to 1 map from the given field
Definition: Field.C:263
Foam::constrainedOptimisationMethod
Abstract base class for optimisation methods supporting constraints. Does not add functionality to up...
Definition: constrainedOptimisationMethod.H:55
n
label n
Definition: TABSMDCalcMethod2.H:31
Foam::label
intWM_LABEL_SIZE_t label
A label is an int32_t or int64_t as specified by the pre-processor macro WM_LABEL_SIZE.
Definition: label.H:62
Foam::updateMethod::updateOldCorrection
virtual void updateOldCorrection(const scalarField &oldCorrection)
Definition: updateMethod.C:390
Foam::Field< scalar >
Foam::inv
dimensionedSphericalTensor inv(const dimensionedSphericalTensor &dt)
Definition: dimensionedSphericalTensor.C:73
Foam::Info
messageStream Info
Information stream (uses stdout - output is on the master only)
Foam::SQP::updateOldCorrection
virtual void updateOldCorrection(const scalarField &oldCorrection)
Definition: SQP.C:391
IOmanip.H
Istream and Ostream manipulators taking arguments.
Foam::SQP::objFunctionFolder_
fileName objFunctionFolder_
Name of the objective folder.
Definition: SQP.H:100
Foam::SQP::activeDesignVars_
labelList activeDesignVars_
Map to active design variables.
Definition: SQP.H:66
Foam::max
label max(const labelHashSet &set, label maxValue=labelMin)
Find the max value in labelHashSet, optionally limited by second argument.
Definition: hashSets.C:47
timeName
word timeName
Definition: getTimeIndex.H:3
dict
dictionary dict
Definition: searchingEngine.H:14
Foam::dictionary
A list of keyword definitions, which are a keyword followed by a number of values (eg,...
Definition: dictionary.H:121
Foam::updateMethod::correction_
scalarField correction_
Design variables correction.
Definition: updateMethod.H:80
mesh
dynamicFvMesh & mesh
Definition: createDynamicFvMesh.H:6
addToRunTimeSelectionTable.H
Macros for easy insertion into run-time selection tables.
Foam::SQP::lamdas_
scalarField lamdas_
Lagrange multipliers.
Definition: SQP.H:94
Foam::fvMesh
Mesh data needed to do the Finite Volume discretisation.
Definition: fvMesh.H:84
Foam
Namespace for OpenFOAM.
Definition: atmBoundaryLayer.C:33
Foam::setw
Omanip< int > setw(const int i)
Definition: IOmanip.H:199
Foam::SQP::write
virtual void write()
Write usefull quantities to files.
Definition: SQP.C:398
Foam::OFstream
Output to file stream, using an OSstream.
Definition: OFstream.H:99
Foam::UPstream::master
static bool master(const label communicator=0)
Am I the master process.
Definition: UPstream.H:438
Foam::updateMethod::coeffsDict
dictionary coeffsDict()
Return optional dictionary with parameters specific to each method.
Definition: updateMethod.C:254
Foam::SquareMatrix< scalar >
Foam::updateMethod::write
virtual void write()
Write usefull quantities to files.
Definition: updateMethod.C:398
DebugInfo
#define DebugInfo
Report an information message using Foam::Info.
Definition: messageStream.H:350
Foam::IOstream::defaultPrecision
static unsigned int defaultPrecision()
Return the default precision.
Definition: IOstream.H:325
Foam::mag
dimensioned< typename typeOfMag< Type >::type > mag(const dimensioned< Type > &dt)
k
label k
Boltzmann constant.
Definition: LISASMDCalcMethod2.H:41
Foam::sum
dimensioned< Type > sum(const DimensionedField< Type, GeoMesh > &df)
Definition: DimensionedFieldFunctions.C:327
bool
bool
Definition: EEqn.H:20
Foam::List::setSize
void setSize(const label newSize)
Alias for resize(const label)
Definition: ListI.H:146
Foam::mkDir
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
Definition: MSwindows.C:507
Foam::defineTypeNameAndDebug
defineTypeNameAndDebug(combustionModel, 0)
WarningInFunction
#define WarningInFunction
Report a warning using Foam::Warning.
Definition: messageStream.H:294
Foam::SQP::meritFunctionDirectionalDerivative
virtual scalar meritFunctionDirectionalDerivative()
Definition: SQP.C:381
Foam::I
static const Identity< scalar > I
Definition: Identity.H:95
Foam::updateMethod::objectiveDerivatives_
scalarField objectiveDerivatives_
Derivatives of the objective functions.
Definition: updateMethod.H:68
y
scalar y
Definition: LISASMDCalcMethod1.H:14