Quandary
Loading...
Searching...
No Matches
timestepper.hpp
Go to the documentation of this file.
1#include <petsc/private/tsimpl.h> /*I "petscts.h" I*/
2#include <petscts.h>
3#include <petscksp.h>
4#include "mastereq.hpp"
5#include <assert.h>
6#include <iostream>
7#include "defs.hpp"
8#include "output.hpp"
9#include "optimtarget.hpp"
10#include <deque>
11#pragma once
12
34 protected:
35 Vec x;
36 Vec xadj;
37 Vec xprimal;
38 std::vector<std::vector<Vec>> trajectory_states;
39 std::vector<Vec> final_states;
40 std::vector<Vec> dpdm_states;
44 PetscInt localsize_u;
45 PetscInt ilow;
46 PetscInt iupp;
47
50 bool eval_dpdm;
57
58 int ntime;
59 double total_time;
60 double dt;
62
63 Vec redgrad;
67
68 public:
69 TimeStepper();
70
79 TimeStepper(const Config& config, MasterEq* mastereq_, Output* output_, int ninit_local);
80
81 virtual ~TimeStepper();
82
86 double getDPDMIntegral(){ return dpdm_integral; };
87 Vec getReducedGradient(){ return redgrad; };
89
90 void setOptimTarget(OptimTarget* optim_target_){ optim_target = optim_target_; };
91
98 Vec getFinalState(size_t iinit_local){ return final_states[iinit_local]; }
99
108 virtual double getMinTimestepSize() const { return dt; }
109
120 virtual Vec solveODE(int initid, int iinit_local, Vec rho_t0);
121
135 virtual void solveAdjointODE(int iinit_local, Vec rho_t0_bar, double Jbar_leakage, double Jbar_weightedcost, double Jbar_dpdm, double Jbar_energy);
136
143 double evalLeakage(const Vec x);
144
152 void evalLeakage_diff(const Vec x, Vec xbar, double Jbar);
153
161 double evalWeightedCost(double time, const Vec x);
162
171 void evalWeightedCost_diff(double time, const Vec x, Vec xbar, double Jbar);
172
181 double evalDpDm(Vec x, Vec xm1, Vec xm2);
182
190 void evalDpDm_diff(int n, Vec xbar, double Jbar);
191
198 double evalEnergy(double time);
199
207 void evalEnergy_diff(double time, double Jbar, Vec redgrad);
208
218 virtual void evolveFWD(const double tstart, const double tstop, Vec x) = 0;
219
232 virtual void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient);
233};
234
241class ExplEuler : public TimeStepper {
242 protected:
243 Vec stage;
244 public:
253 ExplEuler(const Config& config, MasterEq* mastereq_, Output* output_, int ninit_local);
254
255 ~ExplEuler();
256
264 void evolveFWD(const double tstart, const double tstop, Vec x);
265
276 void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient);
277};
278
292class ImplMidpoint : public TimeStepper {
293 protected:
296 KSP ksp;
305 Vec tmp, err;
306
307 public:
316 ImplMidpoint(const Config& config, MasterEq* mastereq_, Output* output_, int ninit_local);
317
319
327 virtual void evolveFWD(const double tstart, const double tstop, Vec x);
328
339 virtual void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient);
340
351 int NeumannSolve(Mat A, Vec b, Vec x, double alpha, bool transpose);
352};
353
362 protected:
363
364 std::vector<double> gamma;
365 std::vector<Vec> x_stage;
366 Vec aux;
367 int order;
368
369 public:
379 CompositionalImplMidpoint(const Config& config, MasterEq* mastereq_, Output* output_, int ninit_local, int order_);
380
382
390 void evolveFWD(const double tstart, const double tstop, Vec x);
391
402 void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient);
403};
404
405
409class PetscTS : public TimeStepper {
410 protected:
411 TS ts;
412 std::vector<TS> ts_pool;
413 std::vector<Vec> q_pool;
415
416 Mat dRHSdp;
419 PetscReal dRHSdp_time;
424
425 public:
434 PetscTS(const Config& config, MasterEq* mastereq_, Output* output_, int ninit_local);
435 ~PetscTS();
436
445 Vec solveODE(int initid, int iinit_local, Vec rho_t0) override;
446
457 void solveAdjointODE(int iinit_local, Vec rho_t0_bar, double Jbar_leakage, double Jbar_weightedcost, double Jbar_dpdm, double Jbar_energy) override;
458
471 static PetscErrorCode RHSMatrixUpdate(TS ts, PetscReal t, Vec x, Mat A, Mat B, void *ptr);
472
483 static PetscErrorCode dRHSdpMatrixUpdate(TS ts, PetscReal t, Vec x, Mat A, void *ptr);
484
495 static PetscErrorCode computedRHSdp(Mat A, Vec x, Vec y);
496
507 static PetscErrorCode IntegralCosts(TS ts, PetscReal t, Vec x, Vec F, void *ctx);
508
520 static PetscErrorCode dIntegralCostdYUpdate(TS ts, PetscReal t, Vec x, Mat A, Mat B, void *ptr);
521
532 static PetscErrorCode dIntegralCostdPUpdate(TS ts, PetscReal t, Vec x, Mat A, void *ptr);
533
534 // Callback function during TSSolve to evaluate trajectory data at each accepted time step
546 static PetscErrorCode monitorTrajectory(TS ts, PetscInt step, PetscReal time, Vec state, void *ctx);
547
548 // THESE ARE NOT USED. Instead, solveODE and solveAdjointODE overwrites the default time-stepping by calling TSSolve.
549 void evolveFWD(const double, const double, Vec) override {};
550 void evolveBWD(const double, const double, const Vec, Vec, Vec, bool) override {};
551
557 double getMinTimestepSize() const override { return min_timestep_size; }
558};
Compositional implicit midpoint rule for higher-order accuracy.
Definition timestepper.hpp:361
int order
Order of the compositional method.
Definition timestepper.hpp:367
void evolveFWD(const double tstart, const double tstop, Vec x)
Evolves state forward using compositional implicit midpoint rule.
Definition timestepper.cpp:806
~CompositionalImplMidpoint()
Definition timestepper.cpp:798
void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient)
Evolves adjoint backward using compositional implicit midpoint rule and accumulates gradient.
Definition timestepper.cpp:826
std::vector< Vec > x_stage
Storage for primal states at intermediate stages.
Definition timestepper.hpp:365
std::vector< double > gamma
Coefficients for compositional step sizes.
Definition timestepper.hpp:364
Vec aux
Auxiliary vector.
Definition timestepper.hpp:366
Configuration class containing all validated settings.
Definition config.hpp:56
Explicit Euler time integration scheme.
Definition timestepper.hpp:241
void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient)
Evolves adjoint backward using explicit Euler method.
Definition timestepper.cpp:528
~ExplEuler()
Definition timestepper.cpp:511
void evolveFWD(const double tstart, const double tstop, Vec x)
Evolves state forward using explicit Euler method.
Definition timestepper.cpp:515
Vec stage
Intermediate vector.
Definition timestepper.hpp:243
Implicit midpoint rule time integration scheme.
Definition timestepper.hpp:292
~ImplMidpoint()
Definition timestepper.cpp:581
LinearSolverType linsolve_type
Linear solver type (GMRES or NEUMANN)
Definition timestepper.hpp:298
virtual void evolveFWD(const double tstart, const double tstop, Vec x)
Evolves state forward using implicit midpoint rule.
Definition timestepper.cpp:606
int linsolve_iterstaken_avg
Average number of linear solver iterations.
Definition timestepper.hpp:302
Vec rhs
Definition timestepper.hpp:295
PC preconditioner
Preconditioner for linear solver.
Definition timestepper.hpp:297
double linsolve_error_avg
Average error of linear solver.
Definition timestepper.hpp:303
int NeumannSolve(Mat A, Vec b, Vec x, double alpha, bool transpose)
Solves (I - alpha*A) * x = b using Neumann iterations.
Definition timestepper.cpp:719
double linsolve_reltol
Relative tolerance for linear solver.
Definition timestepper.hpp:301
Vec tmp
Definition timestepper.hpp:305
int linsolve_maxiter
Maximum number of linear solver iterations.
Definition timestepper.hpp:299
Vec rhs_adj
Right-hand side vectors for forward and adjoint.
Definition timestepper.hpp:295
Vec stage
Definition timestepper.hpp:294
Vec err
Auxiliary vectors for Neumann iterations.
Definition timestepper.hpp:305
virtual void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient)
Evolves adjoint backward using implicit midpoint rule and adds to reduced gradient.
Definition timestepper.cpp:653
int linsolve_counter
Counter for linear solve calls.
Definition timestepper.hpp:304
double linsolve_abstol
Absolute tolerance for linear solver.
Definition timestepper.hpp:300
Vec stage_adj
Intermediate stage vectors for forward and adjoint.
Definition timestepper.hpp:294
KSP ksp
PETSc's linear solver context for GMRES.
Definition timestepper.hpp:296
Implementation of the real-valued right-hand-side (RHS) system matrix of the quantum dynamical equati...
Definition mastereq.hpp:96
Optimization target specification for quantum control.
Definition optimtarget.hpp:20
Output management for quantum control simulations and optimization.
Definition output.hpp:15
Petsc's adaptive timestepper.
Definition timestepper.hpp:409
double min_timestep_size
Smallest timestep size chosen during adaptive timestepping.
Definition timestepper.hpp:423
void solveAdjointODE(int iinit_local, Vec rho_t0_bar, double Jbar_leakage, double Jbar_weightedcost, double Jbar_dpdm, double Jbar_energy) override
Overwrites the default adjoint time-stepping by calling PETSc's TSSolve on the adjoint system.
Definition timestepper.cpp:1015
Mat dRHSdp
MatShell for applying derivative of the RHS to control parameters.
Definition timestepper.hpp:416
TS ts
Backward-compatible alias to ts_pool[0].
Definition timestepper.hpp:411
Mat dIntegralCostdY
Dense matrix for derivative of integral costs wrt state.
Definition timestepper.hpp:417
Vec solveODE(int initid, int iinit_local, Vec rho_t0) override
Overwrites the default time-stepping by calling PETSc's TSSolve.
Definition timestepper.cpp:959
double getMinTimestepSize() const override
Get the smallest timestep size chosen during adaptive timestepping.
Definition timestepper.hpp:557
~PetscTS()
Definition timestepper.cpp:946
std::vector< TS > ts_pool
One PETSc TS per initial condition.
Definition timestepper.hpp:412
static PetscErrorCode computedRHSdp(Mat A, Vec x, Vec y)
PETSc callback to compute the action of the derivative of the RHS with respect to parameters on a vec...
Definition timestepper.cpp:1060
static PetscErrorCode RHSMatrixUpdate(TS ts, PetscReal t, Vec x, Mat A, Mat B, void *ptr)
PETSc callback to update the RHS matrix for the forward system at time t.
Definition timestepper.cpp:1041
Vec redgrad_ts
TS-internal gradient vector with PETSc communicator-compatible layout.
Definition timestepper.hpp:414
Mat dIntegralCostdP
Dense matrix for derivative of integral costs wrt parameters.
Definition timestepper.hpp:418
static PetscErrorCode dRHSdpMatrixUpdate(TS ts, PetscReal t, Vec x, Mat A, void *ptr)
PETSc callback to update the matrix for the derivative of the RHS with respect to control parameters ...
Definition timestepper.cpp:1050
void evolveBWD(const double, const double, const Vec, Vec, Vec, bool) override
Evolves adjoint state backward by one time-step and updates reduced gradient.
Definition timestepper.hpp:550
static PetscErrorCode IntegralCosts(TS ts, PetscReal t, Vec x, Vec F, void *ctx)
PETSc callback to evaluate integral cost functions at time t for the current state x.
Definition timestepper.cpp:1137
double adj_scale_weightedcost
Per-solve scaling for weighted-cost integral adjoint contribution.
Definition timestepper.hpp:421
static PetscErrorCode dIntegralCostdPUpdate(TS ts, PetscReal t, Vec x, Mat A, void *ptr)
PETSc callback to update the matrix for the derivative of integral cost functions with respect to the...
Definition timestepper.cpp:1106
double adj_scale_leakage
Per-solve scaling for leakage integral adjoint contribution.
Definition timestepper.hpp:420
double adj_scale_energy
Per-solve scaling for energy integral adjoint contribution.
Definition timestepper.hpp:422
std::vector< Vec > q_pool
One quadrature state vector per TS/initial condition.
Definition timestepper.hpp:413
static PetscErrorCode monitorTrajectory(TS ts, PetscInt step, PetscReal time, Vec state, void *ctx)
PETSc callback to monitor the trajectory during time-stepping and write data to output files.
Definition timestepper.cpp:1156
void evolveFWD(const double, const double, Vec) override
Evolves state forward by one time-step from tstart to tstop.
Definition timestepper.hpp:549
PetscReal dRHSdp_time
Cached time used by the RHSJacobianP MatShell callbacks.
Definition timestepper.hpp:419
static PetscErrorCode dIntegralCostdYUpdate(TS ts, PetscReal t, Vec x, Mat A, Mat B, void *ptr)
PETSc callback to update the matrix for the derivative of integral cost functions with respect to the...
Definition timestepper.cpp:1070
Base class for time integration schemes to evolve the quantum dynamics.
Definition timestepper.hpp:33
double evalWeightedCost(double time, const Vec x)
Evaluates the weighted cost function term.
Definition timestepper.cpp:330
double weightedcost_integral
Sums the integral over weighted cost function.
Definition timestepper.hpp:55
Vec redgrad
Reduced gradient vector for optimization.
Definition timestepper.hpp:63
int mpirank_petsc
MPI rank in Petsc communicator.
Definition timestepper.hpp:43
void setOptimTarget(OptimTarget *optim_target_)
Definition timestepper.hpp:90
MasterEq * mastereq
Pointer to master equation solver.
Definition timestepper.hpp:66
int ntime
Number of time steps.
Definition timestepper.hpp:58
PetscInt iupp
Last index (+1) of the local sub vector u,v.
Definition timestepper.hpp:46
bool writeTrajectoryDataFiles
Flag to determine whether or not trajectory data will be written to files during forward simulation *...
Definition timestepper.hpp:61
virtual ~TimeStepper()
Definition timestepper.cpp:96
Vec xprimal
Auxiliary vector for backward time stepping.
Definition timestepper.hpp:37
std::vector< Vec > dpdm_states
Storage for states needed for second-order derivative penalty.
Definition timestepper.hpp:40
double getDPDMIntegral()
Definition timestepper.hpp:86
int mpirank_world
MPI rank in global communicator.
Definition timestepper.hpp:41
double evalLeakage(const Vec x)
Evaluates leakage into guard levels.
Definition timestepper.cpp:276
virtual Vec solveODE(int initid, int iinit_local, Vec rho_t0)
Solves the ODE forward in time.
Definition timestepper.cpp:111
double getEnergyIntegral()
Definition timestepper.hpp:85
void evalEnergy_diff(double time, double Jbar, Vec redgrad)
Computes derivative of energy integral.
Definition timestepper.cpp:480
virtual double getMinTimestepSize() const
Get the smallest timestep size used during timestepping.
Definition timestepper.hpp:108
double total_time
Final evolution time.
Definition timestepper.hpp:59
OptimTarget * optim_target
Pointer to optimization target specification.
Definition timestepper.hpp:64
Output * output
Pointer to output handler.
Definition timestepper.hpp:65
double dpdm_integral
Sums second-order derivative variation value.
Definition timestepper.hpp:54
double evalEnergy(double time)
Evaluates energy integral term.
Definition timestepper.cpp:466
bool eval_weightedcost
Flag to compute weighted cost integral term.
Definition timestepper.hpp:51
std::vector< std::vector< Vec > > trajectory_states
Storage for primal states during forward evolution, one trajectory for each local initial condition....
Definition timestepper.hpp:38
virtual void evolveBWD(const double tstart, const double tstop, const Vec x_stop, Vec x_adj, Vec grad, bool compute_gradient)
Evolves adjoint state backward by one time-step and updates reduced gradient.
Definition timestepper.cpp:503
Vec x
Auxiliary vector for forward time stepping.
Definition timestepper.hpp:35
PetscInt ilow
First index of the local sub vector u,v.
Definition timestepper.hpp:45
TimeStepper()
Definition timestepper.cpp:4
bool eval_dpdm
Flag to compute second-order derivative integral term.
Definition timestepper.hpp:50
virtual void evolveFWD(const double tstart, const double tstop, Vec x)=0
Evolves state forward by one time-step from tstart to tstop.
bool eval_leakage
Flag to compute leakage integral term.
Definition timestepper.hpp:48
double evalDpDm(Vec x, Vec xm1, Vec xm2)
Evaluates second-order derivative variation for the state.
Definition timestepper.cpp:364
double energy_integral
Sums the energy term.
Definition timestepper.hpp:53
double weightedcost_width
Width parameter for weighted cost function.
Definition timestepper.hpp:56
Vec getFinalState(size_t iinit_local)
Retrieves the final state for a specific local initial condition.
Definition timestepper.hpp:98
void evalWeightedCost_diff(double time, const Vec x, Vec xbar, double Jbar)
Computes derivative of weighted cost function term.
Definition timestepper.cpp:345
Vec xadj
Auxiliary vector needed for adjoint (backward) time stepping.
Definition timestepper.hpp:36
PetscInt localsize_u
Size of local sub vector u or v in state x=[u,v].
Definition timestepper.hpp:44
virtual void solveAdjointODE(int iinit_local, Vec rho_t0_bar, double Jbar_leakage, double Jbar_weightedcost, double Jbar_dpdm, double Jbar_energy)
Solves the adjoint ODE backward in time.
Definition timestepper.cpp:202
double getLeakageIntegral()
Definition timestepper.hpp:83
void evalLeakage_diff(const Vec x, Vec xbar, double Jbar)
Computes derivative of leakage term.
Definition timestepper.cpp:305
double dt
Time step size.
Definition timestepper.hpp:60
Vec getReducedGradient()
Definition timestepper.hpp:87
int mpisize_petsc
MPI size in Petsc communicator.
Definition timestepper.hpp:42
bool eval_energy
Flag to compute energy integral term.
Definition timestepper.hpp:49
void evalDpDm_diff(int n, Vec xbar, double Jbar)
Computes derivative of second-order derivative variation term.
Definition timestepper.cpp:394
std::vector< Vec > final_states
Storage for final states for each local initial condition. Always filled after solveODE.
Definition timestepper.hpp:39
double getWeightedCostIntegral()
Definition timestepper.hpp:84
void setWriteTrajectoryDataFiles(bool write)
Definition timestepper.hpp:88
double leakage_integral
Sums the integral over leakage.
Definition timestepper.hpp:52
Core type definitions and enumerations for Quandary quantum optimal control.
LinearSolverType
Available types for solving linear systems at each time step.
Definition defs.hpp:113