### Configuration Guide Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Details configuration options for steady state, solvers, grids, and convergence tuning. ```APIDOC ## configuration.md ### Description Documentation for configuration options. ### Options - Steady state options - Solver configuration - Grid parameters - Convergence tuning ### Features - Common configurations - Debugging guidance ``` -------------------------------- ### Configure Impulse Response Options for HetBlock Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/configuration.md This example shows how to configure options for nonlinear impulse response calculations in HetBlock, specifically adjusting the backward iteration tolerance. ```python irf = household.impulse_nonlinear( ss, shocks, options={'impulse_nonlinear': { 'backward_tol': 1e-6 }} ) ``` -------------------------------- ### Combine Blocks Example Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/blocks-api.md An example demonstrating how to combine a list of blocks into a model named 'rbc_model'. ```python from sequence_jacobian import combine blocks = [production, firm_price_setting, household] model = combine(blocks, name="rbc_model") ``` -------------------------------- ### Example Usage of Bijection Mapping and Composition Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Illustrates creating a Bijection, mapping single variables and dictionaries, accessing the inverse mapping, and composing multiple Bijections. ```python # Create mapping from lowercase to uppercase M = Bijection({'y': 'Y', 'c': 'C', 'a': 'A'}) # Map single variable output_name = M @ 'y' # 'Y' # Map dictionary lowercase_dict = {'y': 1.5, 'c': 1.0, 'a': 5.0} uppercase_dict = M @ lowercase_dict # {'Y': 1.5, 'C': 1.0, 'A': 5.0} # Get inverse M_inv = M.inv original_name = M_inv @ 'Y' # 'y' # Compose mappings M1 = Bijection({'a': 'b'}) M2 = Bijection({'b': 'c'}) M_composed = M2 @ M1 # M1 then M2: a -> c ``` -------------------------------- ### Estimation Workflows Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Covers advanced usage patterns for parameter estimation, including parameter sweeps, comparative statics analysis, and examples of grid search techniques. ```python # Estimation Workflow Example (Conceptual) # from sequence_jacobian.estimation import log_likelihood # Define your model and data # model = create_model([...]) # data = ... # Objective function for optimization # def objective(params): # return log_likelihood(model, params, data) # Parameter sweeps and grid search can be implemented using standard Python libraries # or by iterating over parameter grids and calling the objective function. ``` -------------------------------- ### Example Usage of OrderedSet Operations Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Demonstrates creating OrderedSets and performing union, intersection, and difference operations, along with membership checking. ```python inputs = OrderedSet(['K', 'L', 'Z']) outputs = OrderedSet(['Y', 'r', 'w']) # Set operations all_vars = inputs | outputs # Union macro_inputs = inputs & ['K', 'G'] # Intersection exog_shocks = outputs - ['r', 'w'] # Difference # Check membership if 'Z' in inputs: print("TFP is an input") ``` -------------------------------- ### SimpleBlock Decorator and Methods Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Demonstrates the use of the @simple decorator for defining a block, including steady_state with calibration, impulse_linear, impulse_nonlinear, and jacobian computation. Examples cover specifications like Cobb-Douglas. ```python from sequence_jacobian import SimpleBlock @simple def cobb_douglas(K, L, alpha, beta, delta, rho, sigma): # ... (implementation details) return Y, C, K_new, L_new # Example usage: calibration = { "alpha": 0.3, "beta": 0.98, "delta": 0.025, "rho": 1.02, "sigma": 1.5, } # Steady state computation cobb_douglas.steady_state(calibration) # Impulse response functions cobb_douglas.impulse_linear(calibration, impulse_variables={'K': 0.01}) cobb_douglas.impulse_nonlinear(calibration, impulse_variables={'K': 0.01}) # Jacobian computation cobb_douglas.jacobian(calibration) ``` -------------------------------- ### Heterogeneous Agents Impulse Response Example Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Illustrates the structure for impulse responses involving heterogeneous agents, where the 'D' variable represents the distribution over time and heterogeneity dimensions. ```python # Distribution impulse response (heterogeneous agents) impulses_het = { 'D': np.ndarray((T, n_income, n_assets)) # Time x heterogeneity dimensions } ``` -------------------------------- ### Advanced Usage Guide Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Covers advanced topics like Jacobian reuse, perfect foresight transitions, custom block composition, and performance optimization. ```APIDOC ## advanced-usage.md ### Description Guide to advanced usage patterns and techniques. ### Topics - Jacobian reuse patterns - Perfect foresight transitions - Custom block composition - Estimation workflows - Performance optimization - Debugging techniques - Parallel computation ``` -------------------------------- ### Example Usage of ExtendedFunction Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Demonstrates creating an ExtendedFunction from a Python function, accessing its inferred inputs and outputs, and calling it with a dictionary of arguments. ```python from sequence_jacobian.utilities.function import ExtendedFunction def production(Z, K, L, alpha): Y = Z * K ** alpha * L ** (1 - alpha) return Y f = ExtendedFunction(production) print(f.name) # 'production' print(f.inputs) # OrderedSet(['Z', 'K', 'L', 'alpha']) print(f.outputs) # OrderedSet(['Y']) # Call with dict ss = {'Z': 1.0, 'K': 100.0, 'L': 1.0, 'alpha': 0.3} result = f(ss) # {'Y': 30.0} ``` -------------------------------- ### Strict Convergence with Broyden Solver Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/configuration.md Achieve strict convergence using the Broyden solver with a very tight tolerance and increased maximum iterations. This example also demonstrates more conservative backtracking parameters. ```python ss = model.solve_steady_state( cal, unknowns, targets, options={ 'solver': 'broyden', # More robust 'ttol': 1e-14, # Very tight tolerance 'verbose': True, 'solver_kwargs': { 'maxcount': 500, 'backtrack_c': 0.3 # More conservative backtracking } } ) ``` -------------------------------- ### Custom Jacobian-Based Solving for Market Clearing Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/advanced-usage.md Manually solve equilibrium conditions using Jacobian systems. This example demonstrates solving for an unknown interest rate that clears the asset market by constructing and solving a clearing condition based on Jacobians. ```python # Example: Solve for unknown interest rate that clears asset market # J is JacobianDict from model.jacobian() # Get Jacobian of asset supply and capital demand w.r.t. interest rate J_A_r = J['A', 'r'] # Asset supply response to rate J_K_r = J['K', 'r'] # Capital demand response to rate # Construct clearing condition # We need: A(r) = K(r), so we solve J_A_r - J_K_r = some target # In steady state at reference point target = ss['A'] - ss['K'] # Current disequilibrium # Solve for change in r needed to clear delta_r = J.solve({'A': target})['r'] r_new = ss['r'] + delta_r ``` -------------------------------- ### Minimal Import Pattern Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/README.md Imports essential functions and classes for basic usage. This is suitable for getting started quickly with core functionalities. ```python from sequence_jacobian import simple, het, combine, create_model from sequence_jacobian import SteadyStateDict, ImpulseDict, JacobianDict from sequence_jacobian import grids, interpolate, estimation from sequence_jacobian.hetblocks import hh_sim ``` -------------------------------- ### Install Sequence-Space Jacobian Source: https://github.com/shade-econ/sequence-jacobian/blob/master/README.md Install the SSJ toolkit using pip. This command installs the core library and its essential dependencies. ```bash pip install sequence-jacobian ``` -------------------------------- ### Install Graphviz for Python Source: https://github.com/shade-econ/sequence-jacobian/blob/master/README.md Install the optional Graphviz package for plotting the DAG representation of models. This command uses conda for installation from the conda-forge channel. ```bash conda install -c conda-forge python-graphviz ``` -------------------------------- ### Using Pre-Built Household Block Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/quick-start.md Demonstrates how to use the extended household block for steady-state calculations. Requires defining calibration parameters like income persistence, volatility, and economic factors. ```python from sequence_jacobian.hetblocks import hh_sim # Use the extended household block which includes: # - Grid construction from parameters # - Income process setup from wage and efficiency grids hh = hh_sim.hh_extended # Standard parameters cal = { 'min_a': 0, 'max_a': 1000, 'n_a': 200, 'rho_e': 0.975, # Income persistence 'sd_e': 0.7, # Income volatility 'n_e': 7, # Income states 'w': 1.0, # Wage 'r': 0.01, # Interest rate 'beta': 0.99, # Discount factor 'eis': 1.0 # Elasticity of substitution } ss = hh.steady_state(cal) # Access steady state values print(f"Aggregate capital: {ss['A']}") print(f"Aggregate consumption: {ss['C']}") # Access internal policy functions policy_func = ss.internals['hh_extended']['a'] # shape (n_e, n_a) ``` -------------------------------- ### Customizing with hetoutputs Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/hetblocks-api.md Illustrates how to extend the household block with custom `hetoutputs` to compute additional aggregate variables, such as aggregate capital. ```python # Define function to compute aggregate capital def aggregate_capital(a, D): return np.sum(a * D, axis=(0, 1)) # Extend block with hetoutputs hh_extended_with_output = hh_sim.hh_extended.add_hetoutputs([aggregate_capital]) # Now block computes 'A' (aggregate capital) internally ``` -------------------------------- ### Basic Solver Configuration Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/configuration.md Configure the steady-state solver with general options like solver type, tolerances, and verbosity. This snippet shows how to set up the 'newton' solver with specific target and constraint tolerances. ```python ss = model.solve_steady_state( calibration, unknowns={'r': (0.0, 0.1), 'w': (0.5, 2.0)}, targets={'asset_clear': 0, 'labor_clear': 0}, options={ 'solver': 'newton', # or 'broyden' 'solver_kwargs': {}, 'ttol': 1e-12, 'ctol': 1e-9, 'verbose': True, 'constrained_method': 'linear_continuation', 'constrained_kwargs': {} } ) ``` -------------------------------- ### Configuration Options for Solvers and Grids Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Details configuration options for various parts of the library, including steady_state, impulse, jacobian, and solve_steady_state options, as well as all solver and grid parameters. ```python # Configuration Example (Conceptual) # Options can often be passed as dictionaries to the respective methods. # Example for steady_state: # cobb_douglas.steady_state(calibration, options={'conv_tol': 1e-8, 'max_iter': 500}) # Example for solver parameters (e.g., within a SolvedBlock): # @solved(..., solver_options={'tol': 1e-7, 'method': 'broyden'}) def my_block(...): # ... # Grid parameters are typically passed to grid generation functions like asset_grid. ``` -------------------------------- ### Scalar Impulse Response Example Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Defines a simple scalar impulse response using a dictionary of numpy arrays and an ImpulseDict object. ```python # Simple scalar impulse response impulses = { 'Y': np.array([0.01, 0.008, 0.006, 0.004, 0.002, 0.0]), 'C': np.array([0.005, 0.004, 0.003, 0.002, 0.001, 0.0]) } irf = ImpulseDict(impulses, T=6) ``` -------------------------------- ### Configuration Patterns for Convergence and Debugging Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Explains common configuration patterns for achieving conservative convergence, enabling fast computation, and setting up debug configurations for troubleshooting. ```python # Configuration Patterns Example (Conceptual) # Conservative convergence: # Use higher tolerances, more iterations, or damping in solvers. # options={'conv_tol': 1e-9, 'max_iter': 1000, 'damping': 0.5} # Fast computation: # Relax tolerances, use fewer iterations, leverage sparse Jacobians. # options={'conv_tol': 1e-5, 'max_iter': 50} # Debug configuration: # Enable verbose output, print intermediate steps, use smaller grids/horizons. # options={'verbose': True, 'debug_mode': True} ``` -------------------------------- ### Visualize RBC Model DAG Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/rbc.ipynb Generates a visual representation of the RBC model's Directed Acyclic Graph (DAG). Requires Graphviz to be installed. ```python from sequence_jacobian import drawdag unknowns = ['K', 'L'] targets = ['euler', 'goods_mkt'] inputs = ['Z'] drawdag(rbc, inputs, unknowns, targets) ``` -------------------------------- ### Define a HetBlock Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/quick-start.md Define a heterogeneous agent optimization block using the `@het` decorator. This example involves value function iteration and policy computation. ```python @het(exogenous='Pi', policy='a', backward='Va') def household(Va_p, a_grid, y, r, beta, eis): # Value function iteration and policy computation return Va, a, c ``` -------------------------------- ### Customizing with hetinputs Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/hetblocks-api.md Shows how to customize the household block by defining a custom income function and adding it as a `hetinput`. This allows for new model inputs like 'skill_premium'. ```python # Modify income process function def custom_income(w, skill_premium, e_grid): # Different wage structure return w * skill_premium * e_grid # Add new hetinput hh_custom = hh_sim.hh.add_hetinputs([custom_income, make_grids]) # Now model accepts 'skill_premium' as input calibration_custom = { **hh_sim.example_calibration(), 'skill_premium': 1.2 } ``` -------------------------------- ### Using hh_sim in a Model Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/hetblocks-api.md Demonstrates how to create a model using the `hh_sim` extended household block, define a production function, set up calibration, and compute impulse responses. ```python from sequence_jacobian import create_model, simple from sequence_jacobian.hetblocks import hh_sim # Define macro block (e.g., production function) @simple def production(Z, K, L): Y = Z * K ** 0.3 * L ** 0.7 return Y # Use extended household block household_block = hh_sim.hh_extended # Combine with calibration calibration = { **hh_sim.example_calibration(), 'A_shock': np.ones(100) # Some aggregate shock path } # Create model model = create_model([production, household_block]) # Solve steady state ss = model.steady_state(calibration) # Compute impulse responses shocks = {'Z': np.array([0.01, 0, 0, 0, 0])} irf = model.impulse_linear(ss, shocks) ``` -------------------------------- ### Solving Linear Systems with JacobianDict.solve() Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Demonstrates the solve method for solving linear systems of the form J @ x = targets. This is useful for finding equilibrium conditions and leverages sparse factorizations for efficiency. ```python solution = J.solve(targets) ``` -------------------------------- ### CONFIGURATION Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Documentation on configuration options for various solvers, grids, and convergence settings, along with common configuration patterns. ```APIDOC ## CONFIGURATION ### Options Documentation - Covers options for `steady_state()`. - Includes options for `impulse_linear()` and `impulse_nonlinear()`. - Details options for `jacobian()` computation. - Specifies options for `solve_steady_state()`. - Lists all solver parameters. - Documents all grid parameters. ### Configuration Patterns - Examples for conservative convergence. - Settings for fast computation. - Debug configuration options. - Troubleshooting convergence issues. ``` -------------------------------- ### Visualize Model DAG Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/advanced-usage.md Visualize the Directed Acyclic Graph (DAG) of the model to understand dependencies. Requires Graphviz to be installed for direct plotting, or can export to dot format. ```python from sequence_jacobian import drawdag model = combine([prod, household, firm, market_eq]) # drawdag(model) # Requires graphviz # Or export to dot format for external tools # See utilities.drawdag for options ``` -------------------------------- ### Advanced Customization with Hetinputs and Hetoutputs Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Explains advanced customization techniques for heterogeneous agent blocks, including progressive hetinputs for gradual input specification and custom hetoutputs for defining aggregate measurements. ```python # Advanced Customization Example (Conceptual) # from sequence_jacobian import HetBlock # @het(..., hetinputs=[('a', 'a_prev')], hetoutputs=['Y']) def custom_household(...): # ... return a_new, c, Y_firm # Progressive hetinputs can be defined to pass values computed in one block to another. # Custom hetoutputs allow defining new aggregate variables. ``` -------------------------------- ### Blocks API Reference Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Provides a complete API reference for SimpleBlock, HetBlock, SolvedBlock, and CombinedBlock, including all methods, parameters, code examples, and source file references. ```APIDOC ## blocks-api.md ### Description Complete API for SimpleBlock, HetBlock, SolvedBlock, and CombinedBlock. ### Methods - Every method with full signatures - Parameter tables - Code examples - Source file references ``` -------------------------------- ### Perfect Foresight Transitions Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Covers advanced usage for perfect foresight transitions, including the use of the ss_initial parameter, interpretation of results, and path computation. ```python # Perfect Foresight Transition Example (Conceptual) # from sequence_jacobian import SimpleBlock # @simple def my_model(...): # ... # calibration = {...} # initial_state = my_model.steady_state(calibration, return_ss=True) # # Path computation using ss_initial # path = my_model.solve_path(calibration, ss_initial=initial_state, T=100) # # Interpretation of results ``` -------------------------------- ### Set up Main HANK Model DAG Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/hank.ipynb Sets up the main HANK model by replacing the steady-state NKPC block with the full NKPC block and defining the complete list of blocks for the model. ```python blocks = [hh_ext, firm, monetary, fiscal, mkt_clearing, nkpc] hank = create_model(blocks, name="One-Asset HANK") print(*hank.blocks, sep='\n') ``` -------------------------------- ### Import JacobianDict and Compute Firm/Household Jacobians Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/krusell_smith.ipynb Import the JacobianDict class and compute the Jacobians for the firm and household blocks. The firm Jacobian maps inputs 'K' and 'Z' to outputs 'r' and 'w'. The household Jacobian maps 'r' and 'w' to 'a' (assets), with a specified truncation horizon T. ```python from sequence_jacobian.classes import JacobianDict # firm Jacobian: r and w as functions of K and Z J_firm = firm.jacobian(ss, inputs=['K', 'Z']) # household Jacobian: curlyK (called 'a' for assets by J_ha) as function of r and w T = 300 J_ha = household.jacobian(ss, inputs=['r', 'w'], T=T) ``` -------------------------------- ### Solving Nonlinear Impulse Response with Custom Options Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/two_asset.ipynb Compute the nonlinear impulse response by calling `solve_impulse_nonlinear`. This example demonstrates passing custom options to disable verbose output for specific solved blocks. ```python td_nonlin = hank.solve_impulse_nonlinear(ss, unknowns, targets, {"rstar": drstar[:, 2]}, Js={'hh': J_ha}, H_U_factored=H_U_factored, options={'pricing_solved': {'verbose': False}, 'arbitrage_solved': {'verbose': False}, 'labor_to_investment_combined_solved': {'verbose': False}}) ``` -------------------------------- ### Constructing an ImpulseDict Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Initialize an ImpulseDict with impulse response data. The time horizon 'T' can be inferred from the data or provided explicitly. ```python from sequence_jacobian import ImpulseDict import numpy as np impulses = { 'Y': np.array([0.01, 0.005, 0.002, 0.0, ...]), 'C': np.array([0.005, 0.003, 0.001, 0.0, ...]) } irf = ImpulseDict(impulses, T=100) ``` -------------------------------- ### Accessing Impulse Responses by Variable Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Get the impulse response time series for specific variables using dictionary-like key access. Supports single variables, multiple variables, or responses to specific shocks. ```python y_irf = irf['Y'] # Shape (4,) or more c_response = irf['C'] # Consumption response ``` ```python subset = irf[['Y', 'C']] # Get subset of variables ``` ```python y_values = irf['Y', 'shock_name'] # Get response of Y to specific shock (if data structured that way) ``` ```python irf = model.impulse_linear(ss, {'TFP': np.array([0.01, 0, 0, 0])}) y_response = irf['Y'] # Shape (4,) or more ``` -------------------------------- ### Standard API and Utility Imports Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/module-reference.md Import the main API components and common utilities for general use. Ensure these are available in your environment. ```python # Import main API from sequence_jacobian import ( simple, het, solved, combine, create_model, SteadyStateDict, ImpulseDict, JacobianDict ) # Import utilities from sequence_jacobian import grids, interpolate, estimation # Import pre-built blocks from sequence_jacobian.hetblocks import hh_sim ``` -------------------------------- ### Solving for General Equilibrium Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/quick-start.md Demonstrates how to solve for general equilibrium by defining market clearing targets and unknowns for interest rates and wages. Requires a model object and calibration data. ```python from sequence_jacobian import create_model # Define unknowns and targets unknowns = { 'r': (0.0, 0.1), # Interest rate between 0-10% 'w': (0.5, 2.0) # Wage between 0.5-2.0 } targets = { 'asset_market': 'A - K', # Asset supply = capital demand 'labor_market': 'H - L' # Labor supply = labor demand } # Solve for equilibrium ss_ge = model.solve_steady_state( calibration, unknowns, targets, options={'ttol': 1e-12, 'ctol': 1e-9, 'verbose': True} ) print(f"Equilibrium interest rate: {ss_ge['r']:.4f}") print(f"Equilibrium wage: {ss_ge['w']:.4f}") ``` -------------------------------- ### Block API Reference Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/INDEX.txt Reference for the Block API, including decorators for creating different types of blocks (SimpleBlock, HetBlock, SolvedBlock) and functions for combining and creating models. It details all methods with their signatures, parameters, return values, and includes examples. ```APIDOC ## Block API This section details the API for creating and using blocks within the Sequence-Jacobian framework. ### SimpleBlock - **Decorator**: `@simple` - **Description**: Used for creating simple blocks. - **Methods**: Includes methods for calculating steady state, impulse responses, and Jacobians. ### HetBlock - **Decorator**: `@het` - **Description**: Used for creating blocks that handle heterogeneous agents. - **Methods**: Includes methods for handling heterogeneous agent computations. ### SolvedBlock - **Decorator**: `@solved` - **Description**: Used for creating blocks that involve solving for equilibrium. - **Methods**: Includes methods for solving steady states and other equilibrium conditions. ### CombinedBlock - **Functions**: `combine()`, `create_model()` - **Description**: Functions for combining multiple blocks into a larger model or creating a model structure. ### Common Block Methods - **`steady_state()`**: Computes the steady state of the block. - **`impulse_linear()`**: Computes linear impulse responses. - **`impulse_nonlinear()`**: Computes nonlinear impulse responses. - **`jacobian()`**: Computes the Jacobian matrix. - **`solve_steady_state()`**: Solves for the steady state using iterative methods. - **`add_hetinputs()`**: Adds heterogeneous inputs to a block. - **`add_hetoutputs()`**: Adds heterogeneous outputs from a block. - **`rename()`**: Renames variables within a block. - **`partial_jacobians()`**: Computes partial Jacobians. ``` -------------------------------- ### Constructing a JacobianDict Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Demonstrates the simple construction of a JacobianDict by providing a nested dictionary of matrices, along with lists of output and input variable names. The time horizon and a name for the Jacobian can also be specified. ```python from sequence_jacobian import JacobianDict # Simple construction J = JacobianDict( { 'Y': {'Z': J_Y_Z, 'K': J_Y_K}, 'C': {'Z': J_C_Z, 'K': J_C_K} }, outputs=['Y', 'C'], inputs=['Z', 'K'], name='simple_block', T=100 ) ``` -------------------------------- ### Pre-Built Heterogeneous Agent Blocks Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/INDEX.txt Details on pre-built heterogeneous agent blocks available in the library, such as household models with different features. ```APIDOC ## Pre-Built Heterogeneous Agent Blocks This section lists and describes the pre-built heterogeneous agent blocks. ### `hh_sim.hh` - **Description**: Standard household block with capital accumulation. ### `hh_sim.hh_extended` - **Description**: Extended household block including grids and income processes. ### `hh_labor` - **Description**: Household block with endogenous labor supply. ### `hh_twoasset` - **Description**: Household block featuring two assets. ``` -------------------------------- ### Configuration Options Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/INDEX.txt Details on configuration options for various aspects of the library, including solvers, iteration, and output formatting. ```APIDOC ## Configuration Options This section covers the various configuration options available for controlling the behavior of the library. ### Block Method Options - **Description**: Options that can be passed to block methods. ### Steady State Iteration Control - **Description**: Parameters for controlling the steady-state solver, including tolerances and maximum iterations. ### Solver Selection and Parameters - **Description**: Options for selecting and configuring numerical solvers (e.g., Newton, Broyden). ### Grid Construction Parameters - **Description**: Options related to the creation of discrete grids for state variables. ### Interpolation Options - **Description**: Parameters for configuring interpolation methods. ### Estimation Function Parameters - **Description**: Options for estimation-related functions. ### Output and Debugging - **Description**: Options for controlling output verbosity and debugging information, including convergence tips. ``` -------------------------------- ### Timing Steady-State Calibration (Default) Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/krusell_smith.ipynb Measures the execution time of the steady-state calibration routine with default parameters using the IPython %time magic command. ```python %time ss = ks.solve_steady_state(calibration, unknowns_ss, targets_ss, solver="hybr") ``` -------------------------------- ### Create Asset Grid Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/utilities-api.md Constructs a 1D array of asset values for a heterogeneous agent model. Uses a double-exponential transformation for flexible spacing, denser near the minimum asset value. ```python from sequence_jacobian import grids a_grid = grids.asset_grid(amin=0, amax=1000, n=200) ``` ```python # Asset grid from 0 to $1,000,000 with 500 points a = grids.asset_grid(0, 1_000_000, 500) ``` -------------------------------- ### Applying Shocks with JacobianDict.apply() Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Shows how to use the apply method to compute impulse responses by multiplying Jacobian matrices by shock sequences. This method is used internally by impulse_linear but can be called directly for advanced use cases. ```python irf = J.apply(shocks) ``` ```python J = model.jacobian(ss, ['TFP'], T=100) shocks = {'TFP': np.array([0.01, 0, 0, ..., 0])} irf = J.apply(shocks) print(irf['Y']) # Impulse response of Y to TFP shock ``` -------------------------------- ### Configure for Debugging Convergence Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/configuration.md Sets debugging options for troubleshooting convergence issues. Enables verbose output and uses the Newton solver with an exact Jacobian for clarity. ```python debug_options = { 'solve_steady_state': { 'verbose': True, 'ttol': 1e-8, 'solver': 'newton', # Exact Jacobian for clarity 'solver_kwargs': { 'tol': 1e-8, 'maxcount': 200, 'verbose': True # Prints each iteration } } } ``` -------------------------------- ### Solver Configuration Defaults Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/README.md Sets default parameters for the steady-state solver, including tolerance, convergence criteria, verbosity, and the constrained method. ```python solver="", ttol=1e-12, ctol=1e-9 verbose=False, constrained_method="linear_continuation" ``` -------------------------------- ### Calibrating Krusell-Smith Model Steady State Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/krusell_smith.ipynb Sets up calibration parameters, initial guesses for unknowns, and targets for the steady state. It then solves for the steady state using the 'hybr' solver and prints the result. ```python calibration = {'eis': 1, 'delta': 0.025, 'alpha': 0.11, 'rho_e': 0.966, 'sd_e': 0.5, 'L': 1.0, 'nE': 7, 'nA': 500, 'amin': 0, 'amax': 200} unknowns_ss = {'beta': 0.98, 'Z': 0.85, 'K': 3.} targets_ss = {'r': 0.01, 'Y': 1., 'asset_mkt': 0.} ss = ks.solve_steady_state(calibration, unknowns_ss, targets_ss, solver='hybr') print(ss) ``` -------------------------------- ### Print Block Order and I/O Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/advanced-usage.md Inspect the topological order of blocks and their inputs/outputs during steady-state computation. This helps in understanding the model's structure and data flow. ```python model = combine([prod, household, firm, market_eq]) # See topological order print("Block order:", [b.name for b in model.blocks]) # Check inputs/outputs at each step ss = model.steady_state(cal) for block in model.blocks: print(f"{block.name}:") print(f" Inputs: {block.inputs}") print(f" Outputs: {block.outputs}") ``` -------------------------------- ### Verify Steady State Solution Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/two_asset.ipynb Generates the steady-state values from the dynamic DAG using the calibrated steady state. ```python ss = hank.steady_state(cali) print(f"Liquid assets: {ss['B']: 0.2f}") print(f"Asset market clearing: {ss['asset_mkt']: 0.2e}") print(f"Goods market clearing (untargeted): {ss['goods_mkt']: 0.2e}") ``` -------------------------------- ### ImpulseDict Constructor Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Initializes an ImpulseDict instance with impulse response data. It can infer the time horizon from the data or accept an explicit time horizon. ```APIDOC ## ImpulseDict Constructor ### Description Initializes an ImpulseDict instance with impulse response data. It can infer the time horizon from the data or accept an explicit time horizon. ### Parameters * **data** (dict or ImpulseDict) - Required - Dictionary mapping variable names to 1D or multi-dimensional arrays (time series) * **internals** (dict) - Optional - Block-specific internal time series * **T** (int) - Optional - Time horizon; inferred from data if not provided ### Returns `ImpulseDict` instance ### Example ```python from sequence_jacobian import ImpulseDict import numpy as np impulses = { 'Y': np.array([0.01, 0.005, 0.002, 0.0, ...]), 'C': np.array([0.005, 0.003, 0.001, 0.0, ...]) } irf = ImpulseDict(impulses, T=100) ``` ``` -------------------------------- ### Performance Optimization Techniques Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Discusses advanced patterns for performance optimization, including sparse Jacobian handling, time horizon optimization for transitions, and parallel computation strategies. ```python # Performance Optimization Example (Conceptual) # When dealing with large models, sparse Jacobian handling is crucial. # The library automatically leverages sparsity where possible. # Time horizon optimization can be achieved by adjusting the T parameter in path computations. # Parallel computation might involve using libraries like 'joblib' or 'multiprocessing' # to run multiple simulations or estimations concurrently. ``` -------------------------------- ### HetBlock Input/Output Specification Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Illustrates how HetBlock explicitly specifies inputs, outputs, and special variable types like exogenous, policy, and backward using a decorator. ```python # HetBlock specifies via decorator @het(exogenous='Pi', policy='a', backward='Va') def household(Va_p, a_grid, ...): return Va, a, c ``` -------------------------------- ### Basic Perfect Foresight Transition Path Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/advanced-usage.md Compute nonlinear transition paths when agents know future values exactly. This involves defining initial and terminal steady states, and a shock path. ```python # Define two different steady states ss_initial = model.steady_state(cal_initial) ss_terminal = model.steady_state(cal_terminal) # Define shock path that gradually moves economy T = 100 shock_path = { 'TFP': np.concatenate([ np.linspace(0, 0.05, 20), # Ramp up over 20 periods np.full(80, 0.05) # Stay at 5% for rest ]) } # Compute perfect foresight transition irf_transition = model.impulse_nonlinear( ss=ss_terminal, # Terminal steady state inputs=shock_path, ss_initial=ss_initial, # Initial steady state outputs=['Y', 'C', 'w'] ) # Result shows transition path as deviations from terminal ss ``` -------------------------------- ### Sequential Model Building with combine Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/advanced-usage.md Build complex models step-by-step by combining simpler blocks sequentially. This pattern is useful for organizing and composing different parts of an economic model. ```python from sequence_jacobian import simple, combine # Layer 1: Production and pricing @simple def production(Z, K, L, alpha): Y = Z * K ** alpha * L ** (1 - alpha) return Y @simple def pricing(Y, L): w = 0.7 * Y / L r = 0.03 return w, r layer1 = combine([production, pricing], name='production_block') # Layer 2: Add households and markets household = hh_sim.hh_extended market_clearing = some_equilibrium_block layer2 = combine([layer1, household, market_clearing], name='macro_layer') # Layer 3: Add financial markets, government, etc. financial_block = make_financial_block() government_block = make_government_block() full_model = combine([layer2, financial_block, government_block], name='full_soe_model') ``` -------------------------------- ### Accessing Jacobian Matrices with __getitem__ Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/data-classes.md Illustrates various ways to access Jacobian matrices using the __getitem__ method. This includes retrieving a single matrix, all matrices for an output, a subset of inputs for an output, multiple outputs and inputs, or using slicing for all outputs/inputs. ```python # Get single Jacobian matrix J_Y_Z = J['Y', 'Z'] # Returns matrix or sparse representation # Get all Jacobians for one output J_Y = J['Y'] # Returns dict mapping inputs to Jacobians # Get subset of inputs for one output J_Y_subset = J['Y', ['Z', 'K']] # Returns dict with only Z and K inputs # Get multiple outputs and inputs (returns new JacobianDict) J_subset = J[['Y', 'L'], ['Z']] # Returns nested dict for outputs Y,L and input Z # Slice with None to get all J_all = J[:, :] # All outputs and inputs J_all_inputs = J['Y', :] # All inputs for output Y ``` ```python J = model.jacobian(ss, ['TFP', 'discount_rate'], outputs=['Y', 'C'], T=100) J_Y_TFP = J['Y', 'TFP'] # Matrix of shape (T, n_state) J_C = J['C'] # Dict {'TFP': matrix, 'discount_rate': matrix} ``` -------------------------------- ### Configure Steady State Options for HetBlock Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/configuration.md Use this snippet to set custom options for steady-state calculations in HetBlock, such as adjusting convergence tolerances and maximum iterations. ```python ss = block.steady_state(calibration, options={ 'steady_state': {'custom_option': value} }) ``` ```python ss = household.steady_state( calibration, options={'steady_state': { 'backward_tol': 1e-6, # Loosen tolerance for speed 'backward_maxit': 2000 }} ) ``` -------------------------------- ### Model Composition with combine and create_model Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Details advanced patterns for model composition using combine() and create_model(), illustrating sequential building, nested SolvedBlocks, and the creation of complex architectures. ```python from sequence_jacobian import combine, create_model, SolvedBlock # Assume block_a and block_b are defined Block instances # combined_model = combine([block_a, block_b]) # complex_model = create_model([combined_model, another_block]) # Example of nested SolvedBlocks: # nested_solved = SolvedBlock(...) # configured with unknowns/targets # main_model = create_model([nested_solved, ...]) ``` -------------------------------- ### Solve Steady State Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/blocks-api.md Use `solve_steady_state` to find the equilibrium steady state. Provide initial calibration, variables to solve for (unknowns), and target conditions. Solver options can also be passed. ```python cal = {'beta': 0.99, 'alpha': 0.3} unknowns = {'r': (0.0, 0.1), 'w': (0.5, 2.0)} targets = {'asset_market_clear': 0.0, 'labor_market_clear': 0.0} ss = model.solve_steady_state(cal, unknowns, targets) ``` -------------------------------- ### Step-by-Step Steady State Computation Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/advanced-usage.md Compute steady states incrementally for individual blocks (e.g., production, then household) to aid in debugging. This allows isolating issues within specific parts of the model. ```python # Compute partial steady states to debug cal = {...} # Just production block ss_prod = production.steady_state(cal) print("Production outputs:", ss_prod) # Add household ss_with_hh = household.steady_state({**cal, **ss_prod}) print("Household outputs:", {k: v for k, v in ss_with_hh.items() if k not in ss_prod}) # Full model ss_full = model.steady_state(cal) ``` -------------------------------- ### HetBlocks API Reference Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Describes the specification and usage patterns for pre-built HetBlocks like hh_sim, hh_labor, and hh_twoasset. ```APIDOC ## hetblocks-api.md ### Description Specification and usage patterns for pre-built HetBlocks. ### Blocks - hh_sim.hh - hh_sim.hh_extended - hh_labor - hh_twoasset ### Features - Usage patterns - Customization techniques - Return value structure ``` -------------------------------- ### Print Model and Inputs for Calibration DAG Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/two_asset.ipynb Prints the created steady-state calibration model and its required inputs. This is useful for understanding the calibration process and parameter dependencies. ```python print(hank_ss) print(f"Inputs: {hank_ss.inputs}") ``` -------------------------------- ### Verify Steady State Targets Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/rbc.ipynb Prints the values of specific targets from the computed steady state to verify they are satisfied. This includes the Euler equation, goods market clearing, and Walras's law. ```python print(f"Euler equation: {ss['euler']}") print(f"Goods market clearing: {ss['goods_mkt']}") print(f"Walras law: {ss['walras']}") ``` -------------------------------- ### Time Comparison: Solve Jacobian with and without Precomputed Jacobian Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/two_asset.ipynb Compares the execution time of solving Jacobians with and without a precomputed household Jacobian ('J_ha'). Demonstrates significant time savings when using precomputed Jacobians. ```python %time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha}) ``` ```python %time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T) ``` -------------------------------- ### Inspect HetBlock Properties Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/krusell_smith.ipynb Prints the representation of the 'household' HetBlock and lists its inputs, macro outputs, and internal micro outputs. This helps in understanding the structure and data flow of the heterogeneous agent block. ```python print(household) print(f'Inputs: {household.inputs}') print(f'Macro outputs: {household.outputs}') print(f'Micro outputs: {household.internals}') ``` -------------------------------- ### HetBlock Decorator and Methods Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Illustrates the @het decorator for heterogeneous agent blocks, supporting exogenous and policy variables, backward iteration, policy computation, and customization with add_hetinputs and add_hetoutputs. ```python from sequence_jacobian import HetBlock @het(exog_vars=['z'], policy_vars=['a'], backward_vars=['a_next']) def household_block(beta, delta, sigma, z, a, a_next): # ... (implementation details) return a_new, c, l # Example usage: calibration = { "beta": 0.98, "delta": 0.025, "sigma": 1.5, } # Backward iteration mechanics # Policy computation # add_hetinputs() for customization # add_hetoutputs() for aggregation ``` -------------------------------- ### SimpleBlock Input/Output Extraction Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/types.md Demonstrates how SimpleBlock automatically infers inputs and outputs from a decorated function signature. ```python # SimpleBlock automatically extracts from function @simple def production(Z, K, L, alpha): Y = Z * K ** alpha * L ** (1 - alpha) return Y ``` -------------------------------- ### Verify Steady State Consistency Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/hank.ipynb Evaluates the main HANK model at the previously computed steady state (ss0) and asserts that the resulting equilibrium conditions are consistent. ```python ss = hank.steady_state(ss0) for k in ss0.keys(): assert np.all(np.isclose(ss[k], ss0[k])) ``` -------------------------------- ### Pre-built Household Blocks Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/COMPLETION_SUMMARY.txt Showcases pre-built household blocks available in hh_sim and hh_labor, including core household logic, extended versions with grid construction, and endogenous labor supply. ```python from sequence_jacobian.hetblocks import hh_sim, hh_labor, hh_twoasset # Core household with capital # hh_sim.hh # Household with grid construction # hh_sim.hh_extended # Endogenous labor supply # hh_labor # Two-asset household # hh_twoasset ``` -------------------------------- ### Test Blocks Individually Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/configuration.md Run the steady-state calculations for individual blocks to ensure they function correctly before combining them. ```python ss_prod = production.steady_state(cal) ss_hh = household.steady_state({**cal, **ss_prod}) ``` -------------------------------- ### Block Calculation Methods Source: https://github.com/shade-econ/sequence-jacobian/blob/master/_autodocs/README.md Provides methods for calculating steady states, impulse responses, and Jacobians for a given block. ```python # Steady state ss = block.steady_state(calibration, dissolve=[], options={}) ``` ```python # Impulse responses irf = block.impulse_linear(ss, inputs, outputs=None, Js={}) irf = block.impulse_nonlinear(ss, inputs, outputs=None, ss_initial=None) ``` ```python # Jacobians J = block.jacobian(ss, inputs, outputs=None, T=None) ``` ```python # Equilibrium ss = block.solve_steady_state(calibration, unknowns, targets, dissolve=[]) ``` -------------------------------- ### Define Grids and Income for Two-Asset Model Source: https://github.com/shade-econ/sequence-jacobian/blob/master/notebooks/two_asset.ipynb Defines functions to create asset and shock grids, and calculate household income. These are used to extend the generic two-asset household block with necessary inputs. ```python def make_grids(bmax, amax, kmax, nB, nA, nK, nZ, rho_z, sigma_z): b_grid = grids.agrid(amax=bmax, n=nB) a_grid = grids.agrid(amax=amax, n=nA) k_grid = grids.agrid(amax=kmax, n=nK)[::-1].copy() e_grid, _, Pi = grids.markov_rouwenhorst(rho=rho_z, sigma=sigma_z, N=nZ) return b_grid, a_grid, k_grid, e_grid, Pi def income(e_grid, tax, w, N): z_grid = (1 - tax) * w * N * e_grid return z_grid hh = hetblocks.hh_twoasset.hh hh_ext = hh.add_hetinputs([income, make_grids]) ```