def solveAgents(self): ''' Solves the microeconomic problem for all AgentTypes in this market. Parameters ---------- None Returns ------- None ''' #for this_type in self.agents: # this_type.solve() multiThreadCommands(self.agents, ['solve()'])
def FagerengObjFunc(center, spread, verbose=False): ''' Objective function for the quick and dirty structural estimation to fit Fagereng, Holm, and Natvik's Table 9 results with a basic infinite horizon consumption-saving model (with permanent and transitory income shocks). Parameters ---------- center : float Center of the uniform distribution of discount factors. spread : float Width of the uniform distribution of discount factors. verbose : bool When True, print to screen MPC table for these parameters. When False, print (center, spread, distance). Returns ------- distance : float Euclidean distance between simulated MPCs and (adjusted) Table 9 MPCs. ''' # Give our consumer types the requested discount factor distribution beta_set = approxUniform(N=TypeCount, bot=center - spread, top=center + spread)[1] for j in range(TypeCount): EstTypeList[j](DiscFac=beta_set[j]) # Solve and simulate all consumer types, then gather their wealth levels multiThreadCommands( EstTypeList, ['solve()', 'initializeSim()', 'simulate()', 'unpackcFunc()']) WealthNow = np.concatenate([ThisType.aLvlNow for ThisType in EstTypeList]) # Get wealth quartile cutoffs and distribute them to each consumer type quartile_cuts = getPercentiles(WealthNow, percentiles=[0.25, 0.50, 0.75]) for ThisType in EstTypeList: WealthQ = np.zeros(ThisType.AgentCount, dtype=int) for n in range(3): WealthQ[ThisType.aLvlNow > quartile_cuts[n]] += 1 ThisType(WealthQ=WealthQ) # Keep track of MPC sets in lists of lists of arrays MPC_set_list = [[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]] # Calculate the MPC for each of the four lottery sizes for all agents for ThisType in EstTypeList: ThisType.simulate(1) c_base = ThisType.cNrmNow MPC_this_type = np.zeros((ThisType.AgentCount, 4)) for k in range(4): # Get MPC for all agents of this type Llvl = lottery_size[k] Lnrm = Llvl / ThisType.pLvlNow if do_secant: SplurgeNrm = Splurge / ThisType.pLvlNow mAdj = ThisType.mNrmNow + Lnrm - SplurgeNrm cAdj = ThisType.cFunc[0](mAdj) + SplurgeNrm MPC_this_type[:, k] = (cAdj - c_base) / Lnrm else: mAdj = ThisType.mNrmNow + Lnrm MPC_this_type[:, k] = cAdj = ThisType.cFunc[0].derivative(mAdj) # Sort the MPCs into the proper MPC sets for q in range(4): these = ThisType.WealthQ == q for k in range(4): MPC_set_list[k][q].append(MPC_this_type[these, k]) # Calculate average within each MPC set simulated_MPC_means = np.zeros((4, 4)) for k in range(4): for q in range(4): MPC_array = np.concatenate(MPC_set_list[k][q]) simulated_MPC_means[k, q] = np.mean(MPC_array) # Calculate Euclidean distance between simulated MPC averages and Table 9 targets diff = simulated_MPC_means - MPC_target if drop_corner: diff[0, 0] = 0.0 distance = np.sqrt(np.sum((diff)**2)) if verbose: print(simulated_MPC_means) else: print(center, spread, distance) return distance
do_this_stuff = ['updateSolutionTerminal()', 'solve()', 'unpack_cFunc()'] # Solve the model for each type by looping over the types (not multithreading) start_time = clock() multiThreadCommandsFake(my_agent_list, do_this_stuff) # Fake multithreading, just loops end_time = clock() print('Solving ' + str(type_count) + ' types without multithreading took ' + mystr(end_time - start_time) + ' seconds.') # Plot the consumption functions for all types on one figure plotFuncs([this_type.cFunc[0] for this_type in my_agent_list], 0, 5) # Delete the solution for each type to make sure we're not just faking it for i in range(type_count): my_agent_list[i].solution = None my_agent_list[i].cFunc = None my_agent_list[i].time_vary.remove('solution') my_agent_list[i].time_vary.remove('cFunc') # And here's HARK's initial attempt at multithreading: start_time = clock() multiThreadCommands(my_agent_list, do_this_stuff) # Actual multithreading end_time = clock() print('Solving ' + str(type_count) + ' types with multithreading took ' + mystr(end_time - start_time) + ' seconds.') # Plot the consumption functions for all types on one figure to see if it worked plotFuncs([this_type.cFunc[0] for this_type in my_agent_list], 0, 5)
this_agent.assignParameters(CRRA = CRRA_list[i]) # Give it a unique CRRA value my_agent_list.append(this_agent) # Addd it to the list of agent types # Make a list of commands to be run in parallel; these should be methods of ConsumerType do_this_stuff = ['updateSolutionTerminal()','solve()','unpackcFunc()'] # Solve the model for each type by looping over the types (not multithreading) start_time = clock() multiThreadCommandsFake(my_agent_list, do_this_stuff) # Fake multithreading, just loops end_time = clock() print('Solving ' + str(type_count) + ' types without multithreading took ' + mystr(end_time-start_time) + ' seconds.') # Plot the consumption functions for all types on one figure plotFuncs([this_type.cFunc[0] for this_type in my_agent_list],0,5) # Delete the solution for each type to make sure we're not just faking it for i in range(type_count): my_agent_list[i].solution = None my_agent_list[i].cFunc = None my_agent_list[i].time_vary.remove('solution') my_agent_list[i].time_vary.remove('cFunc') # And here's HARK's initial attempt at multithreading: start_time = clock() multiThreadCommands(my_agent_list, do_this_stuff) # Actual multithreading end_time = clock() print('Solving ' + str(type_count) + ' types with multithreading took ' + mystr(end_time-start_time) + ' seconds.') # Plot the consumption functions for all types on one figure to see if it worked plotFuncs([this_type.cFunc[0] for this_type in my_agent_list],0,5)
this_agent = deepcopy(BasicType) this_agent.assignParameters(rho = rho_list[i]) my_agent_list.append(this_agent) do_this_stuff = ['updateSolutionTerminal()','solve()','unpack_cFunc()'] # Solve the model for each type by looping over the types (not multithreading) start_time = time() multiThreadCommandsFake(my_agent_list, do_this_stuff) end_time = time() print('Solving ' + str(type_count) + ' types without multithreading took ' + mystr(end_time-start_time) + ' seconds.') # Plot the consumption functions for all types on one figure plotFuncs([this_type.cFunc[0] for this_type in my_agent_list],0,5) # Delete the solution for each type to make sure we're not just faking it for i in range(type_count): my_agent_list[i].solution = None my_agent_list[i].cFunc = None # And here's my shitty, shitty attempt at multithreading: start_time = time() multiThreadCommands(my_agent_list, do_this_stuff) end_time = time() print('Solving ' + str(type_count) + ' types with multithreading took ' + mystr(end_time-start_time) + ' seconds.') # Plot the consumption functions for all types on one figure to see if it worked plotFuncs([this_type.cFunc[0] for this_type in my_agent_list],0,5)
def runOptimalPolicy(Parameters, LifePrice, MakeCopayFigs, copay_fig_filename=None, copay_fig_title_text=None): ''' Solve for the "socially optimal" health investment subsidy policy, then simulate its effects; depends on user-specified value of a year of life. Parameters ---------- name : str Name of this counterfactual set, used in filenames. Parameters : np.array A size 33 array of parameters, just like for the estimation. LifePrice : float Exogenous dollar "value" of a year of life, in units of $10,000. MakeCopayFigs : bool Indicator for whether to make coinsurance rate figures. copay_fig_filename : str Base of the filename for the coinsurance rate figures. copay_fig_title_text : str Additional text in title of the coinsurance rate figures. Returns ------- TBD ''' # Make the agent types param_dict = convertVecToDict(Parameters) Agents = makeMultiTypeCounterfactual(param_dict) for this_type in Agents: this_type.LifePrice = copy(LifePrice) # Solve the baseline model and get arrays of outcome variables multiThreadCommands(Agents, ['runBaselineAction()'], num_jobs=5) TotalMedBaseline, OOPmedBaseline, LifeBaseline, MedicareBaseline, SubsidyBaseline, WelfareBaseline, GovtBaseline, trash = calcSubpopMeans( Agents) for this_type in Agents: this_type.ValueBaseline = copy(this_type.ValueArray) # Find the "socially optimal" policy and implement it multiThreadCommands(Agents, ['evalSocialOptimum()'], num_jobs=5) for this_type in Agents: this_type.CopayInvstFunc = this_type.OptimalCopayInvstFunc this_type.SameCopayForMedAndInvst = False # Make sure CopayInvst isn't overwritten! if MakeCopayFigs: makeCopayFigures(Agents, copay_fig_filename, copay_fig_title_text) # Run the counterfactual and get arrays of outcome variables multiThreadCommands(Agents, ['runCounterfactualAction()'], num_jobs=5) TotalMedCounterfactual, OOPmedCounterfactual, LifeCounterfactual, MedicareCounterfactual, SubsidyCounterfactual, WelfareCounterfactual, GovtCounterfactual, WTPcounterfactual = calcSubpopMeans( Agents) # Calculate differences and store overall means in the arrays TotalMedDiff = TotalMedCounterfactual.subtract(TotalMedBaseline) OOPmedDiff = OOPmedCounterfactual.subtract(OOPmedBaseline) LifeDiff = LifeCounterfactual.subtract(LifeBaseline) MedicareDiff = MedicareCounterfactual.subtract(MedicareBaseline) SubsidyDiff = SubsidyCounterfactual.subtract(SubsidyBaseline) WelfareDiff = WelfareCounterfactual.subtract(WelfareBaseline) GovtDiff = GovtCounterfactual.subtract(GovtBaseline) # Return the full set of mean-diffs. return [ TotalMedDiff, OOPmedDiff, LifeDiff, MedicareDiff, SubsidyDiff, WelfareDiff, GovtDiff, WTPcounterfactual ]
def runCounterfactuals(name, Parameters, Policies): ''' Run a set of counterfactual policies given a set of parameters. Parameters ---------- name : str Name of this counterfactual set, used in filenames. Parameters : np.array A size 33 array of parameters, just like for the estimation. Policies : [SubsidyPolicy] List of counterfactual policies to simulate. Returns ------- TBD ''' # Make the agent types param_dict = convertVecToDict(Parameters) Agents = makeMultiTypeCounterfactual(param_dict) # Solve the baseline model and get arrays of outcome variables multiThreadCommands(Agents, ['runBaselineAction()'], num_jobs=10) TotalMedBaseline, OOPmedBaseline, ExpectedLifeBaseline, MedicareBaseline, SubsidyBaseline, WelfareBaseline, GovtBaseline, trash = calcSubpopMeans( Agents) for this_type in Agents: this_type.ValueBaseline = copy(this_type.ValueArray) print('Finished the baseline policy.') # Loop through the policies, executing the counterfactuals and storing results. N = len(Policies) TotalMedDiffs = np.zeros(N) OOPmedDiffs = np.zeros(N) LifeDiffs = np.zeros(N) MedicareDiffs = np.zeros(N) SubsidyDiffs = np.zeros(N) WelfareDiffs = np.zeros(N) GovtDiffs = np.zeros(N) WTPs = np.zeros(N) LifeDiffsByIncome = np.zeros((N, 5)) WTPsByIncome = np.zeros((N, 5)) GovtDiffsByIncome = np.zeros((N, 5)) OOPmedDiffsByIncome = np.zeros((N, 5)) TotalMedDiffsByIncome = np.zeros((N, 5)) for n in range(N): # Enact the policy for all of the agents this_policy = Policies[n] this_policy.enactPolicy(Agents) # Run the counterfactual and get arrays of outcome variables multiThreadCommands(Agents, ['runCounterfactualAction()'], num_jobs=5) TotalMedCounterfactual, OOPmedCounterfactual, ExpectedLifeCounterfactual, MedicareCounterfactual, SubsidyCounterfactual, WelfareCounterfactual, GovtCounterfactual, WTPcounterfactual = calcSubpopMeans( Agents) # Calculate differences and store overall means in the arrays TotalMedDiff = TotalMedCounterfactual.subtract(TotalMedBaseline) for i in range(5): TotalMedDiffsByIncome[n, i] = TotalMedDiff.byIncome[i] OOPmedDiff = OOPmedCounterfactual.subtract(OOPmedBaseline) for i in range(5): OOPmedDiffsByIncome[n, i] = OOPmedDiff.byIncome[i] LifeDiff = ExpectedLifeCounterfactual.subtract(ExpectedLifeBaseline) MedicareDiff = MedicareCounterfactual.subtract(MedicareBaseline) SubsidyDiff = SubsidyCounterfactual.subtract(SubsidyBaseline) WelfareDiff = WelfareCounterfactual.subtract(WelfareBaseline) GovtDiff = GovtCounterfactual.subtract(GovtBaseline) for i in range(5): GovtDiffsByIncome[n, i] = GovtDiff.byIncome[i] TotalMedDiffs[n] = TotalMedDiff.overall OOPmedDiffs[n] = OOPmedDiff.overall LifeDiffs[n] = LifeDiff.overall for i in range(5): LifeDiffsByIncome[n, i] = LifeDiff.byIncome[i] MedicareDiffs[n] = MedicareDiff.overall SubsidyDiffs[n] = SubsidyDiff.overall WelfareDiffs[n] = WelfareDiff.overall GovtDiffs[n] = GovtDiff.overall WTPs[n] = WTPcounterfactual.overall for i in range(5): WTPsByIncome[n, i] = WTPcounterfactual.byIncome[i] print('Finished counterfactual policy ' + str(n + 1) + ' of ' + str(N) + ' for ' + name + '.') # If there is only one counterfactual policy, return the full set of mean-diffs. # If there is more than one, return vectors of overall mean-diffs. if len(Policies) > 1: return [ TotalMedDiffs, OOPmedDiffs, LifeDiffs, MedicareDiffs, SubsidyDiffs, WelfareDiffs, GovtDiffs, WTPs, LifeDiffsByIncome, WTPsByIncome, GovtDiffsByIncome, OOPmedDiffsByIncome, TotalMedDiffsByIncome ] else: return [ TotalMedDiff, OOPmedDiff, LifeDiff, MedicareDiff, SubsidyDiff, WelfareDiff, GovtDiff, WTPcounterfactual, ExpectedLifeBaseline ]