This is a static copy of a profile report

Home

Function details for ff_abz_vf_vecThis is a static copy of a profile report

Home

ff_abz_vf_vec (Calls: 1, Time: 280.683 s)
Generated 07-Jul-2019 00:56:41 using performance time.
function in file C:\Users\fan\CodeDynaAsset\m_abz\solve\ff_abz_vf_vec.m
Copy to new window for comparing multiple runs

Parents (calling functions)
No parent
Lines where the most time was spent

Line NumberCodeCallsTotal Time% TimeTime Plot
253
mt_utility = f_util_crra(mt_c)...
13575172.165 s61.3%
270
mt_utility(mt_c <= fl_c_min...
1357574.935 s26.7%
246
mt_c = f_cons_coh(ar_coh, ar_a...
1357522.425 s8.0%
280
[ar_opti_val_z, ar_opti_idx_z]...
135754.927 s1.8%
266
mt_utility = mt_utility + fl_b...
135752.877 s1.0%
All other lines  3.355 s1.2%
Totals  280.683 s100% 
Children (called functions)

Function NameFunction TypeCallsTotal Time% TimeTime Plot
...c)(((c).^(1-fl_crra)-1)./(1-fl_crra))anonymous function27150157.074 s56.0%
...unctions>@(coh,bprime)(coh-bprime)anonymous function2715014.240 s5.1%
...b>0)+b.*(1+fl_r_borr).*(b<=0)))anonymous function135750.135 s0.0%
Self time (built-ins, overhead, etc.)  109.234 s38.9%
Totals  280.683 s100% 
Code Analyzer results
No Code Analyzer messages.
Coverage results
Show coverage for parent directory
Total lines in function374
Non-code lines (comments, blank lines)235
Code lines (lines that can run)139
Code lines that did run55
Code lines that did not run84
Coverage (did run/can run)39.57 %
Function listing
time 
Calls 
 line
   7 
function result_map = ff_abz_vf_vec(varargin)
   8 
%% FF_ABZ_VF_VEC solve infinite horizon exo shock + endo asset problem
   9 
% This program solves the infinite horizon dynamic single asset and single
  10 
% shock problem with vectorized codes.
  11 
% <https://fanwangecon.github.io/CodeDynaAsset/m_abz/solve/html/ff_abz_vf.html
  12 
% ff_abz_vf> shows looped codes. The solution is the same.
  13 
%
  14 
% The borrowing problem is similar to the savings problem. The main
  15 
% addition here in comparison to the savings only code
  16 
% <https://fanwangecon.github.io/CodeDynaAsset/m_az/solve/html/ff_az_vf_vec.html
  17 
% ff_az_vf_vec> is the ability to deal with default, as well as an
  18 
% additional shock to the borrowing interest rate.
  19 
%
  20 
% The vectorization takes advantage of implicit parallization that modern
  21 
% computers have when <https://en.wikipedia.org/wiki/SIMD same instructions
  22 
% are given for different blocks of data> With vectorization, we face a
  23 
% tradeoff between memory and speed. Suppose we have many shock points and
  24 
% many states points, if we build all states and choices into one single
  25 
% matrix and compute consumption, utility, etc over that entire matrix,
  26 
% that might be more efficient than computing consumption, utility, etc by
  27 
% subset of that matrix over a loop, but there is time required for
  28 
% generating that large input matrix, and if there are too many states, a
  29 
% computer could run out of memory.
  30 
%
  31 
% The design philosophy here is that we vectorize the endogenous states and
  32 
% choices into matrixes, but do not include the exogeous states (shocks).
  33 
% The exogenous shocks remain looped. This means we can potentially have
  34 
% multiple shock variables discretized over a large number of shock states,
  35 
% and the computer would not run into memory problems. The speed gain from
  36 
% vectoring the rest of the problem conditional on shocks is very large
  37 
% compared to the pure looped version of the problem. Even if more memory
  38 
% is available, including the exogenous states in the vectorization process
  39 
% might not be speed improving.
  40 
%
  41 
% Note one key issue is whether a programming language is
  42 
% <https://en.wikipedia.org/wiki/Row-_and_column-major_order row or column
  43 
% major> depending on which, states should be rows or columns.
  44 
%
  45 
% Another programming issue is the idea of *broadcasting* vs matrix
  46 
% algebra, both are used here. Since Matlab R2016b,
  47 
% <https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b/
  48 
% matrix broadcasting> has been allowed, which means the sum of a N by 1
  49 
% and 1 by M is N by M. This is unrelated to matrix algebra. Matrix array
  50 
% broadcasting is very useful because it reduces the dimensionality of our
  51 
% model input state and choice and shock vectors, offering greater code
  52 
% clarity.
  53 
%
  54 
% @param param_map container parameter container
  55 
%
  56 
% @param support_map container support container
  57 
%
  58 
% @param armt_map container container with states, choices and shocks
  59 
% grids that are inputs for grid based solution algorithm
  60 
%
  61 
% @param func_map container container with function handles for
  62 
% consumption cash-on-hand etc.
  63 
%
  64 
% @return result_map container contains policy function matrix, value
  65 
% function matrix, iteration results, and policy function, value function
  66 
% and iteration results tables.
  67 
%
  68 
% keys included in result_map:
  69 
%
  70 
% * mt_val matrix states_n by shock_n matrix of converged value function grid
  71 
% * mt_pol_a matrix states_n by shock_n matrix of converged policy function grid
  72 
% * ar_val_diff_norm array if bl_post = true it_iter_last by 1 val function
  73 
% difference between iteration
  74 
% * ar_pol_diff_norm array if bl_post = true it_iter_last by 1 policy
  75 
% function difference between iterations
  76 
% * mt_pol_perc_change matrix if bl_post = true it_iter_last by shock_n the
  77 
% proportion of grid points at which policy function changed between
  78 
% current and last iteration for each element of shock
  79 
%
  80 
% @example
  81 
%
  82 
%    % Get Default Parameters
  83 
%    it_param_set = 2;
  84 
%    [param_map, support_map] = ffs_abz_set_default_param(it_param_set);
  85 
%    % Chnage param_map keys for borrowing
  86 
%    param_map('fl_b_bd') = -20; % borrow bound
  87 
%    param_map('bl_default') = false; % true if allow for default
  88 
%    param_map('fl_c_min') = 0.0001; % u(c_min) when default
  89 
%    % Change Keys in param_map
  90 
%    param_map('it_a_n') = 500;
  91 
%    param_map('it_z_n') = 11;
  92 
%    param_map('fl_a_max') = 100;
  93 
%    param_map('fl_w') = 1.3;
  94 
%    % Change Keys support_map
  95 
%    support_map('bl_display') = false;
  96 
%    support_map('bl_post') = true;
  97 
%    support_map('bl_display_final') = false;
  98 
%    % Call Program with external parameters that override defaults.
  99 
%    ff_abz_vf_vec(param_map, support_map);
 100 
%
 101 
% @include
 102 
%
 103 
% * <https://fanwangecon.github.io/CodeDynaAsset/m_abz/paramfunc/html/ffs_abz_set_default_param.html ffs_abz_set_default_param>
 104 
% * <https://fanwangecon.github.io/CodeDynaAsset/m_abz/paramfunc/html/ffs_abz_get_funcgrid.html ffs_abz_get_funcgrid>
 105 
% * <https://fanwangecon.github.io/CodeDynaAsset/m_az/solvepost/html/ff_az_vf_post.html ff_az_vf_post>
 106 
%
 107 
% @seealso
 108 
%
 109 
% * save loop: <https://fanwangecon.github.io/CodeDynaAsset/m_az/solve/html/ff_az_vf.html ff_az_vf>
 110 
% * save vectorized: <https://fanwangecon.github.io/CodeDynaAsset/m_az/solve/html/ff_az_vf_vec.html ff_az_vf_vec>
 111 
% * save optimized-vectorized: <https://fanwangecon.github.io/CodeDynaAsset/m_az/solve/html/ff_az_vf_vecsv.html ff_az_vf_vecsv>
 112 
% * save + borr loop: <https://fanwangecon.github.io/CodeDynaAsset/m_abz/solve/html/ff_abz_vf.html ff_abz_vf>
 113 
% * save + borr vectorized: <https://fanwangecon.github.io/CodeDynaAsset/m_abz/solve/html/ff_abz_vf_vec.html ff_abz_vf_vec>
 114 
% * save + borr optimized-vectorized: <https://fanwangecon.github.io/CodeDynaAsset/m_abz/solve/html/ff_abz_vf_vecsv.html ff_abz_vf_vecsv>
 115 
%
 116 

 117 
%% Default
 118 
% * it_param_set = 1: quick test
 119 
% * it_param_set = 2: benchmark run
 120 
% * it_param_set = 3: benchmark profile
 121 
% * it_param_set = 4: press publish button
 122 

 123 
it_param_set = 3;
 124 
bl_input_override = true;
 125 
[param_map, support_map] = ffs_abz_set_default_param(it_param_set);
 126 

 127 
% Note: param_map and support_map can be adjusted here or outside to override defaults
 128 
% param_map('it_a_n') = 750;
 129 
% param_map('it_z_n') = 15;
 130 
% param_map('fl_r_save') = 0.025;
 131 
% param_map('fl_r_borr') = 0.035;
 132 

 133 
[armt_map, func_map] = ffs_abz_get_funcgrid(param_map, support_map, bl_input_override); % 1 for override
 134 
default_params = {param_map support_map armt_map func_map};
 135 

 136 
%% Parse Parameters 1
 137 

 138 
% if varargin only has param_map and support_map,
 139 
params_len = length(varargin);
 140 
[default_params{1:params_len}] = varargin{:};
 141 
param_map = [param_map; default_params{1}];
 142 
support_map = [support_map; default_params{2}];
 143 
if params_len >= 1 && params_len <= 2
 144 
    % If override param_map, re-generate armt and func if they are not
 145 
    % provided
 146 
    bl_input_override = true;
 147 
    [armt_map, func_map] = ffs_abz_get_funcgrid(param_map, support_map, bl_input_override);
 148 
else
 149 
    % Override all
 150 
    armt_map = [armt_map; default_params{3}];
 151 
    func_map = [func_map; default_params{4}];
 152 
end
 153 

 154 
% append function name
 155 
st_func_name = 'ff_abz_vf_vec';
 156 
support_map('st_profile_name_main') = [st_func_name support_map('st_profile_name_main')];
 157 
support_map('st_mat_name_main') = [st_func_name support_map('st_mat_name_main')];
 158 
support_map('st_img_name_main') = [st_func_name support_map('st_img_name_main')];
 159 

 160 
%% Parse Parameters 2
 161 

 162 
% armt_map
 163 
params_group = values(armt_map, {'ar_a', 'mt_z_trans', 'ar_z_r_borr_mesh_wage', 'ar_z_wage_mesh_r_borr'});
 164 
[ar_a, mt_z_trans, ar_z_r_borr_mesh_wage, ar_z_wage_mesh_r_borr] = params_group{:};
 165 

 166 
% func_map
 167 
params_group = values(func_map, {'f_util_log', 'f_util_crra', 'f_cons_checkcmin', 'f_coh', 'f_cons_coh'});
 168 
[f_util_log, f_util_crra, f_cons_checkcmin, f_coh, f_cons_coh] = params_group{:};
 169 

 170 
% param_map
 171 
params_group = values(param_map, {'it_a_n', 'it_z_n', 'fl_crra', 'fl_beta', 'fl_c_min',...
 172 
    'fl_nan_replace', 'bl_default', 'fl_default_aprime'});
 173 
[it_a_n, it_z_n, fl_crra, fl_beta, fl_c_min, ...
 174 
    fl_nan_replace, bl_default, fl_default_aprime] = params_group{:};
 175 
params_group = values(param_map, {'it_maxiter_val', 'fl_tol_val', 'fl_tol_pol', 'it_tol_pol_nochange'});
 176 
[it_maxiter_val, fl_tol_val, fl_tol_pol, it_tol_pol_nochange] = params_group{:};
 177 

 178 
% support_map
 179 
params_group = values(support_map, {'bl_profile', 'st_profile_path', ...
 180 
    'st_profile_prefix', 'st_profile_name_main', 'st_profile_suffix',...
 181 
    'bl_time', 'bl_display', 'it_display_every', 'bl_post'});
 182 
[bl_profile, st_profile_path, ...
 183 
    st_profile_prefix, st_profile_name_main, st_profile_suffix, ...
 184 
    bl_time, bl_display, it_display_every, bl_post] = params_group{:};
 185 

 186 
%% Initialize Output Matrixes
 187 
% include mt_pol_idx which we did not have in looped code
 188 

 189 
mt_val_cur = zeros(length(ar_a),it_z_n);
 190 
mt_val = mt_val_cur - 1;
 191 
mt_pol_a = zeros(length(ar_a),it_z_n);
 192 
mt_pol_a_cur = mt_pol_a - 1;
 193 
mt_pol_idx = zeros(length(ar_a),it_z_n);
 194 

 195 
%% Initialize Convergence Conditions
 196 

 197 
bl_vfi_continue = true;
 198 
it_iter = 0;
 199 
ar_val_diff_norm = zeros([it_maxiter_val, 1]);
 200 
ar_pol_diff_norm = zeros([it_maxiter_val, 1]);
 201 
mt_pol_perc_change = zeros([it_maxiter_val, it_z_n]);
 202 

 203 
%% Iterate Value Function
 204 
% Loop solution with 4 nested loops
 205 
%
 206 
% # loop 1: over exogenous states
 207 
% # loop 2: over endogenous states
 208 
% # loop 3: over choices
 209 
% # loop 4: add future utility, integration--loop over future shocks
 210 
%
 211 

 212 
% Start Profile
 213 
if (bl_profile)
 214 
    close all;
 215 
    profile off;
 216 
    profile on;
< 0.001 
      1 
 217
end 
 218 

 219 
% Start Timer
< 0.001 
      1 
 220
if (bl_time) 
< 0.001 
      1 
 221
    tic; 
< 0.001 
      1 
 222
end 
 223 

 224 
% Value Function Iteration
< 0.001 
      1 
 225
while bl_vfi_continue 
< 0.001 
    181 
 226
    it_iter = it_iter + 1; 
 227 

 228 
    %% Solve Optimization Problem Current Iteration
 229 
    % Only this segment of code differs between ff_abz_vf and ff_abz_vf_vec
 230 

 231 
    % loop 1: over exogenous states
 232 
    % incorporating these shocks into vectorization has high memory burden
 233 
    % but insignificant speed gains. Keeping this loop allows for large
 234 
    % number of shocks without overwhelming memory
< 0.001 
    181 
 235
    for it_z_i = 1:it_z_n 
 236 

 237 
        % Current Shock
  0.005 
  13575 
 238
        fl_z_r_borr = ar_z_r_borr_mesh_wage(it_z_i); 
  0.004 
  13575 
 239
        fl_z_wage = ar_z_wage_mesh_r_borr(it_z_i); 
 240 

 241 
        % cash-on-hand
  0.217 
  13575 
 242
        ar_coh = f_coh(fl_z_r_borr, fl_z_wage, ar_a); 
 243 

 244 
        % Consumption: fl_z = 1 by 1, ar_a = 1 by N, ar_a' = N by 1
 245 
        % mt_c is N by N: matrix broadcasting, expand to matrix from arrays
 22.425 
  13575 
 246
        mt_c = f_cons_coh(ar_coh, ar_a'); 
 247 

 248 
        % EVAL current utility: N by N, f_util defined earlier
  0.007 
  13575 
 249
        if (fl_crra == 1) 
 250 
            mt_utility = f_util_log(mt_c);
 251 
            fl_u_cmin = f_util_log(fl_c_min);
  0.004 
  13575 
 252
        else 
 172.165 
  13575 
 253
            mt_utility = f_util_crra(mt_c); 
  0.323 
  13575 
 254
            fl_u_cmin = f_util_crra(fl_c_min); 
  0.003 
  13575 
 255
        end 
 256 

 257 
        % f(z'|z)
  0.039 
  13575 
 258
        ar_z_trans_condi = mt_z_trans(it_z_i,:); 
 259 

 260 
        % EVAL EV((A',K'),Z'|Z) = V((A',K'),Z') x p(z'|z)', (N by Z) x (Z by 1) = N by 1
 261 
        % Note: transpose ar_z_trans_condi from 1 by Z to Z by 1
 262 
        % Note: matrix multiply not dot multiply
  1.161 
  13575 
 263
        mt_evzp_condi_z = mt_val_cur * ar_z_trans_condi'; 
 264 

 265 
        % EVAL add on future utility, N by N + N by 1, broadcast again
  2.877 
  13575 
 266
        mt_utility = mt_utility + fl_beta*mt_evzp_condi_z; 
 267 

  0.007 
  13575 
 268
        if (bl_default) 
 269 
            % if default: only today u(cmin), transition out next period, debt wiped out
 74.935 
  13575 
 270
            mt_utility(mt_c <= fl_c_min) = fl_u_cmin + fl_beta*mt_evzp_condi_z(ar_a == fl_default_aprime); 
 271 
        else
 272 
            % if default is not allowed: v = u(cmin)
 273 
            mt_utility(mt_c <= fl_c_min) = fl_nan_replace;
  0.005 
  13575 
 274
        end 
 275 

 276 
        % Optimization: remember matlab is column major, rows must be
 277 
        % choices, columns must be states
 278 
        % <https://en.wikipedia.org/wiki/Row-_and_column-major_order COLUMN-MAJOR>
 279 
        % mt_utility is N by N, rows are choices, cols are states.         
  4.927 
  13575 
 280
        [ar_opti_val_z, ar_opti_idx_z] = max(mt_utility); 
  0.174 
  13575 
 281
        ar_opti_aprime_z = ar_a(ar_opti_idx_z); 
  0.385 
  13575 
 282
        ar_opti_c_z = f_cons_coh(ar_coh, ar_opti_aprime_z); 
 283 

 284 
        % Handle Default is optimal or not
  0.005 
  13575 
 285
        if (bl_default) 
 286 
            % if defaulting is optimal choice, at these states, not required
 287 
            % to default, non-default possible, but default could be optimal
  0.117 
  13575 
 288
            ar_opti_aprime_z(ar_opti_c_z <= fl_c_min) = fl_default_aprime; 
  0.150 
  13575 
 289
            ar_opti_idx_z(ar_opti_c_z <= fl_c_min) = find(ar_a == fl_default_aprime); 
 290 
        else
 291 
            % if default is not allowed, then next period same state as now
 292 
            % this is absorbing state, this is the limiting case, single
 293 
            % state space point, lowest a and lowest shock has this.
 294 
            ar_opti_aprime_z(ar_opti_c_z <= fl_c_min) = ar_a(ar_opti_c_z <= fl_c_min);
  0.005 
  13575 
 295
        end 
 296 

 297 
        % store optimal values
  0.088 
  13575 
 298
        mt_val(:,it_z_i) = ar_opti_val_z; 
  0.051 
  13575 
 299
        mt_pol_a(:,it_z_i) = ar_opti_aprime_z; 
 300 

  0.005 
  13575 
 301
        if (it_iter == (it_maxiter_val + 1)) 
< 0.001 
     75 
 302
            mt_pol_idx(:,it_z_i) = ar_opti_idx_z; 
< 0.001 
     75 
 303
        end 
  0.006 
  13575 
 304
    end 
 305 

 306 
    %% Check Tolerance and Continuation
 307 

 308 
    % Difference across iterations
  0.286 
    181 
 309
    ar_val_diff_norm(it_iter) = norm(mt_val - mt_val_cur); 
  0.252 
    181 
 310
    ar_pol_diff_norm(it_iter) = norm(mt_pol_a - mt_pol_a_cur); 
  0.025 
    181 
 311
    mt_pol_perc_change(it_iter, :) = sum((mt_pol_a ~= mt_pol_a_cur))/(it_a_n); 
 312 

 313 
    % Update
  0.012 
    181 
 314
    mt_val_cur = mt_val; 
  0.009 
    181 
 315
    mt_pol_a_cur = mt_pol_a; 
 316 

 317 
    % Print Iteration Results
< 0.001 
    181 
 318
    if (bl_display && (rem(it_iter, it_display_every)==0)) 
 319 
        fprintf('VAL it_iter:%d, fl_diff:%d, fl_diff_pol:%d\n', ...
 320 
            it_iter, ar_val_diff_norm(it_iter), ar_pol_diff_norm(it_iter));
 321 
        tb_valpol_iter = array2table([mean(mt_val_cur,1); mean(mt_pol_a_cur,1); ...
 322 
            mt_val_cur(it_a_n,:); mt_pol_a_cur(it_a_n,:)]);
 323 
        tb_valpol_iter.Properties.VariableNames = strcat('z', string((1:size(mt_val_cur,2))));
 324 
        tb_valpol_iter.Properties.RowNames = {'mval', 'map', 'Hval', 'Hap'};
 325 
        disp('mval = mean(mt_val_cur,1), average value over a')
 326 
        disp('map  = mean(mt_pol_a_cur,1), average choice over a')
 327 
        disp('Hval = mt_val_cur(it_a_n,:), highest a state val')
 328 
        disp('Hap = mt_pol_a_cur(it_a_n,:), highest a state choice')
 329 
        disp(tb_valpol_iter);
 330 
    end
 331 

 332 
    % Continuation Conditions:
 333 
    % 1. if value function convergence criteria reached
 334 
    % 2. if policy function variation over iterations is less than
 335 
    % threshold
< 0.001 
    181 
 336
    if (it_iter == (it_maxiter_val + 1)) 
< 0.001 
      1 
 337
        bl_vfi_continue = false; 
  0.003 
    180 
 338
    elseif ((it_iter == it_maxiter_val) || ... 
    180 
 339
            (ar_val_diff_norm(it_iter) < fl_tol_val) || ... 
    180 
 340
            (sum(ar_pol_diff_norm(max(1, it_iter-it_tol_pol_nochange):it_iter)) < fl_tol_pol)) 
 341 
        % Fix to max, run again to save results if needed
< 0.001 
      1 
 342
        it_iter_last = it_iter; 
< 0.001 
      1 
 343
        it_iter = it_maxiter_val; 
< 0.001 
      1 
 344
    end 
 345 

< 0.001 
    181 
 346
end 
 347 

 348 
% End Timer
< 0.001 
      1 
 349
if (bl_time) 
< 0.001 
      1 
 350
    toc; 
< 0.001 
      1 
 351
end 
 352 

 353 
% End Profile
< 0.001 
      1 
 354
if (bl_profile) 
  0.004 
      1 
 355
    profile off 
 356 
    profile viewer
 357 
    st_file_name = [st_profile_prefix st_profile_name_main st_profile_suffix];
 358 
    profsave(profile('info'), strcat(st_profile_path, st_file_name));
 359 
end
 360 

 361 
%% Process Optimal Choices
 362 

 363 
result_map = containers.Map('KeyType','char', 'ValueType','any');
 364 
result_map('mt_val') = mt_val;
 365 
result_map('mt_pol_idx') = mt_pol_idx;
 366 

 367 
result_map('cl_mt_coh') = {f_coh(ar_z_r_borr_mesh_wage, ar_z_wage_mesh_r_borr, ar_a'), zeros(1)};
 368 
result_map('cl_mt_pol_a') = {mt_pol_a, zeros(1)};
 369 
result_map('cl_mt_pol_c') = {f_cons_checkcmin(ar_z_r_borr_mesh_wage, ar_z_wage_mesh_r_borr, ar_a', mt_pol_a), zeros(1)};
 370 
result_map('ar_st_pol_names') = ["cl_mt_pol_a", "cl_mt_coh", "cl_mt_pol_c"];
 371 

 372 
if (bl_post)
 373 
    bl_input_override = true;
 374 
    result_map('ar_val_diff_norm') = ar_val_diff_norm(1:it_iter_last);
 375 
    result_map('ar_pol_diff_norm') = ar_pol_diff_norm(1:it_iter_last);
 376 
    result_map('mt_pol_perc_change') = mt_pol_perc_change(1:it_iter_last, :);
 377 
    result_map = ff_az_vf_post(param_map, support_map, armt_map, func_map, result_map, bl_input_override);
 378 
end
 379 

 380 
end

Other subfunctions in this file are not included in this listing.