Debian Codegraph @

mex/sources/heterogeneity/utils/calibration.f08

raw
1 ! Copyright © 2025-2026 Dynare Team
2 !
3 ! This file is part of Dynare.
4 !
5 ! Dynare is free software: you can redistribute it and/or modify it under the terms of the
6 ! GNU General Public License as published by the Free Software Foundation, either version 3 of
7 ! the License, or (at your option) any later version.
8 !
9 ! Dynare is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 ! even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 ! GNU General Public License for more details.
12 !
13 ! You should have received a copy of the GNU General Public License along with Dynare. If not,
14 ! see <https://www.gnu.org/licenses/>.
15 !
16 ! Original author: Normann Rion <[email protected]>
17 !
18 ! Parameter calibration using Broyden quasi-Newton solver
19
20 module calibration
21 use iso_fortran_env, only: real64, int32
22 use iso_c_binding
23 use matlab_mex ! For mexPrintf
24 use calibration_types
25 use aggregate_residuals_tensor, only: agg_resid_tensor
26
27 ! Broyden quasi-Newton solver for parameter calibration
28 use broyden_solver, only: broyden_solve, &
29 BROYDEN_SUCCESS, BROYDEN_MAX_ITER, BROYDEN_SINGULAR_JAC, &
30 BROYDEN_MAX_BACKTRACK, BROYDEN_FCN_ERROR
31
32 implicit none (type, external)
33
34 private
35 public :: calibrate
36
37 contains
38
39 !---------------------------------------------------------------------------
40 ! Calibrate parameters to match targets using Broyden quasi-Newton method
41 !
42 ! This implements the pattern from Python SSJ hank_1a.py lines 223-224:
43 ! (beta, vphi), _ = utils.broyden_solver(res, initial_guess)
44 !
45 ! where res() calls household_trans.ss() which is like our solve_steady_state()
46 !
47 ! Returns: status (0=success, >0=error code)
48 !---------------------------------------------------------------------------
49 subroutine calibrate(input, output)
50 type(calibration_input), intent(inout) :: input
51 type(calibration_output), intent(inout) :: output
52 integer(int32) :: status
53
54 ! Local variables for Broyden solver
55 real(real64), allocatable :: x(:), fvec(:)
56 integer(int32) :: info, nfev
57 integer :: i
58 character(len=256) :: msg
59
60 ! Handle no-calibration case: just compute residuals
61 if (input%dims%n_free_parameters == 0) then
62 status = agg_resid_tensor(input, output)
63 output%converged = (status == 0)
64 output%iterations = 1
65 ! residual_norm computed from ALL aggregate residuals
66 output%residual_norm = maxval(abs(output%agg_output%residuals))
67 if (input%cal_verbosity == 2) &
68 call mexPrintf('No calibration parameters - computing residuals only'//NEW_LINE('A'))
69 return
70 end if
71
72 if (input%cal_verbosity == 2) &
73 call mexPrintf('=== Parameter Calibration (Broyden) ==='//NEW_LINE('A'))
74
75 ! Allocate local solution and residual vectors
76 allocate(x(input%dims%n_free_parameters), fvec(input%dims%n_free_parameters))
77
78 ! Set initial guess (work directly in θ-space, no transformation)
79 do i = 1, input%dims%n_free_parameters
80 x(i) = input%free_parameters_init(i)
81 end do
82
83 ! Print initial guesses and bounds
84 if (input%cal_verbosity == 2) then
85 call mexPrintf(' Initial parameter guesses:'//NEW_LINE('A'))
86 do i = 1, input%dims%n_free_parameters
87 write(msg, '(A,A,A,ES12.5,A,ES12.5,A,ES12.5,A)') &
88 ' ', trim(input%free_parameters_names(i)), ' = ', input%free_parameters_init(i), &
89 ' (lb=', input%free_parameters_bounds(1, i), &
90 ', ub=', input%free_parameters_bounds(2, i), ')'
91 call mexPrintf(trim(msg)//NEW_LINE('A'))
92 end do
93 end if
94
95 ! Solve using Broyden method with bounds (clamping)
96 info = broyden_solve(input%broyden_ws, x, fvec, residual_wrapper, &
97 input%solver_opts%tol, input%solver_opts%max_iter, nfev, &
98 verbosity=input%cal_verbosity, &
99 lower_bounds=input%free_parameters_bounds(1,:), &
100 upper_bounds=input%free_parameters_bounds(2,:))
101
102 ! Check convergence
103 if (info == BROYDEN_SUCCESS) then
104 output%converged = .true.
105 if (input%cal_verbosity == 2) &
106 call mexPrintf('Calibration converged successfully!'//NEW_LINE('A'))
107 else
108 output%converged = .false.
109 if (input%cal_verbosity == 2) then
110 call mexPrintf('Calibration failed to converge'//NEW_LINE('A'))
111 call print_broyden_error(info)
112 end if
113 end if
114
115 ! Extract calibrated parameters (already in θ-space)
116 if (.not. allocated(output%params)) allocate(output%params(input%dims%n_free_parameters))
117 do i = 1, input%dims%n_free_parameters
118 output%params(i) = x(i)
119 end do
120
121 ! Print calibrated parameters
122 if (input%cal_verbosity == 2 .and. output%converged) then
123 call mexPrintf('Calibrated parameters:'//NEW_LINE('A'))
124 do i = 1, input%dims%n_free_parameters
125 write(msg, '(A,A,A,ES12.5)') ' ', trim(input%free_parameters_names(i)), ' = ', output%params(i)
126 call mexPrintf(trim(msg)//NEW_LINE('A'))
127 end do
128 write(msg, '(A,I4,A)') 'Converged in ', nfev, ' function evaluations'
129 call mexPrintf(trim(msg)//NEW_LINE('A'))
130 end if
131
132 ! Extract calibration target equations residuals
133 if (.not. allocated(output%residuals)) allocate(output%residuals(input%dims%n_free_parameters))
134 output%residuals = fvec
135 output%residual_norm = maxval(abs(output%residuals))
136
137 ! Store iteration count
138 output%iterations = nfev
139
140 if (input%cal_verbosity == 2) call mexPrintf('Calibration complete'//NEW_LINE('A'))
141
142 contains
143 ! Residual wrapper (nested procedure to access input/output)
144 subroutine residual_wrapper(nvar, x_params, resid, iflag)
145 integer, intent(in) :: nvar
146 real(real64), intent(in) :: x_params(nvar)
147 real(real64), intent(out) :: resid(nvar)
148 integer, intent(inout) :: iflag
149
150 integer(int32) :: ss_status, k, n_target_eqs
151
152 ! Update parameters with current guess (already in θ-space)
153 do k = 1, nvar
154 input%params(input%free_parameters_ind(k)) = x_params(k)
155 end do
156
157 ! Solve full steady state with these parameters (time iteration + distribution + aggregation)
158 ss_status = agg_resid_tensor(input, output)
159
160 if (ss_status /= 0) then
161 iflag = -1 ! Signal error to Broyden solver
162 return
163 end if
164
165 ! Populate resid with calibration target equations residuals
166 n_target_eqs = size(input%target_equations, 1)
167 do k = 1, n_target_eqs
168 resid(k) = output%agg_output%residuals(input%target_equations(k))
169 end do
170
171 ! Print iteration info if verbosity == 2 (use parameter values from params)
172 if (input%cal_verbosity == 2) &
173 call print_calibration_iteration(nvar, input%params, input%free_parameters_ind, &
174 input%free_parameters_names)
175
176 end subroutine residual_wrapper
177
178 subroutine print_broyden_error(code)
179 integer(int32), intent(in) :: code
180 select case (code)
181 case (BROYDEN_MAX_ITER)
182 call mexPrintf(' Broyden: Maximum iterations exceeded'//NEW_LINE('A'))
183 case (BROYDEN_SINGULAR_JAC)
184 call mexPrintf(' Broyden: Singular Jacobian encountered'//NEW_LINE('A'))
185 case (BROYDEN_MAX_BACKTRACK)
186 call mexPrintf(' Broyden: Too many backtracks'//NEW_LINE('A'))
187 case (BROYDEN_FCN_ERROR)
188 call mexPrintf(' Broyden: Function evaluation error'//NEW_LINE('A'))
189 case default
190 call mexPrintf(' Broyden: Unknown error code'//NEW_LINE('A'))
191 end select
192 end subroutine print_broyden_error
193
194 subroutine print_calibration_iteration(n, params, free_parameters_ind, param_names)
195 integer, intent(in) :: n
196 real(real64), intent(in) :: params(:) ! Full params array
197 integer(int32), intent(in) :: free_parameters_ind(:) ! Indices of free parameters in params
198 character(len=*), intent(in) :: param_names(:)
199 character(len=256) :: msg
200 integer :: i
201
202 do i = 1, n
203 write(msg, '(A,A,A,ES12.5)') ' ', trim(param_names(i)), ' = ', &
204 params(free_parameters_ind(i))
205 call mexPrintf(trim(msg)//NEW_LINE('A'))
206 end do
207 end subroutine print_calibration_iteration
208
209 end subroutine calibrate
210
211 end module calibration