Debian Codegraph @

mex/sources/heterogeneity/utils/aggregate_residuals_tensor.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 ! Main entry point for heterogeneous-agent steady-state computation
19
20 module aggregate_residuals_tensor
21 use iso_fortran_env, only: real64, int32
22 use iso_c_binding, only: C_DOUBLE, C_INT
23 use calibration_types
24 use matlab_mex
25 use time_iteration_tensor
26 use blas
27
28 implicit none (type, external)
29
30 private
31 public :: agg_resid_tensor
32
33 contains
34
35 !---------------------------------------------------------------------------
36 ! Main solver function for tensor product grids (Cases 1 & 2)
37 ! Simpler than solve_steady_state since grid is already constructed
38 ! Returns: status (0=success, >0=error code)
39 !---------------------------------------------------------------------------
40 function agg_resid_tensor(input, output) result(status)
41 type(calibration_input), intent(inout) :: input
42 type(calibration_output), intent(inout) :: output
43 integer(int32) :: status
44
45 ! Initialize
46 status = 0
47
48 ! Phase 1: Time iteration on fixed tensor grid
49 status = solve_time_iteration_tensor( &
50 input%dims, input%ti_options, input%ti_verbosity, input%state_var, &
51 input%tg_config, &
52 input%old_pol, input%old_pol_array, input%new_pol, input%weighted_old_pol, &
53 input%gc_cache_next, input%gc_cache_om, input%gc_cache_fi, &
54 input%gp_ws, input%mex, &
55 output%ti_output)
56
57 ! Phase 2: Forward iteration for distribution
58 status = solve_distribution_tensor(input, output%dist_output)
59
60 ! Phase 3: Compute aggregated heterogeneous variables
61 call compute_agg_het_variables(input, output)
62
63 ! Phase 4: Compute aggregate residuals for calibration target equations
64 call compute_aggregate_residuals(input, output)
65
66 ! Only print "Calibration iteration complete" when there's actual calibration
67 if (input%dims%n_free_parameters > 0 .and. input%cal_verbosity == 2) &
68 call mexPrintf(' Calibration iteration complete'//NEW_LINE('A'))
69
70 end function agg_resid_tensor
71
72 function solve_distribution_tensor(input, dist_output) result(status)
73 type(calibration_input), intent(inout) :: input
74 type(distribution_output), intent(inout) :: dist_output
75 integer(int32) :: status
76
77 integer(int32) :: N_om, N_a, N_e, j, j_a, iter, m, kf, t, Kcorn, n_states
78 real(real64) :: diff_norm
79 real(real64), pointer, contiguous :: d_mat(:,:), d_mat_next(:,:)
80 character(len=256) :: msg
81 real(real64), pointer, contiguous :: inc(:), acc(:), r_up(:,:), r_down(:,:), beta_0(:)
82 integer(int32), pointer, contiguous :: z(:), linear_idx(:), stride_shocks(:)
83 logical, pointer, contiguous :: is_hard_one(:,:), is_hard_zero(:,:), sk(:)
84
85 ! Initialize status
86 status = 0
87 dist_output%converged = .false.
88
89 ! Useful size variables
90 N_om = input%dims%N_om
91 N_a = input%dims%N_a_om
92 N_e = input%dims%N_e
93 n_states = input%dims%n_states
94 Kcorn = input%gc_cache_fi%Kcorn
95
96 ! Create a few pointers to make the code more readable
97 inc(1:N_om) => input%gc_cache_fi%inc
98 acc(1:N_om) => input%gc_cache_fi%acc
99 r_up(1:N_om, 1:n_states) => input%gc_cache_fi%r_up
100 r_down(1:N_om, 1:n_states) => input%gc_cache_fi%r_down
101 beta_0(1:N_om) => input%gc_cache_fi%beta_0
102 z(1:N_om) => input%gc_cache_fi%z
103 linear_idx(1:N_om) => input%gc_cache_fi%linear_idx
104 stride_shocks(1:n_states) => input%gc_cache_fi%stride_shocks
105 is_hard_one(1:N_om, 1:n_states) => input%gc_cache_fi%is_hard_one
106 is_hard_zero(1:N_om, 1:n_states) => input%gc_cache_fi%is_hard_zero
107 sk(1:n_states) => input%gc_cache_fi%sk
108
109 ! Initialize the distribution to a uniform one
110 d_mat(1:N_e, 1:N_a) => dist_output%distribution
111 do j_a = 1, N_a
112 d_mat(:,j_a) = input%tg_config%p / N_a
113 end do
114 input%d_next = dist_output%distribution
115 d_mat_next(1:N_e, 1:N_a) => input%d_next
116
117 if (input%forward_verbosity == 2) &
118 call mexPrintf(' === Forward Iteration ==='//NEW_LINE('A'))
119
120 ! Perform forward iterations
121 do iter = 1, input%d_options%max_iter
122 ! Perform the forward iteration algorithm
123 ! Initialization
124 linear_idx = input%gc_cache_fi%corner_idx ! Reset to initial low-corner indices
125 sk = .false.
126 z = count(is_hard_zero, dim=2)
127
128 ! Start at the low corner
129 inc = beta_0*dist_output%distribution
130 acc = 0.0_real64
131 do j = 1, N_om
132 if (z(j) == 0_int32) then
133 m = linear_idx(j)
134 acc(m) = acc(m) + inc(j)
135 end if
136 end do
137
138 ! Go over the other corners
139 do t = 1, input%gc_cache_fi%Kcorn-1
140 kf = input%gc_cache_fi%flip_idx(t)
141 if (.not. sk(kf)) then
142 ! lower -> upper on dim kf
143 linear_idx = linear_idx+stride_shocks(kf)
144 sk(kf) = .true.
145 do j = 1, N_om
146 if (is_hard_one(j,kf)) then
147 z(j) = z(j)+1_int32
148 else if (is_hard_zero(j,kf)) then
149 z(j) = z(j)-1_int32
150 else
151 inc(j) = inc(j)*r_up(j,kf)
152 end if
153 end do
154 else
155 ! upper -> lower on dim kf
156 linear_idx = linear_idx-stride_shocks(kf)
157 sk(kf) = .false.
158 do j = 1, N_om
159 if (is_hard_one(j,kf)) then
160 z(j) = z(j)-1_int32
161 else if (is_hard_zero(j,kf)) then
162 z(j) = z(j)+1_int32
163 else
164 inc(j) = inc(j)*r_down(j,kf)
165 end if
166 end do
167 end if
168 do j=1, N_om
169 if (z(j) == 0_int32) then
170 m = linear_idx(j)
171 acc(m) = acc(m)+inc(j)
172 end if
173 end do
174 end do
175
176 ! Weighting with the Markov kernel and update for the next distribution
177 d_mat(1:N_e, 1:N_a) => acc
178 call matmul_add("N", "N", 1.0_real64, input%tg_config%MuT, d_mat, &
179 0.0_real64, d_mat_next)
180
181 ! Check convergence every check_every iterations
182 if (mod(iter, input%d_options%check_every) == 0 .or. iter == input%d_options%max_iter) then
183 diff_norm = maxval(abs(dist_output%distribution - input%d_next))
184
185 ! Print per-iteration trace for verbosity == 2
186 if (input%forward_verbosity == 2) then
187 write(msg, '(A,I6,A,ES10.3,A,ES10.3)') ' Forward iter ', iter, &
188 ': ||ΔD|| = ', diff_norm, ', tol = ', input%d_options%tol
189 call mexPrintf(trim(msg)//NEW_LINE('A'))
190 end if
191
192 if (diff_norm < input%d_options%tol) then
193 dist_output%converged = .true.
194 dist_output%iterations = iter
195 dist_output%residual_norm = diff_norm
196 if (input%forward_verbosity == 2) then
197 write(msg, '(A,I0,A,ES10.3,A)') ' Distribution converged in ', iter, &
198 ' iterations (norm: ', diff_norm, ')'
199 call mexPrintf(trim(msg)//NEW_LINE('A'))
200 end if
201 ! Final update
202 dist_output%distribution = input%d_next
203 exit
204 end if
205 end if
206 ! Update for next iteration
207 dist_output%distribution = input%d_next
208 end do
209
210 ! Check if converged
211 if (.not. dist_output%converged) then
212 status = 1
213 dist_output%iterations = input%d_options%max_iter
214 dist_output%residual_norm = diff_norm
215 if (input%forward_verbosity >= 1) then
216 write(msg, '(A,I0,A,ES10.3,A)') ' WARNING: Distribution did not converge after ', &
217 input%d_options%max_iter, ' iterations (norm: ', diff_norm, ')'
218 call mexPrintf(trim(msg)//NEW_LINE('A'))
219 end if
220 end if
221
222 end function solve_distribution_tensor
223
224 subroutine compute_agg_het_variables(input, output)
225 type(calibration_input), intent(inout) :: input
226 type(calibration_output), intent(inout) :: output
227
228 integer(int32) :: k, N_Ix
229
230 if (input%cal_verbosity == 2) &
231 call mexPrintf(' === Aggregate variables and residuals ==='//NEW_LINE('A'))
232
233 ! Compute the aggregated heterogeneous policy functions
234 ! Ix_j = sum_i D_i * policy_j(state_i)
235 call matvecmul_add("N", 1.0_real64, output%ti_output%policies_om, &
236 output%dist_output%distribution, 0.0_real64, output%agg_output%Ix)
237
238 ! Fill yagg - subset corresponding to SUM operators
239 ! yagg = Ix(indices.Ix.in_x)
240 input%yagg = output%agg_output%Ix(input%Ix_in_het)
241 ! Fill the SUM_x variables in y
242 N_Ix = size(input%Ix_in_agg,1)
243 do k=1,N_Ix
244 input%y(input%dims%n_agg_endo+input%Ix_in_agg(k)) = input%yagg(k)
245 end do
246 end subroutine compute_agg_het_variables
247
248 subroutine compute_aggregate_residuals(input, output)
249 type(calibration_input), intent(inout) :: input
250 type(calibration_output), intent(inout) :: output
251 character(len=256) :: msg
252 integer :: i
253
254 if (input%dims%n_agg_endo > 0_int32) &
255 ! Use MATLAB MEX function
256 call call_matlab_resid_tensor(output%agg_output%residuals, input%mex)
257
258 ! Print all aggregate residuals if verbosity == 2
259 if (input%cal_verbosity == 2) then
260 call mexPrintf(' Aggregate residuals:'//NEW_LINE('A'))
261 do i = 1, size(input%equation_names, 1)
262 if (len_trim(input%equation_names(i)) > 0) then
263 ! Use equation name if available
264 write(msg, '(A,A,A,ES15.6)') ' ', trim(input%equation_names(i)), ': ', &
265 output%agg_output%residuals(i)
266 else
267 ! Fall back to equation number
268 write(msg, '(A,I3,A,ES15.6)') ' ', i, ': ', &
269 output%agg_output%residuals(i)
270 end if
271 call mexPrintf(trim(msg)//NEW_LINE('A'))
272 end do
273 write(msg, '(A,ES15.6,A,ES15.6)') ' Max norm: ', &
274 maxval(abs(output%agg_output%residuals(1:input%dims%n_agg_endo))), &
275 ', tol = ', input%solver_opts%tol
276 call mexPrintf(trim(msg)//NEW_LINE('A'))
277 end if
278
279 end subroutine compute_aggregate_residuals
280
281 !---------------------------------------------------------------------------
282 ! Call dynamic_het1_resid via mexCallMATLAB
283 !---------------------------------------------------------------------------
284 subroutine call_matlab_resid_tensor(residuals, input_mex)
285 type(matlab_mex_handles), intent(in) :: input_mex
286 real(real64), contiguous, intent(inout) :: residuals(:)
287
288 ! MATLAB interface variables
289 type(c_ptr), dimension(7) :: prhs
290 type(c_ptr), dimension(1) :: plhs
291 integer(C_INT) :: retval
292 real(real64), pointer, contiguous :: resid(:)
293
294 ! Build input array for mexCallMATLAB (7 inputs, no T management)
295 prhs(1) = input_mex%y_mx
296 prhs(2) = input_mex%x_mx
297 prhs(3) = input_mex%params_mx
298 prhs(4) = input_mex%y_mx
299 prhs(5) = input_mex%yagg_mx
300
301 ! Call MATLAB function: resid = model_name.dynamic_resid(y, x, params, ss, yagg)
302 retval = mexCallMATLAB(1_C_INT, plhs, 5_C_INT, prhs, input_mex%agg_resid)
303
304 if (retval /= 0) &
305 call mexErrMsgTxt("MATLAB fallback: Failed to call " // input_mex%agg_resid)
306
307 ! Extract residual from MATLAB output
308 resid(1:size(residuals)) => mxGetDoubles(plhs(1))
309 residuals = resid
310
311 call mxDestroyArray(plhs(1))
312
313 end subroutine call_matlab_resid_tensor
314
315 end module aggregate_residuals_tensor