Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjoint new try #512

Draft
wants to merge 46 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
cdb173f
eclproblem option to avoid restart spesific deserialize
hnil Nov 15, 2017
231fe5e
Tried to fix serialization of simulator by adding time step to it
hnil Nov 16, 2017
36bfda8
disable storageCache
hnil Nov 16, 2017
0d2f024
use storage cach on
hnil Feb 1, 2018
4fa97f7
tried to add timefocus
hnil Feb 2, 2018
19bd8e8
changes to make focus time work in particular for storage term, need …
hnil Feb 6, 2018
d2adee2
added numAdjoint in ecl def, and fixed storage term to work also with…
hnil Feb 14, 2018
fb5c54f
fixed time focus for solvent and polymer
hnil Feb 14, 2018
a6cafd5
fix after timefocus added
hnil Feb 14, 2018
f3167a7
introduced directory for ebos serialization, NB probably break all ew…
hnil Feb 18, 2018
73d32fb
added extra terminal output for deserialization
hnil Feb 19, 2018
7cc9c6b
changed order of primary variables
hnil May 25, 2018
10f7fca
Update file after failed rebase.
atgeirr Aug 21, 2018
89b6ec7
Adding focusTimeIdx parameter to energy module where necessary.
atgeirr Aug 23, 2018
e070472
Fix fallout from rebasing.
atgeirr Aug 27, 2018
0f36a76
tried to correct with respect to coment in pull request 371
hnil Nov 5, 2018
86a2ec1
corrected camelcase
hnil Nov 30, 2018
2c81e37
Enabled reseting of Storage cache: it is critical that all is deleted…
hnil Dec 2, 2018
89295d9
added possibility to avoid removing auxModule. Fis may be wrong if to…
hnil Dec 7, 2018
a0ed73e
merged master and rebase_adjoint
hnil Dec 7, 2018
af756b7
code comples after merge
hnil Dec 7, 2018
a73c2b9
working version
hnil Dec 11, 2018
8db4520
added spesialization need for getting matrix market work with Ewoms::…
hnil Dec 12, 2018
24eeb49
introduced hack to avoid calling any source terms in the evaluating w…
hnil Dec 12, 2018
bd839d2
Merge remote-tracking branch 'upstream/master' into merge_master_reba…
hnil Dec 17, 2018
3d625d3
fixed compilatino of pure ewoms after introdusing focusTimeIdx
hnil Dec 17, 2018
b0356c4
changed use fo time from simulator
hnil Jan 4, 2019
c7e3300
Merge remote-tracking branch 'upstream/master' into merge_master_reba…
hnil Jan 4, 2019
c5c4d67
changed black oil indices back for less small changes in tests
hnil Jan 4, 2019
9bc9271
moved back index change to get test ok
hnil Jan 7, 2019
0ea41e0
Merge remote-tracking branch 'upstream/master' into merge_master_reba…
hnil Jan 7, 2019
2701579
Merge branch 'merge_master_rebase_adjoint' of https://github.com/hnil…
atgeirr Jan 14, 2019
ac9ad80
Use default argument to avoid changing API.
atgeirr Jan 14, 2019
9199388
Enable compiling also for grids without the name() method.
atgeirr Jan 14, 2019
f6a1687
Silence shadowing warning.
atgeirr Jan 15, 2019
5ad25b8
Add default argument to preserve existing API.
atgeirr Jan 15, 2019
1ad1bd9
Use Toolbox::value() instead of clearDerivatives().
atgeirr Jan 16, 2019
31f80b8
Silence unused variable warning.
atgeirr Jan 16, 2019
1348d05
Add focusTimeIdx to all ...IntensiveQuantities classes.
atgeirr Jan 16, 2019
c9bad00
Make timestep-past-episode logic optional in Simulator class.
atgeirr Jan 17, 2019
b0b5670
Output is written for the end time of steps.
atgeirr Jan 18, 2019
00b288c
Add defaulted atEndOfStep arguments to serialization.
atgeirr Jan 21, 2019
a6218ce
Merge pull request #1 from atgeirr/update-adjoint-alternative
hnil Jan 21, 2019
0fb0cce
Merge remote-tracking branch 'origin/merge_master_rebase_adjoint' int…
hnil May 26, 2019
6c46be5
added comment on hack to get adjoint to work
hnil May 31, 2019
0508c95
Merge branch 'master' of https://github.com/OPM/ewoms into adjoint_ne…
hnil Aug 14, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions ewoms/common/parametersystem.hh
Original file line number Diff line number Diff line change
Expand Up @@ -961,7 +961,6 @@ public:
check_(Dune::className<ParamType>(), propTagName, paramName);
#endif

typedef typename GET_PROP(TypeTag, ParameterMetaData) ParamsMeta;
if (errorIfNotRegistered) {
if (ParamsMeta::registrationOpen())
throw std::runtime_error("Parameters can only checked after _all_ of them have "
Expand Down Expand Up @@ -1038,7 +1037,6 @@ private:
check_(Dune::className<ParamType>(), propTagName, paramName);
#endif

typedef typename GET_PROP(TypeTag, ParameterMetaData) ParamsMeta;
if (errorIfNotRegistered) {
if (ParamsMeta::registrationOpen())
throw std::runtime_error("Parameters can only retieved after _all_ of them have "
Expand Down
26 changes: 24 additions & 2 deletions ewoms/common/simulator.hh
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ NEW_PROP_TAG(EndTime);
NEW_PROP_TAG(RestartTime);
NEW_PROP_TAG(InitialTimeStepSize);
NEW_PROP_TAG(PredeterminedTimeStepsFile);
NEW_PROP_TAG(SimulatorManageTimeStep);

END_PROPERTIES

Expand Down Expand Up @@ -107,6 +108,8 @@ class Simulator
typedef typename GET_PROP_TYPE(TypeTag, Model) Model;
typedef typename GET_PROP_TYPE(TypeTag, Problem) Problem;

enum { simulatorManageTimeStep = GET_PROP_VALUE(TypeTag, SimulatorManageTimeStep) };

public:
// do not allow to copy simulators around
Simulator(const Simulator& ) = delete;
Expand Down Expand Up @@ -866,11 +869,11 @@ public:
* name and uses the extension <tt>.ers</tt>. (Ewoms ReStart
* file.) See Ewoms::Restart for details.
*/
void serialize()
void serialize(const bool atEndOfStep = true)
{
typedef Ewoms::Restart Restarter;
Restarter res;
res.serializeBegin(*this);
res.serializeBegin(*this, atEndOfStep);
if (gridView().comm().rank() == 0)
std::cout << "Serialize to file '" << res.fileName() << "'"
<< ", next time step size: " << timeStepSize()
Expand All @@ -882,6 +885,23 @@ public:
res.serializeEnd();
}

void deserializeAll(Scalar t,bool only_reservoir)
{
typedef Ewoms::Restart Restarter;
Restarter res;
res.deserializeBegin(*this, t);
if (gridView().comm().rank() == 0)
std::cout << "Deserialize file '" << res.fileName() << "'"
<< ", next time step size: " << timeStepSize()
<< "\n" << std::flush;
this->deserialize(res);
if( not(only_reservoir) ){
problem_->deserialize(res, false);
}
model_->deserialize(res);

res.deserializeEnd();
}
/*!
* \brief Write the time manager's state to a restart file.
*
Expand All @@ -899,6 +919,7 @@ public:
<< episodeLength_ << " "
<< startTime_ << " "
<< time_ << " "
<< timeStepSize_ << " "
<< timeStepIdx_ << " ";
restarter.serializeSectionEnd();
}
Expand All @@ -920,6 +941,7 @@ public:
>> episodeLength_
>> startTime_
>> time_
>> timeStepSize_
>> timeStepIdx_;
restarter.deserializeSectionEnd();
}
Expand Down
10 changes: 10 additions & 0 deletions ewoms/disc/common/fvbasediscretization.hh
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ SET_BOOL_PROP(FvBaseDiscretization, UseVolumetricResidual, true);

//! eWoms is mainly targeted at research, so experimental features are enabled by
//! default.
SET_BOOL_PROP(FvBaseDiscretization, SimulatorManageTimeStep, true);
SET_BOOL_PROP(FvBaseDiscretization, EnableExperiments, true);

END_PROPERTIES
Expand Down Expand Up @@ -759,6 +760,15 @@ public:
bool enableStorageCache() const
{ return enableStorageCache_; }

/*!
* \brief Set the value of enable storage cache
*
* Be aware that calling the *CachedStorage() methods if the storage cache is
* disabled will crash the program.
*/
void setEnableStorageCache(bool enableStorageCache)
{ enableStorageCache_= enableStorageCache; }

/*!
* \brief Retrieve an entry of the cache for the storage term.
*
Expand Down
25 changes: 23 additions & 2 deletions ewoms/disc/common/fvbaseelementcontext.hh
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,10 @@ public:
{
// remember the simulator object
simulatorPtr_ = &simulator;
enableStorageCache_ = EWOMS_GET_PARAM(TypeTag, bool, EnableStorageCache);
enableStorageCache_ = simulator.model().enableStorageCache();//EWOMS_GET_PARAM(TypeTag, bool, EnableStorageCache);
stashedDofIdx_ = -1;
focusDofIdx_ = -1;
focusTimeIdx_ = 0;
}

static void *operator new(size_t size)
Expand Down Expand Up @@ -260,6 +261,17 @@ public:
void setFocusDofIndex(unsigned dofIdx)
{ focusDofIdx_ = dofIdx; }

/*!
* \brief Sets the time index on which the simulator is currently "focused" on
*
* I.e., in the case of automatic differentiation, all derivatives are with regard to
* the primary variables of that time index. Only "primary" DOFs can be
* focused on.
*/

void setFocusTimeIndex(unsigned timeIdx)
{ focusTimeIdx_ = timeIdx; }

/*!
* \brief Returns the degree of freedom on which the simulator is currently "focused" on
*
Expand All @@ -268,6 +280,14 @@ public:
unsigned focusDofIndex() const
{ return focusDofIdx_; }

/*!
* \brief Returns the time index on which the simulator is currently "focused" on
*
* \copydetails setFocusDof()
*/
unsigned focusTimeIndex() const
{ return focusTimeIdx_; }

/*!
* \brief Return a reference to the simulator.
*/
Expand Down Expand Up @@ -581,7 +601,7 @@ protected:
#endif

dofVars_[dofIdx].priVars[timeIdx] = priVars;
dofVars_[dofIdx].intensiveQuantities[timeIdx].update(/*context=*/asImp_(), dofIdx, timeIdx);
dofVars_[dofIdx].intensiveQuantities[timeIdx].update(/*context=*/asImp_(), dofIdx, timeIdx, focusTimeIdx_);
}

IntensiveQuantities intensiveQuantitiesStashed_;
Expand All @@ -599,6 +619,7 @@ protected:

int stashedDofIdx_;
int focusDofIdx_;
int focusTimeIdx_;
bool enableStorageCache_;
};

Expand Down
3 changes: 2 additions & 1 deletion ewoms/disc/common/fvbaseintensivequantities.hh
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ public:
*/
void update(const ElementContext& elemCtx,
unsigned dofIdx,
unsigned timeIdx)
unsigned timeIdx,
unsigned focusTimeIdx OPM_UNUSED)
{ extrusionFactor_ = elemCtx.problem().extrusionFactor(elemCtx, dofIdx, timeIdx); }

/*!
Expand Down
32 changes: 20 additions & 12 deletions ewoms/disc/common/fvbaselinearizer.hh
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ public:
{
simulatorPtr_ = &simulator;
eraseMatrix();
auto it = elementCtx_.begin();
const auto& endIt = elementCtx_.end();
for (; it != endIt; ++it){
delete *it;
}
elementCtx_.resize(0);
}

/*!
Expand All @@ -158,14 +164,15 @@ public:
}

/*!
* \brief Linearize the full system of non-linear equations.
* \brief Linearize the full system of non-linear equations about focusTimeIdx
* defualt is 0 i.e. current time normally time to be found.
*
* This means the spatial domain plus all auxiliary equations.
*/
void linearize()
void linearize(unsigned focusTimeIdx = 0)
{
linearizeDomain();
linearizeAuxiliaryEquations();
linearizeDomain(focusTimeIdx);
linearizeAuxiliaryEquations(focusTimeIdx);
}

/*!
Expand All @@ -178,7 +185,7 @@ public:
* The current state of affairs (esp. the previous and the current solutions) is
* represented by the model object.
*/
void linearizeDomain()
void linearizeDomain(unsigned focustimeIndex)
{
// we defer the initialization of the Jacobian matrix until here because the
// auxiliary modules usually assume the problem, model and grid to be fully
Expand All @@ -188,7 +195,7 @@ public:

int succeeded;
try {
linearize_();
linearize_(focustimeIndex);
succeeded = 1;
}
#if ! DUNE_VERSION_NEWER(DUNE_COMMON, 2,5)
Expand Down Expand Up @@ -227,7 +234,7 @@ public:
* \brief Linearize the part of the non-linear system of equations that is associated
* with the spatial domain.
*/
void linearizeAuxiliaryEquations()
void linearizeAuxiliaryEquations(unsigned focusTimeIdx OPM_UNUSED = 0)
{
// flush possible local caches into matrix structure
jacobian_->commit();
Expand All @@ -237,7 +244,7 @@ public:
for (unsigned auxModIdx = 0; auxModIdx < model.numAuxiliaryModules(); ++auxModIdx) {
bool succeeded = true;
try {
model.auxiliaryModule(auxModIdx)->linearize(*jacobian_, residual_);
model.auxiliaryModule(auxModIdx)->linearize(*jacobian_, residual_);//, focusTimeIdx);
}
catch (const std::exception& e) {
succeeded = false;
Expand Down Expand Up @@ -330,6 +337,7 @@ private:
elementCtx_[threadId] = new ElementContext(simulator_());
}


// Construct the BCRS matrix for the Jacobian of the residual function
void createMatrix_()
{
Expand Down Expand Up @@ -425,7 +433,7 @@ private:
}

// linearize the whole system
void linearize_()
void linearize_(unsigned focustimeindex)
{
resetSystem_();

Expand Down Expand Up @@ -472,8 +480,7 @@ private:
const Element& elem = *elemIt;
if (!linearizeNonLocalElements && elem.partitionType() != Dune::InteriorEntity)
continue;

linearizeElement_(elem);
linearizeElement_(elem, focustimeindex);
}
}
// If an exception occurs in the parallel block, it won't escape the
Expand Down Expand Up @@ -503,14 +510,15 @@ private:
}

// linearize an element in the interior of the process' grid partition
void linearizeElement_(const Element& elem)
void linearizeElement_(const Element& elem, unsigned focustimeindex)
{
unsigned threadId = ThreadManager::threadId();

ElementContext *elementCtx = elementCtx_[threadId];
auto& localLinearizer = model_().localLinearizer(threadId);

// the actual work of linearization is done by the local linearizer class
elementCtx->setFocusTimeIndex(focustimeindex);
localLinearizer.linearize(*elementCtx, elem);

// update the right hand side and the Jacobian matrix
Expand Down
53 changes: 36 additions & 17 deletions ewoms/disc/common/fvbaselocalresidual.hh
Original file line number Diff line number Diff line change
Expand Up @@ -163,16 +163,17 @@ public:
assert(residual.size() == elemCtx.numDof(/*timeIdx=*/0));

residual = 0.0;

if(elemCtx.focusTimeIndex()==0){//NB: This is only valid if fluxeterm sis purely implicite, This was nesseary to not get false derivatives form wells in adjiont.
// evaluate the flux terms
asImp_().evalFluxes(residual, elemCtx, /*timeIdx=*/0);

asImp_().evalFluxes(residual, elemCtx, /*timeIdx=*/0);
}
// evaluate the storage and the source terms
asImp_().evalVolumeTerms_(residual, elemCtx);

asImp_().evalVolumeTerms_(residual, elemCtx);
if(elemCtx.focusTimeIndex()==0){//NB: This is only valid if fluxeterm sis purely implicite, This was nesseary to not get false derivatives form wells in adjiont.
// evaluate the boundary conditions
asImp_().evalBoundary_(residual, elemCtx, /*timeIdx=*/0);

asImp_().evalBoundary_(residual, elemCtx, /*timeIdx=*/0);
}
if (useVolumetricResidual) {
// make the residual volume specific (i.e., make it incorrect mass per cubic
// meter instead of total mass)
Expand Down Expand Up @@ -492,6 +493,7 @@ protected:
{
EvalVector tmp;
EqVector tmp2;
EvalVector tmp2Der;// this is added to support calculation of storage term derivative focusTime!=0 for need for adjoint: always used if cachedStororage term si false
RateVector sourceRate;

tmp = 0.0;
Expand Down Expand Up @@ -572,24 +574,41 @@ protected:
else {
// if the mass storage at the beginning of the time step is not cached,
// we re-calculate it from scratch.
tmp2 = 0.0;
asImp_().computeStorage(tmp2, elemCtx, dofIdx, /*timeIdx=*/1);
Opm::Valgrind::CheckDefined(tmp2);
// if storage cache not enables we always use derivatives
tmp2Der = 0.0;
asImp_().computeStorage(tmp2Der, elemCtx, dofIdx, /*timeIdx=*/1);
Opm::Valgrind::CheckDefined(tmp2Der);
}

// Use the implicit Euler time discretization
for (unsigned eqIdx = 0; eqIdx < numEq; ++eqIdx) {
tmp[eqIdx] -= tmp2[eqIdx];
tmp[eqIdx] *= scvVolume / elemCtx.simulator().timeStepSize();

residual[dofIdx][eqIdx] += tmp[eqIdx];
if( !elemCtx.enableStorageCache() or elemCtx.focusTimeIndex()>0){
// Use the implicit Euler time discretization
for (unsigned eqIdx = 0; eqIdx < numEq; ++eqIdx) {
if (elemCtx.focusTimeIndex() == 0) {
tmp2Der[eqIdx] = Toolbox::value(tmp2Der[eqIdx]);
} else {
tmp[eqIdx] = Toolbox::value(tmp[eqIdx]);
}
tmp[eqIdx] -= tmp2Der[eqIdx];
tmp[eqIdx] *= scvVolume / elemCtx.simulator().timeStepSize();
residual[dofIdx][eqIdx] += tmp[eqIdx];
}
}else{
for (unsigned eqIdx = 0; eqIdx < numEq; ++eqIdx) {
// cached storage should only be used in forward mode
assert(elemCtx.focusTimeIndex()==0);
tmp[eqIdx] -= tmp2[eqIdx];
tmp[eqIdx] *= scvVolume / elemCtx.simulator().timeStepSize();
residual[dofIdx][eqIdx] += tmp[eqIdx];
}
}

Opm::Valgrind::CheckDefined(residual[dofIdx]);

// deal with the source term
asImp_().computeSource(sourceRate, elemCtx, dofIdx, /*timeIdx=*/0);

//assumes sourceterm is independent of prevois state
if(elemCtx.focusTimeIndex()==0){
asImp_().computeSource(sourceRate, elemCtx, dofIdx, /*timeIdx=*/0);
}
// if the model uses extensive quantities in its storage term, and we use
// automatic differention and current DOF is also not the one we currently
// focus on, the storage term does not need any derivatives!
Expand Down
Loading