[{"url":"cheatsheets/","title":"Cheatsheets","description":"","tags":["welcome"],"text":"CheatsheetsGetting Started with Julia - live.Fastrack to Julia cheatsheet.MATLAB-Julia-Python comparative cheatsheet by QuantEcon groupPlots.jl cheatsheet"},{"url":".","title":"Welcome","description":"","tags":["homepage"],"text":"Course Website of Networks in Economics and FinanceThis website contains the course material. The course is part of the Bachelor in Economics at the University of Vienna.Acknowledgement\nThe design of this website is based on Computational Thinking, a live online Julia/Pluto textbook.(computationalthinking.mit.edu)Build your own course website using https://github.com/greimel/pluto-course-template"},{"url":"installation/","title":"Software installation","description":"","tags":["welcome"],"text":"First-time setup: Install Julia & PlutoStep 1: Install Julia 1.13We install Julia with juliaup, the official Julia installer and version manager.Windows: open the Command Prompt and runwinget install --name Julia --id 9NJNWW8PVKMN -e -s msstore\nmacOS and Linux: open a Terminal and runcurl -fsSL https://install.julialang.org | sh\nAccept the default options. Then close the terminal, open a new one, and make Julia 1.13 the version you use for this course:juliaup add 1.13\njuliaup default 1.13\nIf anything goes wrong, see the instructions at julialang.org/install.Step 2: Run JuliaType julia in a terminal and press ENTER. This starts the Julia REPL, the command-line interface to Julia. Make sure that you can execute 1 + 1:Make sure that you are able to launch Julia and calculate 1+1 before proceeding!Step 3: Install PlutoNext we install Pluto, the notebook environment that we use during the course. Pluto is a Julia programming environment designed for interactivity and quick experiments.In the REPL you type Julia commands, and when you press ENTER, it runs, and you see the result.To install Pluto, we want to run a package manager command. To switch from Julia mode to Pkg mode, type ] (closing square bracket) at the julia> prompt:\njulia> ]\n\n(@v1.13) pkg>\nThe line turns blue and the prompt changes to pkg>, telling you that you are now in package manager mode. This mode allows you to do operations on packages (also called libraries).To install Pluto, run the following (case sensitive) command to add (install) the package to your system by downloading it from the internet.\nYou only need to do this once for each installation of Julia:\n(@v1.13) pkg> add Pluto\nThis might take a couple of minutes, so you can go get yourself a cup of tea!You can now close the terminal.Step 4: Use a modern browser: Mozilla Firefox or Google ChromeWe need a modern browser to view Pluto notebooks with. Firefox and Chrome work best.Second time: Running Pluto & opening a notebookRepeat the following steps whenever you want to work on a notebook or an assignment.Step 1: Start PlutoStart the Julia REPL, like you did during the setup. In the REPL, type:julia> using Pluto\n\njulia> Pluto.run()\nThe terminal tells us to go to http://localhost:1234/ (or a similar URL). Let’s open Firefox or Chrome and type that into the address bar.If nothing happens in the browser the first time, close Julia and try again. And please let us know!Step 2a: Opening a notebook from the course websiteThis is the main menu - here you can create new notebooks, or open existing ones. The notebooks and assignments of this course are on this website. To open one of them, go to its page, and on the top right, click on the button that says “Edit or run this notebook”. From these instructions, copy the notebook link, and paste it into the blue box in the Pluto main menu. Press ENTER, and select OK in the confirmation box.The first time you open a notebook, Pluto installs the packages it needs. This can take several minutes.The first thing we will want to do is to save the notebook somewhere on our own computer; see below.Step 2b: Opening an existing notebook fileWhen you launch Pluto for the second time, your recent notebooks will appear in the main menu. You can click on them to continue where you left off.If you want to run a local notebook file that you have not opened before, then you need to enter its full path into the blue box in the main menu. More on finding full paths in step 3.Step 3: Saving a notebookWe first need a folder to save our work in. Open your file explorer and create one.Next, we need to know the absolute path of that folder. Here’s how you do that in Windows and macOS.For example, you might have:C:\\Users\\yourname\\Documents\\networks\\ on Windows/Users/yourname/Documents/networks/ on macOS/home/yourname/Documents/networks/ on LinuxNow that we know the absolute path, go back to your Pluto notebook, and at the top of the page, click on “Save notebook…”.This is where you type the new path+filename for your notebook:Click Choose.Pluto saves your notebook automatically whenever you run a cell. You will find the notebook file (ending in .jl) in the folder you created.Step 4: Submitting an assignmentYou submit an assignment as an HTML export of your notebook on Moodle.Make sure that all cells have finished running and that your answers and figures are visible.Click the export button on the top right of the notebook and choose Static HTML. Your browser downloads an .html file.Open the downloaded file in your browser and check that it shows your answers.Upload the .html file to the assignment on Moodle."},{"url":"search/","title":"Search results","description":"","tags":[],"text":"window.init_search();SearchResults\nLoading..."},{"url":"sidebar data/","title":"sidebar data","description":"","tags":[],"text":"Dict main \"welcome\" collections \"welcome\" .pages, \"Julia basics\" collections \"julia basics\" .pages, \"Networks basics\" collections \"networks basics\" .pages, \"Diffusion on Networks\" collections \"diffusion\" .pages, \"Social networks\" collections \"social networks\" .pages, \"Financial networks\" collections \"financial networks\" .pages, \"Production networks\" collections \"production networks\" .pages, , about Dict authors name \"Fabian Greimel\", url \"https www.greimel.eu\" , title \"Networks in Economics and Finance\", subtitle \"BSc Economics | University of Vienna\", institution \"University of Vienna\", institution url \"https www.univie.ac.at\", institution logo \"univie logo.svg\", institution logo darkmode \"univie logo bg.svg\" "},{"url":"diffusion/DeGroot/","title":"Spread of Information and the DeGroot model","description":"","tags":["diffusion"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 3 section 1 order 1 title \"Spread of Information and the DeGroot model\" layout \"layout.jlhtml\" tags \"diffusion\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using CairoMakie.Makie.MathTeXEngine texfont using PlutoUI using Graphs using GraphMakie graphplot, graphplot using CairoMakie using LinearAlgebra using LaTeXStrings latexstring, L str using Latexify latexify using SimpleWeightedGraphs SimpleWeightedDiGraph, weight using DataFrames DataFrame, stack, Not using AlgebraOfGraphics data, mapping, visual, draw using DataFrameMacros transform md\"\"\" `DeGroot.jl` | Version 1.3 | content updated 7 Feb 2024, packages updated 4 Oct 2026 \"\"\" md\"\"\" Exercises on the DeGroot model \"\"\" md\"\"\" Below there are some some adjacency matrices. \"\"\" begin T1 1 2 1 2 0 0 0 1 2 0 1 2 0 0 1 2 0 0 1 2 0 0 0 0 0 1 0 0 1 2 1 2 0 T2 1 2 1 2 0 0 0 1 0 0 0 0 1 2 0 0 1 2 0 0 0 0 0 1 0 0 1 2 1 2 0 T3 1 2 1 2 0 0 0 1 0 0 0 0 1 2 0 0 1 2 0 0 0 0 0 1 0 0 0 1 2 1 2 T4 1 2 1 2 0 0 0 1 0 0 0 0 1 2 0 0 1 2 0 0 0 0 0 1 0 0 0 1 0 Ts T1, T2, T3, T4 latexify. Ts end md\" Exercise 1 Simulate the DeGroot model for the networks ``T 1, \\ldots, T 4`` shown below. Plot the beliefs of agent node ``1, \\ldots, 5`` as a function of time, and check whether there is convergence , and if so, consensus . Explain what you observe in terms of the SCCs in the network and the links between them. \" b0 0.2, 0.4, 0.6, 0.8, 1.0 T selector bind T Select Ts . string. \"T \", 1 4 graph SimpleWeightedDiGraph T T^50 b0 function b series T, b0, N k 0 b b0 b ts b0' while k N b T b b ts b ts b' k 1 end return b ts end function b df T, b₀, N n nodes size T, 1 b ts b series T, b₀, N df DataFrame b ts, \"node i\" for i ∈ 1 n nodes df transform df, t bycol 0 N end function b stacked T, b₀, N df b df T, b₀, N stack df, Not t , value name \"opinion\", variable name \"node\" end md\" Exercise 2 Examine the structure of high powers of T i . For the cases without convergence also inspect consecutive high powers, such as 10000 and 10001 . Relate the obtained matrices to the simulation results of Exercise 1. \" T selector T^10 000 T^10 001 round. T^10 001 T^10 000, digits 5 md\" Exercise 3 Calculate the eigenvalues of T 1', \\ldots, T 4' . Determine the social influence vector s by inspecting the eigenvectors normalised such that the elements add up to 1 that correspond to the eigenvalues that are 1 . Interpret your results. \" T selector unit eigvals findall ≈ 1 , eigvals T' unit eigvecs eigvecs T' ,unit eigvals real if real x isreal x ? real x x normalized eigvecs unit eigvecs . sum unit eigvecs, dims 1 | real if real md\"\"\" Appendix \"\"\" TableOfContents md\"\"\" Plotting helpers \"\"\" fonts regular texfont , bold texfont bold , italic texfont italic data b stacked T,b0,50 mapping t L\"time t \", opinion, color node \"\" visual Lines | x draw x figure size 500, 300 , fonts fixed layout Point2 Float64 2,1 , 1,2 , 1, 1 , 0,1 , 1,0 figure size 300, 250 , fonts attr graph args... ilabels vertices graph , layout fixed layout, arrow size 20, elabels distance 15, nlabels distance 10, node color orange, args... minimal args... xgridvisible false, xticksvisible false, xticklabelsvisible false, ygridvisible false, yticksvisible false, yticklabelsvisible false, args... let fig Figure fonts graphs SimpleWeightedDiGraph. Ts graphplot fig 1,1 , graphs 1 attr graphs 1 ..., axis minimal title L\"T 1\" graphplot fig 1,2 , graphs 2 attr graphs 2 ..., axis minimal title L\"T 2\" graphplot fig 2,1 , graphs 3 attr graphs 3 ..., axis minimal title L\"T 3\" graphplot fig 2,2 , graphs 4 attr graphs 4 ..., axis minimal title L\"T 4\" fig | as svg end graphplot graph attr graph, elabels string. weight. edges graph , ..., axis minimal , figure | as svg graphplot graph attr graph, elabels string. weight. edges graph , nlabels string. \"eigvec \", round. vec sum normalized eigvecs, dims 2 , digits 2 ..., axis minimal , figure md\"\"\" Packages \"\"\" "},{"url":"diffusion/disease/","title":"Spread of Covid19 and the SIR model","description":"","tags":["diffusion"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 3 section 2 order 2 title \"Spread of Covid19 and the SIR model\" layout \"layout.jlhtml\" tags \"diffusion\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using CairoMakie.Makie.MathTeXEngine texfont using MarkdownLiteral markdown using PlutoUI Slider, TableOfContents, CheckBox, NumberField using Statistics mean using GeometryBasics Point2 using Graphs SimpleGraph, add edge , StarGraph, CycleGraph, WheelGraph, betweenness centrality, eigenvector centrality, edges, adjacency matrix, nv, ne using DataFrames DataFrame, groupby, rename , stack, unstack, leftjoin, leftjoin , Not using DataFrameMacros combine, transform , transform, groupby, subset, subset using Chain chain using CategoricalArrays CategoricalArrays, categorical, cut, levels using AlgebraOfGraphics, GraphMakie using CairoMakie using Makie Makie, Figure, Axis, Legend, Lines, lines , scatter , scatterlines, scatterlines , vlines , hidedecorations , ylims , cgrad, lift, Observable using NetworkLayout NetworkLayout, Shell using NearestNeighbors BallTree, knn using Distributions Distributions, LogNormal using PlutoTest test using HypertextLiteral md\"\"\" `disease.jl` | Version 1.8 | content updated 14 Oct 2024, packages updated 4 Oct 2026 \"\"\" md\"\"\" Diffusion on Networks Modeling Transmission of Disease This notebook will be the basis for part of Lecture 4 and Assignment 3 . Here is what we will cover. 1. We will model the diffusion of disease on a network. We will analyze how the parameters of the model change the outcomes. \"\"\" md\"\"\" 2. We will show how various policies mitigate the spread of the disease. We will see how we can map social distancing and vaccination programs into the model. The plot below shows how the number of infected people decreases when we randomly pick 20% of the population. Can we improve the efficacy of the vaccination program by targeting specific people? \"\"\" md\"\"\" 3. In your assignment you will make to model a little richer by `` i `` separating the `R` state into dead and immune which includes recovered and vaccinated and `` ii `` taking into account age specific death case fatality rates. Can we now improve the efficacy of the vaccination program even more? 4. Is this economics? Yes and no. There have been many papers studying the economic impact of Covid. Many of them integrate some version of the SIR model into a macroeconomic model. If you are interested, you can have a look at the collection of covid economics resources https cepr.org content covid 19 by the CEPR, this blogpost https johnhcochrane.blogspot.com 2020 05 an sir model with behavior.html by John Cochrane or this paper https www.aeaweb.org articles?id 10.1257 jep.34.4.105 by an epidemiologist in the Journal of Economic Perspectives . \"\"\" md\"\"\" The SIR Model In the simplest case, there are three states. 1. `S`usceptible 2. `I`nfected 3. `R`emoved recovered or dead For your assignment you will split up the `R` state into immune and dead. \"\"\" begin abstract type State end struct S State end struct I State end struct R State end struct D State end Assignment end const States Union subtypes State ... Markdown.MD Markdown.Admonition \"warning\", \"Note\", md\"The code uses the concept Multiple dispatch . For a simpler illustration have a look at the notebook `more julia.jl`\" md\" Define the transitions \" function transition I, par, node, args... kwargs... δ, ρ node x rand if ??? die XXXX ASSIGNMENT YOUR ACTION IS REQUIRED HERE else if x ρ δ recover or die R else I end end transition R, args... kwargs... R function transition S, par, node, adjacency matrix, is infected node id node inv prob 1.0 for i in is infected inv prob 1 par.p adjacency matrix i, node id end inv prob prod 1 par.p adjacency matrix i, node id for i in is infected, init 1.0 π 1.0 inv prob rand π ? I S end function iterate states new, states, adjacency matrix, par, node df is infected findall isa. states, I for node row ∈ eachrow node df node id node row states new node id transition states node id , par, node row, adjacency matrix, is infected end states new end function iterate states, adjacency matrix, par, node df states new Vector States undef, N iterate states new, states, adjacency matrix, par, node df states new end md\"\"\" Simulate on a Simple Network ``\\rho s`` bind ρ simple Slider 0.0 0.25 1.0, default 0.0, show value true recovery probability ``\\delta s`` bind δ simple Slider 0.0 0.25 1.0, default 0.0, show value true death rate ``p s`` bind p simple Slider 0.0 0.25 1.0, default 0.5, show value true infection probability \"\"\" simple graph CycleGraph 10 T simple 15 md\"\"\" ``t`` bind t0 simple NumberField 1 T simple, default 1 \"\"\" md\"\"\" Simulate on a Big Network \"\"\" md\"\"\" ``\\rho`` bind ρ0 Slider 0.0 0.1 0.9, default 0.1, show value true recovery probability ``\\delta`` bind δ0 Slider 0.0 0.02 0.2, default 0.04, show value true death rate ``p`` bind p0 Slider 0.1 0.1 0.9, default 0.3, show value true infection probability \"\"\" T big 100 period selector md\"\"\" ``t`` bind t0 NumberField 1 T big, default 20 \"\"\" period selector md\"\"\" Policies \"\"\" md\"\"\" Social Distancing \"\"\" p range 0.1 0.1 0.9 md\"\"\" School closures See last year's assignment https greimel.github.io networks course notebooks school closures \"\"\" md\"\"\" Vaccinations \"\"\" md\"\"\" ``t`` bind t0 vacc NumberField 1 T big, default 1 \"\"\" md\"\"\" It's really hard to see the difference, so let's use an alternative visualization. \"\"\" md\"\"\" Assignment 3 Whom to vaccinate? If you have 100 doses at your disposal, whom would you vaccinate? \"\"\" group members firstname \"Ella Louise\", lastname \"Flores\" , firstname \"Padraig\", lastname \"Cope\" , firstname \"Christy\", lastname \"Denton\" group number 99 if group number 99 || group members 1 .firstname \"Ella Louise\" && group members 1 .lastname \"Flores\" md\"\"\" danger \"Note \" Before you submit , please replace the randomly generated names in this cell 3bf0f92a 991d 42d3 ad30 28fb0acb3269 by the names of your group and put the right group number in this cell 1e2189d3 58c5 4f7d b76c 2e0ad5b7a803 . \"\"\" end md\"\"\" Task 1 Distinguishing `R`ecovered and `D`ead 3 points \"\"\" md\"\"\" 👉 Add a new state `D`ead. \"\"\" md\"\"\" 👉 Add a transition rule for `D`. \"\"\" transition D, args... kwargs... your code here md\"\"\" 👉 Go to section Define the transtions and adjust the transition rules for the other states if necessary. \"\"\" md\"\"\" Great You can now have a look how the simulations from the lecture have automatically updated. \"\"\" md\"\"\" Introducing age specific death rates The death probabilities are highly heterogeneous across age groups. See for example this dated article in Nature. https www.nature.com articles s41586 020 2918 0 Let us assume there are the following age groups with age specific \\delta . Feel free to experiment a bit and change how these are computed. \"\"\" md\"\"\" We randomly assign each node into an age bin. This is visualized below. \"\"\" md\"\"\" We want to adjust the code so that it can handle node specific \\delta . The way we are going to do it is to pass a vector \\vec \\delta \\delta 1, \\ldots, \\delta N that holds the death probability for each node. \"\"\" md\"\"\" Task 2 Whom to vaccinate? 5 points Can you think of a way to improve the effectiveness of the vaccination program? If you have 100 doses at your disposal, whom would you vaccinate? \"\"\" function pseudo random N, n, offset 1 step N ÷ n range offset, step step, length n end md\"\"\" 👉 Decide which nodes you want to vaccinate and adjust the cell below. Make sure you only vaccinate `N vacc` nodes. \"\"\" answer2 md\"\"\" You answer goes here ... \"\"\" answer3 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Before you submit ... 👉 Make sure you have added your names in this cell 3bf0f92a 991d 42d3 ad30 28fb0acb3269 and your group number in this cell 1e2189d3 58c5 4f7d b76c 2e0ad5b7a803 . 👉 Make sure that that all group members proofread your submission especially your little essay . 👉 Go to the very top of the notebook and click on the symbol in the very top right corner. Export a static html file of this notebook for submission. The source code is embedded in the html file. \"\"\" md\"\"\" Appendix to Assignment \"\"\" md\"\"\" Details on age specific infection fatality rates \"\"\" md\"\"\" The death probabilities are highly heterogeneous across age groups. See for example this article in Nature. https www.nature.com articles s41586 020 2918 0 We find that age specific IFRs estimated by the ensemble model range from 0.001% 95% credible interval, 0–0.001 in those aged 5–9 years old range, 0–0.002% across individual national level seroprevalence surveys to 8.29% 95% credible intervals, 7.11–9.59% in those aged 80 range, 2.49–15.55% across individual national level seroprevalence surveys . Markdown.MD Markdown.Admonition \"danger\", \"Beware \", md\"These data are outdated.\" Below find the data from supplementary table S3 from this article. \"\"\" md\"\"\" Get from infection fatality ratio to \\delta When the recovery rate is \\rho , the expected time infected is T I 1 \\rho . So we want the survival probability to 1 IFR 1 \\delta ^ T I . \"\"\" get δ from ifr ifr, ρ 1 1 ifr 100 ^ ρ md\"\"\" Appendix \"\"\" md\"\"\" Functions for the simulation \"\"\" function initial state N, infected nodes, recovered nodes fill with \"Susceptible\" init States S for i in 1 N init infected nodes . Ref I init recovered nodes . Ref R init end function initial state N, n infected spread out the desired number of infected people infected nodes 1 N÷n infected N initial state N, infected nodes, end function simulate graph, par, T, init initial state nv graph , max nv graph ÷ 100, 1 node df DataFrame node id 1 nv graph , par... mat adjacency matrix graph N nv graph sim Matrix States undef, N, T sim ,1 . init for t 2 T iterate view sim, , t , view sim, , t 1 , mat, par, node df end sim end sim simple let g simple graph par p p simple node df DataFrame node id 1 nv g , δ δ simple, ρ ρ simple info node df sim simulate simple graph, par, T simple node df sim, g end md\"\"\" Processing the Simulated Data \"\"\" function ordered states states levels unique states order \"S\", \"I\", \"R\", \"D\" if levels ⊆ order return sorted order ∩ levels else return levels end end label x DataType string Base.typename x .name label x label typeof x function tidy simulation output sim go from type to symbol S \"S\" sim1 label. sim make it a DataFrame with T columns and N rows df0 DataFrame sim1, auto rename df0, string. 1 size df0,2 add a column with node identifier df0.node id 1 size df0, 1 stack df to node id | t | state df stack df0, Not node id , variable name t, value name state make t numeric transform df, t parse Int, eval t , state bycol categorical state df end function fractions over time sim tidy sim tidy simulation output sim N, T size sim return chain tidy sim begin groupby t, state combine fraction length node id N put states into nice order transform state bycol levels state, ordered states state end end md\"\"\" Plotting helpers \"\"\" fonts regular texfont , bold texfont bold , italic texfont italic figure figurepadding 3, fonts function plot fractions figpos, t, sim, color dict, legpos nothing df fractions over time sim plt data df visual Lines mapping t AlgebraOfGraphics.L\"t\", fraction, color state \"\" visual Lines fg draw figpos, plt, scales Color palette collect color dict ax only fg .axis vlines ax, map t t , t , color gray50, linestyle dash, loose ylims ax, 0.05, 1.05 some attributes to make the legend nicer attr orientation horizontal, titleposition left, framevisible false if isnothing legpos leg legend legpos, fg attr... else leg nothing end ax fg, leg end function plot diffusion figpos, graph, sim, t, color dict kwargs... sim colors color dict label s for s in sim state as color t lift sim colors , t ax Axis figpos hidedecorations ax N, T size sim msize N 20 ? 15 N ≤ 100 ? 10 7 graphplot ax, graph node size msize, node color state as color t, kwargs... ax end function sir plot figpos, legpos, sim, graph, t kwargs... states ordered states label. subtypes State colors Makie.wong colors 5,2,3,1,6,4,7 color dict Dict s colors i for i,s in enumerate states ax f, leg plot fractions figpos 1,2 , t, sim, color dict, legpos ax d plot diffusion figpos 1,1 , graph, sim, t, color dict kwargs... ax f, ax d, leg end function compare sir sim1, sim2, graph t 1, kwargs... t Observable 1 fig Figure figure... legpos fig 1 2,2 panel1 fig 1,1 panel2 fig 2,1 axs1 sir plot panel1, legpos, sim1, graph, t kwargs... axs2 sir plot panel2, nothing, sim2, graph, t kwargs... axs1.leg.orientation vertical assert axes sim1, 2 axes sim2, 2 fig, t, T range axes sim1, 2 end function sir plot sim, graph t 1, kwargs... t Observable 1 fig Figure figure..., size 600, 300 main fig fig 2,1 leg pos fig 1,1 sir plot main fig, leg pos, sim, graph, t kwargs... fig, t, T range axes sim, 2 end let sim, g sim simple out sir plot sim, g, layout Shell , node attr strokewidth 0.5, , ilabels vertices g , t t0 simple out.fig end md\" Spatial graph \" adapted from David Gleich, Purdue University https www.cs.purdue.edu homes dgleich cs515 2020 julia viral spreading.html function spatial graph node positions degreedist LogNormal log 2 ,1 n length node positions coords matrix hcat Vector. node positions ... T BallTree coords matrix g SimpleGraph n for i 1 n draw the number of links `deg` deg min ceil Int, rand degreedist , n 1 use the `deg` closest nodes as neighbours idxs, dists knn T, coords matrix ,i , deg 1 for j in idxs if i j add edge g, i, j end end end g end function spatial graph N Int id 1 N x rand N y rand N node positions Point2. x, y spatial graph node positions , node positions end sim big let par p p0 graph, node positions spatial graph 1000 node df DataFrame node id 1 nv graph , ρ ρ0, δ δ0 sim simulate graph, par, T big node df sim big sim, graph, node positions end big fig let sim, graph, node positions sim big attr layout node positions, node attr strokewidth 0.1 , edge width 0.5, edge color black, 0.3 , out sir plot sim, graph t t0, attr... out.fig end big fig graph, node positions spatial graph 1000 let state \"I\" fig Figure figure..., size 400, 300 ax Axis fig 1,1 , title \" state when varying the infection probability\", titlefont italic node df DataFrame node id 1 nv graph , ρ ρ0, δ δ0 for p in p range par p sim simulate graph, par, 100 node df df0 fractions over time sim filter state state , df0 lines df0.t, df0.fraction, label L\"p % p\", color blue, 1 p end Legend fig 1,2 , ax fig end vacc let N 1000 N vacc N ÷ 5 par p 0.1 graph, node positions spatial graph N node df DataFrame node id 1 nv graph , ρ ρ0, δ δ0 vaccinated \"none\" , \"random\" pseudo random N, N vacc, 3 , place for your suggestions infected nodes pseudo random N, N ÷ 5, 1 sims map vaccinated do label, vacc nodes init initial state N, infected nodes, vacc nodes sim simulate graph, par, 100, init node df label sim end graph, node positions, sims sims end out vacc let attr layout vacc.node positions, node attr strokewidth 0.1 , edge width 0.5, edge color black, 0.3 , compare sir last. vacc.sims 1,2 ..., vacc.graph t t0 vacc, attr... end out vacc.fig fig vaccc let state \"I\" fig Figure figure..., size 350, 350 ax Axis fig 1,1 , title \" state when vaccinating different groups\" for i, lab, sim in enumerate vacc.sims df0 fractions over time sim subset df0, state state lines df0.t, df0.fraction, label lab , color colors i end some attributes to make the legend nicer attr orientation horizontal, titleposition left, framevisible false leg Legend fig 2,1 , ax attr... fig end fig vaccc md\"\"\" Utils \"\"\" md\"\"\" Package Environment \"\"\" generate a list of points that can be used to plot the graph function edges as points graph, node positions edges as pts Point2f0 for e in edges graph push edges as pts, node positions e.src push edges as pts, node positions e.dst push edges as pts, Point2f0 NaN, NaN end edges as pts end md\"\"\" Data \"\"\" import CSV ifr csv CSV.File IOBuffer \"\"\" from to IFR pc 0 4 0.003 5 9 0.001 10 14 0.001 15 19 0.003 20 24 0.006 25 29 0.013 30 34 0.024 35 39 0.040 40 44 0.075 45 49 0.121 50 54 0.207 55 59 0.323 60 64 0.456 65 69 1.075 70 74 1.674 75 79 3.203 80 95 8.292 \"\"\" note the oldest age group is actually 80 ifr df0 chain ifr csv begin DataFrame transform age mean tuple from, to , age bin bycol cut to, 0, 40, 75, 100 end ifr df chain ifr df0 begin groupby age bin combine IFR pc mean IFR pc transform age group bycol 1 length age bin transform ρ 1 7 transform δ get δ from ifr IFR pc, ρ end scatterlines ifr df0.age, ifr df0.IFR pc, axis xlabel \"age group\", ylabel \"infection fatality ratio % \" md\"\"\" Plotting \"\"\" md\"\"\" Spatial network \"\"\" md\"\"\" Other Stuff \"\"\" cell id \" \" string PlutoRunner.currently running cell id age graph let N 1000 p 0.5 node df DataFrame node id 1 N, ρ 0.5, δ 0.01 age group rand Distributions.Categorical 0.4, 0.35, 0.25 , N chain node df begin leftjoin , ifr df, on age group transform δ 20 δ end par p graph, node positions spatial graph N par, graph, node positions, node df end bad cell cell id let graph, node positions, node df age graph age groups unique node df.age bin colors Makie.wong colors 5,2,3,1,6,4,7 color dict Dict s colors i for i,s in enumerate age groups node color color dict grp for grp ∈ node df.age bin fig, ax, graphplot graph layout node positions, node color, figure leg df label string label , element MarkerElement marker circle, color for label, color ∈ pairs color dict | DataFrame leg df axislegend ax, leg df.element, leg df.label, \"age bin\" fig end vacc age let par, graph, node positions, node df age graph N nv graph info node df N vacc N ÷ 5 my try 1 N vacc centr betweenness centrality graph split 50 vaccinated \"none\" , \"random\" pseudo random N, N vacc, 4 , \"my try\" my try place your suggestions here You can also adjust \"my try\" infected nodes pseudo random N, N ÷ 10, 1 sims map vaccinated do label, vacc nodes init initial state N, infected nodes, vacc nodes sim simulate graph, par, 100, init node df label sim end graph, node positions, sims end fig vacc age let state isdefined D ? \"D\" \"I\" fig Figure figure..., size 450, 300 ax Axis fig 1,1 , title \" state when vaccinating different groups\", titlefont italic for i, lab, sim in enumerate vacc age.sims df0 fractions over time sim filter state state , df0 lines df0.t, df0.fraction, label lab end Legend fig 1,2 , ax fig end TableOfContents begin hint text Markdown.MD Markdown.Admonition \"hint\", \"Hint\", text almost text Markdown.MD Markdown.Admonition \"warning\", \"Almost there \", text still missing text md\"Replace `missing` with your answer.\" Markdown.MD Markdown.Admonition \"warning\", \"Here we go \", text keep working text md\"The answer is not quite right.\" Markdown.MD Markdown.Admonition \"danger\", \"Keep working on it \", text yays md\"Great \", md\"Yay ❤\", md\"Great 🎉\", md\"Well done \", md\"Keep it up \", md\"Good job \", md\"Awesome \", md\"You got the right answer \", md\"Let's move on to the next section.\" correct text rand yays Markdown.MD Markdown.Admonition \"correct\", \"Got it \", text end if isdefined D if hasproperty States.b.b, b correct md\"You've successfully defined type `D`.\" else almost md\"You've successfully defined `D`. But you need to do it in the right place. Go to The SIR Model b8d874b6 648d 11eb 251c 636c5ebc1f42 and uncomment the line that defines `D`.\" end else keep working md\" Go to The SIR Model b8d874b6 648d 11eb 251c 636c5ebc1f42 and uncomment the line that defines `D`.\" end hint md\"You can look at the section Define the transitions for inspiration.\" try transition D if transition D D correct md\"You've successfully specified the transition rule for `D`.\" else keey working md\"The transition rule for `D` doesn't seem to work correctly\" end catch e if e isa MethodError keep working md\"The transition rule for `D` is not yet defined.\" else keep working md\"The transition rule for `D` doesn't seem to work correctly\" end end begin try test1 transition I , , δ 1, ρ 0 , 0 D test2 transition I , , δ 0, ρ 1 , 0 R test3 transition I , , δ 0, ρ 0 , 0 I if test1 && test2 && test3 correct md\"It seems that you've successfully adjusted the transition rule for `I`. Note the other rules are not checked \" else keep working end catch keep working end end function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ', ' ', '.', ',', ' ', ' ', '\"', ' ', ' ', '\\'' length filter \"\" , words end test wordcount \" Hello, it's me. \" 4 test wordcount \"This doesn't really matter.\" 5 show words answer md\" approximately wordcount answer words \" function show words limit answer, limit count wordcount answer if count 1.02 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end limit2 250 show words limit answer2, limit2 md\"\"\" Now write a short essay describing your choice. Your simulation results are subject to random noise. Make sure you run you simulations multiple times to make sure they are robust. 👉 Describe how you would select nodes to be vaccinated 👉 Be accurate but concise. Aim at no more than limit2 words. \"\"\" limit3 150 show words limit answer3, limit3 markdown \"\"\" Task 3 Identifying scientific misconduct 2 points 👉 Look at this cell bad cell . It contains scientific misconduct. Identify the offending line of code, explain what it does, and how it affects the results of Task 2. Use fewer than limit3 words. \"\"\" members let names map group members do firstname, lastname firstname \" \" lastname end join names, \", \", \" & \" end md\"\"\" submitted by members group group number \"\"\" strike str htl \" s str s \" md\"\"\" Acknowledgement \"\"\" Markdown.MD Markdown.Admonition \"warning\", \"The design of this notebook is based on\", md\"\"\" Computational Thinking , a live online Julia Pluto textbook. computationalthinking.mit.edu https computationalthinking.mit.edu \"\"\" "},{"url":"financial-networks/risk-sharing/","title":"Risk sharing in financial networks","description":"","tags":["financial-networks"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 5 section 1 order 1 title \"Risk sharing in financial networks\" layout \"layout.jlhtml\" tags \"financial networks\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using CairoMakie.Makie.MathTeXEngine texfont using Graphs using Optim using ForwardDiff using Chain chain using DataFrames using DataFrameMacros using AlgebraOfGraphics using CairoMakie, Makie using GraphMakie using NetworkLayout using LaTeXStrings latexstring, L str using Random using PlutoUI Slider using NamedTupleTools delete using PlutoUI using PlutoTest test md\"\"\" `risk sharing.jl` | Version 1.3 | content updated 13 Mar 2024, packages updated 4 Oct 2026 \"\"\" md\"\"\" Risk Sharing and Systemic Risk in Financial Networks A financial network is a network of promises a liability is a promised payment between banks or other financial institutions 👉 Part A Risk sharing What's good about financial networks? \\ based on Allen & Gale, 2000 https www.jstor.org stable 10.1086 262109 , Journal of Political Economy 1. banks provide liquidity 2. banks are fragile subject to bank runs 3. an interbank market can avoid default , prevent bank runs Part B Systemic Risk What's bad about financial networks? \\ based on Acemoglu, Ozdaglar & Tahbaz Salehi, 2015 https www.aeaweb.org articles?id 10.1257 aer.20130456 , American Economic Review 1. Model setup 2. insolvency and bankruptcy in the payment equilibrium 3. financial contagion 4. stability and resilience of financial networks more interbank lending leads to higher fragility densely connected networks are robust, yet fragile with big shocks , we want to have disconnected components \"\"\" md\"\"\" Part A Risk sharing in financial networks We study the model of Allen & Gale 2000 , which builds on the Diamond & Dybvig 1983 of bank runs. \"\"\" md\"\"\" If you want to read more about the Diamond Dybvig model a true classic Diamond & Dybvig 1983 https www.jstor.org stable 1837095 Bank Runs, Deposit Insurance, and Liquidity, Journal of Political Economy Diamond 2007 https www.richmondfed.org media RichmondFedOrg publications research economic quarterly 2007 spring pdf diamond.pdf A simple exposition of the Diamond Dybvig model, Richmond Fed Economic Quarterly \"\"\" md\"\"\" 1. Banks provide liquidity A story A simple world We are in a simple world. At period ``t 0`` there are is a big population, where each person owns 1 kg of potatoes the initial endowment is 1 . Preferences At this moment `` t 0 ``, nobody is hungry. Everybody knows that they will be hungry at some point . But they don't know when either in period ``1`` or period ``2``. The utility of an agent is ```math \\begin cases u c 1 & \\text with probability \\gamma \\\\ u c 2 &\\text with probability 1 \\gamma \\end cases ``` Investment opportunities There are two options. Either store the potatoes or plant potatoes to grow more of them. Storage has a gross return of ``1`` no gain, no loss and the stored potatoes are a liquid asset. They can be eaten in either of the two periods. Each kilogram of planted potatos yield ``1.5`` kilograms of potatoes in period 2. The gross return is ``R 1.5`` if held to maturity . Planted potatoes are an illiquid asset . If you dig up the planted potatoes in the intermediate period they will have lost their quality and not be very enjoyable. So, in case of early liquidation the gross return is ``r \\in 0, 1 ``. \"\"\" md\"\"\" Investment decision of an agent Each agent can split up their initial endowment 1kg of potatoes , plant fraction ``x`` and store fraction ``1 x``. When the agents wakes up hungry in period 1, the agent will dig up liquidate the planted potatoes and have a consumption of ``c 1 1 x r x``. If the agent wake is not hungry in period 1, she will keep the ``x`` potatoes in the ground, and the `` 1 x `` potatoes in the storage and have a consumption of ``c 2 1 x R x`` in period 2. ```math \\begin align &\\max x \\mathbb E U c 1, c 2 \\gamma u c 1 1 \\gamma u c 2 \\\\ &\\begin aligned \\text such that & c 1 1 x r x \\\\ & c 2 1 x R x \\end aligned \\end align ``` \"\"\" u log 𝔼U c₁, c₂ γ γ u c₁ 1 γ u c₂ sliders md\"\"\" ``R`` bind R Slider 0.5 0.05 1.5, default 1.1, show value true ``r`` bind r Slider 0.0 0.05 1.0, default 0.1, show value true ``\\gamma`` bind γ Slider 0.0 0.05 1.0, default 0.5, show value true \"\"\" sliders md\"\"\" If the return from liquidation r is sufficiently low, agents will not invest in the liquid asset x 0 . The fact that nobody is investing in the asset is not very satisfying. Isn't it somehow possible to predict how many agents will be hungry in period 2 ? Then we could invest at least plant some potatoes and distribute the returns somehow. \"\"\" md\"\"\" The social optimum What would a benevolent social planner do? The planner can collect all initial endowments, make an investment decision and distribute the proceeds. The planner maximizes the ex ante expected utility of an agent. ```math \\begin align & \\max x, \\ell \\in 0,1 \\gamma u c 1 1 \\gamma u c 2 \\\\ &\\begin aligned \\text such that && \\gamma c 1 & 1 x \\ell r x \\\\ && 1 \\gamma c 2 & 1 \\ell R x \\end aligned \\end align ``` \"\"\" c₁ x, ℓ γ γ 1 x ℓ x r γ c₂ x, ℓ γ γ 1 ℓ x R 0.0 ? 0.0 1 ℓ x R 1 γ function obj args γ γ x, ℓ args 𝔼U c₁ x, ℓ γ , c₂ x, ℓ γ γ end social optimum let neg obj args obj args res optimize neg obj, 0.0, 0.0 , 1.0, 1.0 , 0.5, 0.5 , Fminbox GradientDescent x opt, ℓ opt Optim.minimizer res x opt, ℓ opt, c₁ opt c₁ x opt, ℓ opt γ , c₂ opt c₂ x opt, ℓ opt γ end sliders md\"\"\" We can see that in the social optimum, there is a significant investment into the liquid asset. We can also see, that the optimal expected utility is higher than in the individual optimum above. In the real world, there is no benevolent social planner. So the question is How can we achieve the social optimum? TL DR banks. \"\"\" md\"\"\" The role of a bank Agents deposit their initial potatoes in the bank. The investment decision is delegated to the bank, who promises a fixed return `` c 1, c 2 `` depending on the time of withdrawal. The banks know that the fraction ``\\gamma`` of people will withdraw in period 1 because they are hungry and `` 1 \\gamma `` will withdraw in period 2. The bank needs to make sure that ``c 2 \\geq c 1``, otherwise late agents have an incentive to withdraw their deposits in period 1 and store them until period 2 . We assume that banks act on a competitive market, so agents will only choose to deposit in a bank that provides the optimal contract . Thus, banks will only operate if they maximize ```math \\begin align & \\max x, \\ell \\in 0,1 \\gamma u c 1 1 \\gamma u c 2 \\\\ &\\begin aligned \\text such that && \\gamma c 1 & 1 x ℓ r x \\\\ && 1 \\gamma c 2 & 1 ℓ R x \\\\ && c 2 &≥ c 1 \\end aligned \\end align ``` This problem is the same as the planner's problem , except that the incentive compatibility constraint IC ``c 2 \\geq c 1`` is added. It turns out, that under some conditions for the utility function `u` the IC will always be satisfied. So the presence of banks will lead to the welfare maximizing outcome in this model. \"\"\" md\"\"\" 2. Financial fragility Bank runs What will happen, if a fraction ``\\tilde \\omega \\omega`` withdraws money in period ``t 1``? The bank will have to dig up some of its potatoes to fill the gap. This means that the payout in period two will have to be reduced there are not enough potatoes left . As soon as the expected payout ``\\tilde c 2`` becomes small enough, there will be a bank run . If the ``\\tilde c 2 c 1`` the incentive compatibility constraint is violated and the \"late\" types will start to withdraw their money. \"\"\" begin x opt, ℓ opt, c₁ opt, c₂ opt social optimum liquid ℓ 1 x opt ℓ x opt r withdrawal ω c₁ opt ω end md\"additional withdrawers ε bind ε Slider 0 0.01 1 γ , default 0.05, show value true \" ω γ ε liquid ℓ opt withdrawal ω withdrawal ω ≤ liquid ℓ opt function realized payout ω, opt ib payable 0.0, ib deposit 0.0 x opt, ℓ opt, c₁ opt, c₂ opt opt liquid ℓ 1 x opt ℓ x opt r ib payable withdrawal ω c₁ opt ω shortfall0 max withdrawal ω liquid 0.0 , 0.0 if 0 ≤ shortfall0 ≤ ib deposit ib withdrawal shortfall0 else shortfall ib deposit ib withdrawal ib deposit end info shortfall0 shortfall shortfall0 ib withdrawal ℓ new clamp shortfall x opt r , 0.0, 1.0 c₁ new c₁ x opt, ℓ new, γ max γ, ω c₂ new c₂ x opt, ℓ new, γ max γ, ω if c₂ new c₁ new && ω 1.0 IC violated everybody withdraws early ω̃ 1.0 return ω, delete realized payout ω̃, opt , ω ... end ω, c₁ opt, c₂ opt, ℓ opt, c₁ new, c₂ new, ℓ new end realized payout ω, social optimum let ε 0.2 ib deposit 0.2 bank1 realized payout γ ε, social optimum ib deposit bank2 realized payout γ ε, social optimum ib deposit chain bank1 bank2 begin DataFrame select ω, ℓ new, ib withdrawal end end md\" hidden cell \" sliders 1.1, 0.4. 0.5 md\"\"\" 3. Risk sharing in the interbank market Now, let's suppose that there are ``N`` banks. All banks face the same decision problem, so they will offer the same deposit contract `` c 1, c 2 ``. Agents will randomly pick one of the two banks the outcome will be the same as before. Let ``\\omega i`` be the fraction of bank ``i``'s customers that withdraws early. The average fraction of withdrawers is ``\\gamma \\frac 1 N \\sum i 1 ^N \\omega i``. We assume that there is idiosychratic i.e. bank specific risk , but no aggregate risk . That is, banks don't know ``\\omega i``, but they know ``\\gamma``. Can the social optimum still be achieved? TL DR Yes, if there is an interbank market \"\"\" md\"\"\" Banks can serve at most ``\\gamma`` early withdrawals without liquidating assets. If they are faced with ``\\omega i \\gamma`` early customers, the bank as excess liquidity needs of `` \\omega i \\gamma c 1`` in period 1. If faced with ``\\omega i \\gamma`` early customers, the bank has excess liquidity in period 1, but a shortage of funds of `` 1 \\gamma 1 \\omega i c 2 \\omega i \\gamma c 2`` in period 2. Since ``0 \\leq \\omega i \\leq 1``, the maximal liquity need in period 1 is ```math 1 \\gamma c 1 ``` Suppose banks can deposit at the same terms as agents. So for each unit deposited, agents get ``c 1`` if withdrawn in period ``t 1`` and ``c 2`` if withdrawn in period ``t 2``. Now suppose that each has total deposits of ``\\bar y 1 \\gamma``. \"\"\" md\"\"\" illustration missing \"\"\" let ib deposit 0.2 ω γ 0.2 shortfall0 max ω c₁ opt γ c₁ opt, 0.0 if 0 ≤ shortfall0 ib deposit ib withdrawal shortfall0 c₁ c₁ opt ℓ 0.0 shortfall 0.0 elseif shortfall0 ≤ ib deposit x opt r ib withdrawal ib deposit shortfall shortfall0 ib withdrawal ℓ shortfall x opt r γ ω c₁ c₁ opt else ib withdrawal ib deposit ℓ 1.0 c₁ liquid ℓ ib withdrawal ω end ζ excess liquidity liquid ℓ ib withdrawal ω c₁ ζ next next period c₂ opt ω γ ζ next, ib withdrawal, ω, ℓ, c₁, ζ, shortfall0, shortfall end md\"\"\" Exercise Avoiding a bank run \"\"\" md\"\"\" Consider the setup of Allen & Gale with banks ``i \\in \\ 1, 2, 3, 4\\ ``. Banks know that a fraction ``\\gamma`` of the population are early types . In the social optimum, banks offer deposit contracts `` c 1, c 2 ``. The fraction of early types ``\\omega i`` in each bank is random. There are three possible states ``S j \\omega 1j , \\omega 2j , \\omega 3j , \\omega 4j `` ```math \\begin align S 1 & \\gamma, \\gamma, \\gamma, \\gamma \\\\ S 2 & \\gamma \\varepsilon, \\gamma \\varepsilon, \\gamma \\varepsilon, \\gamma \\varepsilon \\\\ S 3 & \\gamma \\varepsilon, \\gamma \\varepsilon, \\gamma \\varepsilon, \\gamma \\varepsilon \\\\ \\end align ``` The states are shown in the figure below. The red dots mean \"more early customers\" ``\\gamma \\varepsilon`` , the green dots mean \"more late customers\" ``\\gamma \\varepsilon`` and the gray dots mean \"no shock\" ``\\gamma`` . \"\"\" states none, none, none, none , early, early, late, late , late, late, early, early , md\"\"\" Select state the ``i`` in ``S i`` bind i state NumberField 1 length states . \"\"\" md\"\"\" 👉 a What is the minimal number of edges that will prevent a bank run in period ``t 1`` in state ``S 1``? Explain briefly. \"\"\" answer a md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 b What is the minimal number of edges that will prevent a bank run in period ``t 1`` in all possible states? Explain and adjust the adjacency matrix `G minimal` accordingly. \"\"\" G minimal 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 answer b md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 c Assume that your minimal network from a has uniform weights . What is the lower bound ``y \\text min `` for that weight that will allow the socially optimal allocation in all states? \"\"\" answer c md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 d What will happen if ``y y \\text min ``? \"\"\" answer d md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 e Assume that there is a complete interbank network with uniform weights to ensure the socially optimal allocation in all states. What would be an alternative state ``S 4``, where the given network has a worse outcome than the empty network? \"\"\" answer e md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Functions for exercise \"\"\" exX let S states i state n length S node styles title \"shock\", df DataFrame label string. early, late, none , color \"lightgreen\", \"tomato\", \"lightgray\" df chain begin DataFrame bank 1 n, label string. S leftjoin , node styles.df, on label end n, color df.color, node styles end function node legend figpos, node styles, title \"\" elems MarkerElement color, markersize 15, marker circle for color ∈ node styles.color if length title 0 title tuple else title tuple title, end Legend figpos, elems, node styles.label, title tuple... orientation horizontal, titleposition left, framevisible false end md\"\"\" Appendix \"\"\" fonts regular texfont , bold texfont bold , italic texfont italic fig attr size 350, 300 figure padding 3, fonts, size fig attr xscale 1, yscale xscale figure padding 3, size xscale 200, yscale 200 , fonts let function obj x γ γ c₁ 1 x x r c₂ 1 x x R 𝔼U c₁, c₂ γ end res maximize obj, 0, 1 x opt Optim.maximizer res info x opt xx 0.0 0.05 1.0 fig Figure fig attr 1.2, 1 ... ax Axis fig 1,1 , xlabel L\"fraction invested x \", ylabel \"expected utility\" lines ax, xx, obj. xx vlines ax, x opt, linestyle dash, loose , color gray fig end let x opt, ℓ opt social optimum xx range 0.001, 0.99, 100 ℓℓ 0.0 0.05 1.0 fig Figure fig attr 1.2, 1 ... ax Axis fig 1,1 , xlabel \"fraction invested\", ylabel \"expected utility\", title L\"expected utility for ℓ^ % round ℓ opt, digits 4 \" objj obj x, ℓ for ℓ ∈ ℓℓ, x ∈ xx ax Axis3 fig 1,1 , xlabel \"fraction invested\", ylabel \"fraction liquidated\", zlabel \"expected utility\" surface ax, ℓℓ, xx, objj lines ax, xx, obj x, ℓ opt for x ∈ xx vlines ax, x opt, linestyle dash, loose , color gray fig end let x opt, ℓ opt social optimum xx range 0.05, 0.95, 100 fig Figure fig attr 1.5, 1 ... ax1 Axis fig 1,1 , xlabel L\"fraction invested x \" ax2 Axis fig 2,1 , xlabel L\"fraction invested x \" lines ax1, xx, c₁. xx, ℓ opt , label L\"c 1\" lines ax1, xx, c₂. xx, ℓ opt , label L\"c 2\" lines ax2, xx, 𝔼U. c₁. xx, ℓ opt , c₂. xx, ℓ opt γ , label L\"\\bbE U\" vlines . ax1, ax2 , x opt, linestyle dash, loose , color gray axislegend. ax1, ax2 linkxaxes ax1, ax2 hidexdecorations ax1, grid false fig end let df map 0 0.005 1 do ω ε ω γ ε, realized payout ω, social optimum ... end | DataFrame chain df begin select Not ω stack Not ε transform astable begin tmp split variable, \" \" variable latexstring replace tmp 1 , \"₁\" \" 1\", \"₂\" \" 2\" mod tmp 2 \"opt\" ? \"planned\" \"realized\" end data mapping ε L\"additional withdrawers ε \", value, color variable, linestyle mod \"\" visual Lines draw figure fig attr 2.0, 1.1 end end minimal extend limits 0.1, hidespines true, kwargs... xgridvisible false, xticksvisible false, xticklabelsvisible false, ygridvisible false, yticksvisible false, yticklabelsvisible false, leftspinevisible hidespines, rightspinevisible hidespines, topspinevisible hidespines, bottomspinevisible hidespines, xautolimitmargin extend limits, extend limits , yautolimitmargin extend limits, extend limits , kwargs... let g SimpleDiGraph G minimal fig, ax, graphplot g ilabels vertices g , node color exX.color, layout Shell , figure fig attr 1.3, 1.1 , axis minimal title L\"interbank network in state S % i state \", extend limits 0.1 node styles exX if ismissing node styles title, df node styles node legend fig end 1,1 , df, title end rowgap fig.layout, 1 fig end md\"\"\" Package environment \"\"\" md\"\"\" Graphs \"\"\" md\"\"\" Numerical Methods \"\"\" md\"\"\" Data \"\"\" md\"\"\" Plotting \"\"\" md\"\"\" Other \"\"\" TableOfContents md\"\"\" Assignment infrastructure \"\"\" function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ', ' ', '.', ',', ' ', ' ', '\"', ' ', ' ', '\\'' length filter \"\" , words end test wordcount \" Hello, it's me. \" 4 test wordcount \"This doesn't really matter.\" 5 show words answer md\" approximately wordcount answer words \" show words answer a show words answer b show words answer c show words answer d show words answer e function show words limit answer, limit count wordcount answer if count 1.02 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end "},{"url":"financial-networks/systemic-risk/","title":"Systemic risk in financial networks","description":"","tags":["financial-networks"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 5 section 2 order 2 title \"Systemic risk in financial networks\" layout \"layout.jlhtml\" tags \"financial networks\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using SparseArrays using Makie LinePattern, Pattern using MarkdownLiteral markdown, mdx using LinearAlgebra dot using HypertextLiteral using StructArrays using PlutoUI PlutoUI, TableOfContents, details, Slider, CheckBox, Select, NumberField using StatsBase weights using CategoricalArrays using DataAPI refarray using Graphs, SimpleWeightedGraphs using NetworkLayout using LinearAlgebra I using PlutoTeachingTools using Chain chain using GeometryBasics Rect, Vec2f using DataFrames, DataFrameMacros using Roots find zero using Colors colorant str using Statistics mean using GraphMakie using NamedTupleTools using CairoMakie key str, lift, L str using CairoMakie, AlgebraOfGraphics, Colors using LaTeXStrings begin fonts regular CairoMakie.Makie.MathTeXEngine.texfont , bold CairoMakie.Makie.MathTeXEngine.texfont set theme fonts using Makie using Makie.LaTeXStrings using Makie automatic end using PlutoTest test md\"\"\" `systemic risk.jl` | Version 2.5 | content updated 25 Nov 2024, packages updated 4 Oct 2026 \"\"\" ChooseDisplayMode md\"\"\" need space? bind need space CheckBox default false \"\"\" space need space 10 md\"\"\" Systemic Risk in Financial Networks based on Acemoglu, Ozdaglar & Tahbaz Salehi, 2015 https www.aeaweb.org articles?id 10.1257 aer.20130456 , American Economic Review \"\"\" md\"\"\" Overview Contagion on Financial Networks \"\"\" nisl str \"number of components \" md\"\"\" Plan for the lecture Goal Understand model and key results of Acemoglu, Ozdaglar & Tahbaz Salehi 2015 \"\"\" md\"\"\" 1. Model Setup Model I Banks \"\"\" md\"\"\" Model II Firms fixed initial size dividend ``\\delta a ε`` paid to bank ``ε`` is a shock fraction ``\\tilde ℓ`` can be liquidated recover ``\\tilde ℓ ζ A`` final pay off `` 1 \\tilde ℓ A`` \"\"\" dividend a , ε max a ε, 0.0 recovery ζ, A , ℓ ℓ ζ A function cashflow₁ firm, ε, ℓ div dividend firm, ε rec recovery firm, ℓ cf div rec cf, div, rec end md\"\"\" 2. Payment equilibrium \"\"\" md\"\"\" size of shock bind ε cash Slider 0.0 0.05 1.0, show value true, default 0.0 show illiquid firm value ``A`` bind show illiquid CheckBox default false recovery rate ``ζ`` bind recovery rate Slider 0 0.1 0.5, show value true, default 0.0 \"\"\" md\"\"\" 3. Financial Contagion \"\"\" md\"\"\" Notable insights 1. Let ``\\tilde y`` and ``\\hat y`` be two regular financial networks with `` y, n ``. Let ``\\varepsilon`` be big enough to wipe out all banks in ``\\tilde y``. Then ... 3. Let's start with an ``\\varepsilon`` small enough, so that no bank defaults. What will happen to the number of defaults as we increase ``\\varepsilon``? Ring step wise increase in defaults, Complete bang bang \"\"\" md\"\"\" 4. Stability and Resilience \"\"\" md\"\"\" Result 1 More interbank lending leads to less stability and less resilience Formally, for a given regular financial network `` y ij `` let ``\\tilde y ij \\beta y ij `` for ``\\beta 1``. Financial network ``\\tilde y`` is less resilient and less stable see Proposition 3 . Proposition 3 More interbank lending leads to a more fragile system. For a given network topology, the defaults are increasing in ``\\bar y``. \"\"\" md\"\"\" Result 2 Densely connected networks are robust, yet fragile Our results thus confirm a conjecture of Andrew Haldane 2009, then Executive Director for Financial Stability at the Bank of England , who suggested that highly interconnected financial networks may be “robust yet fragile” in the sense that “within a certain range, connections serve as shock absorbers and connectivity engenders robustness.” However, beyond that range, interconnections start to serve as a mechanism for the propagation of shocks, “the system flips to the wrong side of the knife edge,” and fragility prevails. Upto some ``\\varepsilon^ ``, the shock does not spread Above this value, all banks default This is an example for a phase transition it flips from being the most to the least stable and resilient network Compare Propositions 4 and 6 Proposition 4 For small shocks and big ``\\bar y``, the complete network ist the most resilitient and most stable financial network and the ring is the least resilient and least stable. Proposition 6 For big shocks, the ring and complete networks are the least resilient and least stable. \"\"\" A 0.5 md\"\"\" Assignment \"\"\" md\"\"\" Task 1 6 Points \"\"\" md\"\"\" 👉 1.1 | 2 points Consider financial network ``\\tilde y``. What is the minimal number of shocks ``\\tilde p`` that have to occur to wipe out the whole financial system. Which banks have to be hit? How big would the shocks ``\\tilde \\varepsilon`` have to be? \"\"\" answer11 md\"\"\" Your answer goes here ... You can type math like this ``\\tilde p 17``, ``\\tilde \\varepsilon 1.1`` \"\"\" md\"\"\" 👉 1.2 | 2 points Consider financial network ``\\hat y``. What is the minimal number of shocks ``\\hat p`` that have to occur to wipe out the whole financial system. Which banks have to be hit? How big would the shocks ``\\hat \\varepsilon`` have to be? \"\"\" answer12 md\"\"\" Your answer goes here ... You can type math like this ``\\hat p 17``, ``\\hat \\varepsilon 1.1`` \"\"\" md\"\"\" 👉 1.3 | 2 points Now consider ``\\varepsilon \\max\\ \\tilde \\varepsilon, \\hat \\varepsilon \\ `` and ``p 1``. Which network is more stable? Which network is more resilient? \"\"\" answer13 md\"\"\" Your answer goes here ... You can type math like this ``\\hat p 17``, ``\\tilde \\varepsilon 1.1`` \"\"\" md\"\"\" Task 2 4 Points Consider the model of systemic risk by Acemoglu, Ozdaglar & Tahbaz Salehi 2015 with n 5 banks. There are two scenarios that differ by the structure of the financial network \\tilde y vs. \\hat y . Both \\tilde y and \\hat y are regular financial networks with parameter y . \"\"\" md\"\"\" Each bank owns a project that pays z i a \\varepsilon i in the intermediate period. \\varepsilon i 0 is a shock. Let \\tilde p be the minimal number of shocks, and \\tilde \\varepsilon be the minimal shock size that can wipe out the whole system that is, a simultaneous default of all banks under the financial network \\tilde y . \"\"\" md\"\"\" 👉 2.1 | 2 points What is \\tilde p ? Explain which banks would have to be hit to wipe out the whole system. \"\"\" answer21 md\"\"\" Your answer goes here ... You can type math like this ``p 17``, ``\\varepsilon 1.1`` \"\"\" md\"\"\" 👉 2.2 | 2 points Let \\delta 0 be very small and shock size \\varepsilon' \\in \\tilde \\varepsilon \\delta, \\tilde \\varepsilon . Conditional on p' 1 and \\varepsilon' , which network is more resilient and which network is more stable? Explain. \"\"\" answer22 md\"\"\" Your answer goes here ... You can type math like this ``p 17``, ``\\varepsilon 1.1`` \"\"\" md\"\"\" Before you submit ... 👉 Make sure you have added your names and your group number in the cells below. 👉 Make sure that that all group members proofread your submission especially your little essays . 👉 Go to the very top of the notebook and click on the symbol in the very top right corner. Export a static html file of this notebook for submission. The source code is embedded in the html file. \"\"\" group members firstname \"Ella Louise\", lastname \"Flores\" , firstname \"Padraig\", lastname \"Cope\" , firstname \"Christy\", lastname \"Denton\" group number 99 if group number 99 || group members 1 .firstname \"Ella Louise\" && group members 1 .lastname \"Flores\" md\"\"\" danger \"Note \" Before you submit , please replace the randomly generated names above by the names of your group and put the right group number in the appropriate cell. \"\"\" end md\"\"\" Task 3 not graded Avoiding a bank run see notebook `risk sharing.jl` \"\"\" md\"\"\" Objects for Task 2 \"\"\" md\"\"\" Appendix \"\"\" TableOfContents md\"\"\" Helpers \"\"\" md\"\"\" Packages \"\"\" PlutoUI.details md\"\"\" HTML Helpers \"\"\" htl \" style .blurry text color transparent text shadow 0 0 5px rgba 0,0,0,0.5 white space nowrap .blurry text hover color transparent text shadow 0 0 0px rgba 0,0,0.5 white space nowrap style \" blur text htl \"\"\" span class \"blurry text\" text span \"\"\" md fig htl \"\"\" md\" Financial network banks linked by interbank lending 1. How do shocks propagate on a financial network? 2. How should a network look so that shocks don't spread? \" md\" ring vs complete `` γ `` bind γ Slider 0 0.1 1.0, show value true, default 0.5 shock to bank ``1`` `` ε `` bind ε Slider 0.0 0.05 1, show value true, default 0.0 blur nisl str bind n components Slider 1 3, show value true, default 1 \" \"\"\" strike text htl \" s text s \" vertical space space space htl \"\"\" p style \"line height space cm \" br p \"\"\" vertical space vertical space vertical space vertical space vertical space function TwoColumns a, b, α 50, β 100 α PlutoUI.ExperimentalLayout.Div PlutoUI.ExperimentalLayout.Div a style Dict \"flex\" \"0 0 α%\" PlutoUI.ExperimentalLayout.Div b style Dict \"flex\" \"0 0 β%\" style Dict \"display\" \"flex\", \"flex direction\" \"row\" end TwoColumns md\"\"\" default on interbank market ``\\implies`` lower interbank receivables for other banks ``\\implies`` reduces distance to default \"\"\", md\"\"\" | variable | value | | | | | ring vs complete ``γ`` | bind γ2 Slider 0 0.01 1, default 0.5, show value true | | shock ``ε`` | bind ε Slider 0 0.1 2, default 0.0, show value true | details \"Change parameters ...\", md\" | variable | value | | | | | dividend ``a`` | bind a Slider 0 0.01 1, default 0.7, show value true | | recovery rate ``ζ`` | bind ζ Slider 0 0.01 1, default 0.3, show value true | | external | | | cash ``c`` | bind c Slider 0 0.1 2, default 1.2, show value true | | deposits ``ν`` | bind ν Slider 0.0 0.1 2, default 1.8, show value true | | internal | | | interbank ``y`` | bind y Slider 0 0.1 2, default 1.0, show value true | \" \"\"\", 45 function OneColumn a, α 60 PlutoUI.ExperimentalLayout.Div PlutoUI.ExperimentalLayout.Div a style Dict \"flex\" \"0 0 α%\" style Dict \"display\" \"flex\", \"flex direction\" \"row\" end md\"\"\" Theorems, etc \"\"\" function theorem header type, number, title out type if isnothing number && length number 0 out out \" \" string number end if isnothing title && length title 0 out out \" \" string title end out end begin admonition kind, title, text Markdown.MD Markdown.Admonition kind, title, text proposition text number nothing, title nothing admonition \"correct\", theorem header \"Proposition\", number, title , text corollary text number nothing, title nothing admonition \"note\", theorem header \"Corollary\", number, title , text definition text number nothing, title nothing admonition \"warning\", theorem header \"Definition\", number, title , text assumption text number nothing, title nothing admonition \"danger\", theorem header \"Assumption\", number, title , text danger text, title \"Danger\" admonition \"danger\", title, text correct text, title \"Correct\" admonition \"hint\", title, text end Foldable \"Take away\", proposition md\"\"\" Small Shocks more complete ``\\implies`` fewer defaults Large shocks split up network ``\\implies`` fewer defaults Foldable \"in their words\", md\" Not all financial systems, however, are as fragile in the presence of large shocks. In fact, as part `` ii `` shows, for small enough values of ``δ``, any ``δ`` connected financial network is strictly more stable and resilient than both the complete and the ring networks. The presence of such weakly connected components in the network guarantees that the losses—rather than being transmitted to all other banks—are borne in part by the distressed bank’s senior creditors.\" \"\"\", title \"Acemoglu, Ozdaglar & Tahbaz Salehi 2015 \", md\"\"\" Packages \"\"\" md\"\"\" Line patterns in AlgebraOfGraphics \"\"\" hatch dict Dict Vec2f 1 , \\ Vec2f 1, 1 , Vec2f 1, 0 , | Vec2f 0, 1 , x Vec2f 1 , Vec2f 1, 1 , Vec2f 1, 0 , Vec2f 0, 1 hatches \\, , , |, x, line pattern hatch width 1.5, tilesize 10,10 , linecolor black, color white Makie.LinePattern direction hatch dict Symbol hatch , width, tilesize, linecolor, background color color md\"\"\" FinancialNetworks.jl \"\"\" md\"\"\" Payments and Equilibrium \"\"\" function repay c, ν , x, y , firm, ε assets ℓ x c cashflow₁ firm, ε, ℓ .cf if ν y ≤ assets 0.0 out ℓ 0, y pc 1.0, ν pc 1.0 elseif assets 0.0 ν y ≤ assets 1.0 ℓ find zero ℓ ν y assets ℓ , 0.0, 1.0 out ℓ, y pc 1.0, ν pc 1.0 else ℓ 1.0 ass assets ℓ if ν ≤ ass ν y out ℓ, y pc ass ν y, ν pc 1.0 else assets ν out ℓ, y pc 0.0, ν pc ass ν end end out..., assets assets out.ℓ , cashflow₁ firm, ε, out.ℓ ..., firm pc 1 out.ℓ, x, y y out.y pc end md\"\"\" Visualize bank firm network \"\"\" function edge attr df g A adjacency matrix g n size A, 1 df map edges g do src, dst, weight src, dst, weight end | DataFrame norm const sum A n chain df begin transform edge width √ weight norm const 1.5, arrow size √ weight norm const 14 end df end function edge attrs g df edge attr df g df.edge width, df.arrow size end function add legend figpos cols, kwargs... dict lightgray \"solvent bank\" if orange ∈ cols push dict, orange \"insolvent\" end if red ∈ cols push dict, red \"bankrupt\" end elements MarkerElement marker circle, strokewidth 1, markersize 20, color c for c in first. dict Legend figpos, elements, last. dict kwargs... figpos end md\"\"\" Visualize bank balance sheet \"\"\" balance sheet palette function balance sheet palette palette df DataFrame label \"external\", \"interbank\", \"firm\", \"liquidated\", \"shortfall\" , color Makie.wong colors 5, 2, 4, 3, ..., Makie.Pattern \" \" palette df.label . palette df.color end function balance sheet df c, x, div, ill, rec, ν paid, y paid, shortfall receivable DataFrame color \"external\", val c, lab L\"cash c \" , color \"interbank\", val x, lab L\"IB deposit x \" , color \"firm\", val div, lab L\"dividend δ \" , color \"firm\", val ill, lab \"illiquid\" , color \"liquidated\", val rec, lab L\"recovered ρ \" , payable DataFrame color \"external\", val ν paid, lab L\"deposits ν \" , color \"interbank\", val y paid, lab L\"IB debt y \" , color \"shortfall\", val shortfall, lab \"\" , nt receivable, payable vcat nt..., source side collect string. keys nt end function balance sheet df new bank, firm, x, y ε cash get bank, ε, 0.0 c₀ bank.c c max c₀ ε cash, 0.0 bank c, bank.ν y pc, ν pc, ℓ, rec, div repay bank, x, y , firm, ε a, A firm ν, c bank y paid y pc y ν paid ν pc ν shortfall 1 ν pc ν 1 y pc y ill 1 ℓ A df balance sheet df c, x, div, ill, rec, ν paid, y paid, shortfall bs max max A a x c₀, y ν df, bs max, ℓ, shortfall end function visualize simple balance sheet bank, firm, x, y show illiquid true, fontsize 15 df, bs max, ℓ, shortfall balance sheet df new bank, firm, x, y transform df, stack lab \"illiquid\" ? lab color if show illiquid || ℓ ≈ 1 subset df, lab ≠ \"illiquid\" end if ℓ firm.ζ ≈ 0 subset df, color ≠ \"liquidated\" end subset df, val 0 transform df, subset val 0.3 , lab \"\" df.color categorical df.color ordered chain begin \"external\", \"interbank\", \"firm\", \"liquidated\", \"shortfall\" filter ∈ unique df.color , end levels df.color, ordered df.stack categorical df.stack ordered chain begin \"external\", \"interbank\", \"firm\", \"liquidated\", \"illiquid\", \"shortfall\" filter ∈ unique df.stack , end levels df.stack, ordered plt data df mapping side sorter \"receivable\", \"payable\" \"\", val \"\", stack stack, color color \"\", bar labels lab verbatim visual BarPlot, flip labels at 0, label size fontsize, strokewidth 0.5 plt, bs max end function visualize simple balance sheet args... figure , legend , kwargs... plt, bs max visualize simple balance sheet args... kwargs... if isempty legend legend position top, titleposition left, framevisible false end fg draw plt, scales Color palette balance sheet palette axis limits nothing, nothing, 0, 1.05 bs max , , figure, legend, rowgap fg.figure.layout, 1 fg end balance sheet let c 0.7 ν 1.2 x 1.0 a 0.7 y 1.0 A 1.0 ζ recovery rate shortfall max y ν c ε cash x a , 0 figure size 0.8 . 400, 350 , fontsize 15, figure padding 3 firm a, A, ζ visualize simple balance sheet c, ν, ε ε cash , firm, x, y figure, show illiquid end TwoColumns md\"\"\" Bank external debt deposits ``ν`` external assets cash ``c`` borrowing and lending on financial network see below investment in strike \"loan to\" firm see below Financial network ``n`` banks ``y ij 0 ⟺`` bank ``i`` has debt with bank ``j`` the network is regular \\ ``\\forall i \\sum j y ij \\sum j y ji \\bar y`` \"\"\", balance sheet, 62 TwoColumns mdx \"\"\" br Banks' choice 1. payables receivables repay all debt solvent 2. not enough? liquidate part of the firm ``ℓ 0`` insolvent 3. still not enough? partially default on interbank debt bankrupt 4. still not enough? partially default on external liabilities ``ν`` bankrupt \"\"\" , balance sheet, 65 function visualize simple balance sheet figpos, legpos, args... legend , kwargs... plt, bs max visualize simple balance sheet args... kwargs... fg draw figpos, plt, scales Color palette balance sheet palette legend legpos, fg legend... end function balance sheet df ν, c , a, A, ζ , ℓ, y pc, ν pc, x, y, div, rec y paid y y y y pc ν paid ν pc ν shortfall 1 ν pc ν 1 y pc y ill 1 ℓ A df balance sheet df c, x, div, ill, rec, ν paid, y paid, shortfall subset df, lab ≠ \"illiquid\" bs max max a x c, y ν 1.05 df, bs max isfinite bs max ? bs max zero bs max end function visualize balance sheets figpos, bank df, banks, firm use palettes true bank dfs balance sheet df banks i , firm, bank df i, for i ∈ 1 length banks | StructArray combined bank df vcat bank dfs.df..., source bank transform combined bank df, bank \"bank bank \" bs max maximum bank dfs.bs max plt chain combined bank df begin data mapping side sorter \"receivable\", \"payable\" \"\", val \"\", color color \"\", stack color, col bank visual BarPlot, strokewidth 0.5 end color scale use palettes ? scales Color palette balance sheet palette scales fg draw figpos 2,1 , plt, color scale axis limits nothing, nothing, 0, 1.05 bs max , legend figpos 1,1 , fg, orientation horizontal, titleposition left, framevisible false nothing end function visualize balance sheets out, banks, firms, shares fig Figure visualize balance sheets fig 1,1 , out, banks, firms, shares fig end md\"\"\" NetworkUtils.jl \"\"\" md\"\"\" Regular interbank market \"\"\" weighted adjacency matrix graph Graphs.weights graph . adjacency matrix graph . 0 function payments received promises, pc served Y weighted adjacency matrix promises vec pc served' Y end function payments promised promises Y weighted adjacency matrix promises dropdims sum Y, dims 2 , dims 2 end function iterate payments banks, promises, pc served, firm, εs firm, ℓs zeros length banks ys payments promised promises x new copy y out map enumerate banks do i, bank compute repayment xs payments received promises, pc served internal x xs i , y ys i rpy repay bank, internal, firm, εs firm i y pc, ℓ rpy ℓs i ℓ pc served i y pc return bank's choices bank i, rpy... end pc served, out, ℓs end function equilibrium banks, promises, firm, ε firms maxit 100 n banks length banks pc served ones n banks ℓs zeros n banks for it ∈ 1 maxit ℓs old copy ℓs pc served old copy pc served pc served, out, ℓs iterate payments banks, promises, pc served, firm, ε firms, ℓs converged pc served old ≈ pc served && ℓs old ≈ ℓs if converged || it maxit bank df DataFrame out return bank df, it, success it maxit, banks end end end function is regular Y vec sum Y, dims 1 ≈ vec sum Y, dims 2 end function is regular Y, ȳ is regular Y && mean sum Y, dims 1 ≈ ȳ end initial network interbank market adjacency matrix interbank market.network updated network interbank market interbank market.payments function complete network n, ȳ Y fill ȳ n 1 , n, n for i in 1 n Y i,i 0.0 end Y end function CompleteNetwork n, ȳ SimpleWeightedDiGraph complete network n, ȳ end function ring network n, ȳ Y zeros n, n for i in 1 n 1 Y i, i 1 ȳ end if n 1 Y n, 1 ȳ end Y end function RingNetwork n, ȳ SimpleWeightedDiGraph ring network n, ȳ end function γ network n, ȳ, γ Y γ ring network n, ȳ 1 γ complete network n, ȳ end function γNetwork n, ȳ, γ SimpleWeightedDiGraph γ network n, ȳ, γ end function component network n components, n banks per component, ȳ, γ blocks γ network n banks per component, ȳ, γ for in 1 n components cat blocks...,dims 1,2 end function component network n banks AbstractVector, ȳ, γ blocks γ network n, ȳ, γ for n ∈ n banks cat blocks...,dims 1,2 end function ComponentNetwork n components, n banks per component, ȳ γ 0.0 Y component network n components, n banks per component, ȳ, γ SimpleWeightedDiGraph Y end function ComponentNetwork n banks AbstractVector, ȳ γ 0.0 Y component network n banks, ȳ, γ SimpleWeightedDiGraph Y end initial analysis let n banks 6 n firms n banks ν 2.3 c 2.4 banks ν, c max c i 1 ε , 0 for i ∈ 1 n banks firm ζ 0.0, a 0.0, A 0.5 εs zeros n banks ȳ 1.2 promises ComponentNetwork n components, n banks ÷ n components, ȳ γ γ bank df equilibrium banks, promises, firm, εs promises, banks, firm, bank df end transmission analysis let n components 1 n banks 3 banks ν, c max c i 1 ε, 0 for i ∈ 1 n banks firm ζ, a, A εs zeros n banks ȳ y IM ComponentNetwork n components, n banks ÷ n components, ȳ γ γ2 bank df equilibrium banks, IM, firm, εs banks, firm, IM, bank df end md\"\"\" Layout \"\"\" begin function points on circle n c Point 0, 0 , r 1, start 0 if n 0 Point2 else x range 0, 2, n 1 . start . 0.5 x x begin end 1 Point2. r sinpi. x , r cospi. x . Ref c end end function nested circles inner r 1.5, start 0 function g n nodes nv g outer n nodes inner points on circle inner points on circle outer r, start end end function componentwise circle g AbstractGraph kwargs... components connected components g componentwise circle components kwargs... end function componentwise circle components scale 2.5 nodes Int node locs Point2f N length components ncol ceil Int, sqrt N for i, component in enumerate components row, col fldmod1 i, ncol n length component append nodes, component append node locs, points on circle n, c Point scale col 1 , scale 1 row end node locs sortperm nodes end end function visualize bank firm network ax, IM, bank df r 1.4, start Makie.automatic, layout Makie.automatic, show firms true, kwargs... A adjacency matrix IM n banks nv IM if show firms n firms n banks shares I n firms big A A shares' 0 shares 0 I else big A A end g big A | SimpleWeightedDiGraph n banks Base.size A, 1 edge df chain g begin edge attr df transform subset src ≤ n banks, dst ≤ n banks , linestyle Makie.automatic transform subset dst n banks , edge width 0.5, arrow size 0.0, linestyle \" \" end arrow attr markersize edge df.arrow size edge attr linewidth edge df.edge width, edge df.linestyle node color ifelse. bank df.y pc . 1.0, red, ifelse. bank df.ℓ . 0.0, orange, lightgray nlabels string. 1 n banks node marker fill Circle, n banks if show firms nlabels nlabels \"F i\" for i ∈ 1 n firms node marker node marker fill Rect, n firms node color node color fill colorant\"limegreen\", n firms end start start Makie.automatic ? 1 n banks start layout layout Makie.automatic ? nested circles n banks start, r layout graphplot attr layout, edge attr, arrow attr, edge plottype beziersegments, kwargs... graphplot ax, g ilabels nlabels, node marker, node color, graphplot attr... unique node color end md\"\"\" Plotting helpers \"\"\" attr kwargs... arrow size 10, elabels distance 15, edge width 1, nlabels distance 10, kwargs... minimal extend limits 0.1, hidespines true, kwargs... xgridvisible false, xticksvisible false, xticklabelsvisible false, ygridvisible false, yticksvisible false, yticklabelsvisible false, leftspinevisible hidespines, rightspinevisible hidespines, topspinevisible hidespines, bottomspinevisible hidespines, xautolimitmargin extend limits, extend limits , yautolimitmargin extend limits, extend limits , kwargs... let IM, firm, banks, bank df transmission analysis fig Figure size 650, 180 , figure padding 3 visualize bank firm network Axis fig 1,1 minimal extend limits 0.1 ..., aspect DataAspect , IM, bank df start 1 8, show firms false visualize balance sheets fig 1,2 4 , bank df, banks, firm rowgap content fig 1,2 4 , 0 rowgap fig 1,2 4 .layout, 0 fig end fig attr xscale 1, yscale xscale figure padding 3, size xscale 200, yscale 200 out T1 let y 2.1 γ 0 n1 6 ỹ ComponentNetwork 3, n1 3, 5 , y γ ŷ ComponentNetwork n1, 2, 1, 1, 1 , y γ assert nv ỹ nv ŷ n nv ỹ layout n componentwise circle 1 n, n . 1 5 fig Figure fig attr 3.0, 1.0 ... ax1 Axis fig 1,1 minimal hidespines false, title L\"interbank market \\tilde y \" ... ax2 Axis fig 1,2 minimal hidespines false, title L\"interbank market \\hat y \" ... graphplot ax1, ỹ layout layout n1 , ilabels vertices ỹ , edge attrs ỹ ... graphplot ax2, ŷ layout layout n1 , ilabels vertices ŷ , edge attrs ŷ ... ỹ, ŷ, fig, n, y end out T1.fig markdown \"\"\" Consider the interbank networks ``\\\\tilde y`` and ``\\\\hat y`` of out T1.n banks as depicted above. For all non isolated banks the sum of interbank liabilities equal the sum of interbank claims ``y out T1.y `` . \"\"\" md\"\"\" For this exercise you can use the tool below, to simulate the payment equilibrium for a given interbank market, shock size, and the bank that is hit by the shock. Which bank is hit? ``i`` bind i T1 Slider 1 out T1.n, default 1, show value true Size of the shock ``\\varepsilon`` bind ε T1 Slider 0.0 0.1 3.0, show value true, default 1.0 Select ``\\tilde y`` or ``\\hat y`` bind IM T1 Select out T1.ỹ \"ỹ\", out T1.ŷ \"ŷ\" \"\"\" out T2 let ȳ 2.1 IM1 ComponentNetwork 3, 2 , ȳ γ 0.0 IM2 ComponentNetwork 3, 2 , ȳ γ 1.0 n1 nv IM1 n2 nv IM2 if n1 n2 n n1 else n n1, n2 end layout Shell fig Figure fig attr 2, 1 ... ax1 Axis fig 1,1 minimal hidespines false, title L\"interbank market \\tilde y \", extend limits 0.1 ... ax2 Axis fig 1,2 minimal hidespines false, title L\"interbank market \\hat y \", extend limits 0.1 ... graphplot ax1, IM1 ilabels vertices IM1 , layout, edge attrs IM1 ... graphplot ax2, IM2 ilabels vertices IM2 , layout, edge attrs IM2 ... IM1, IM2, fig, n end out T2.fig tool text md\"\"\" If you have understood the mechanics of the model, you should be able to solve these tasks without simulations. You can use the given tool to verify your answer. Which bank is hit? ``i`` bind i bank T2 Slider 1 out T2.n, default 1, show value true Size of the shock ``\\varepsilon`` bind ε T2 Slider 0.0 0.1 3.0, show value true, default 1.0 Select ``\\tilde y`` or ``\\hat y`` bind IM T2 Select out T2.IM1 \"ỹ\", out T2.IM2 \"ŷ\" \"\"\" function visualize bank firm network IM, bank df figure fig attr , add legend false, hidespines true, kwargs... fig Figure figure... ax Axis fig 1,1 minimal hidespines, extend limits 0.1 ... cols visualize bank firm network ax, IM, bank df kwargs... if add legend vertical add legend fig ,end 1 cols, orientation vertical, framevisible false colgap fig.layout, 1 elseif add legend add legend fig 0, cols, orientation horizontal, framevisible false rowgap fig.layout, 1 end fig | as svg end fig let promises, bank df initial analysis visualize bank firm network promises, bank df figure fig attr 1, 1.1 , start 1 6, show firms false, add legend true end TwoColumns md fig, fig, 62 TwoColumns md\"\"\" I. Model setup II. insolvency and bankruptcy in the payment equilibrium III. financial contagion IV. stability and resilience of financial networks more interbank lending leads to higher fragility densely connected networks are robust, yet fragile with big shocks , we want to have disconnected components V. Empirical relevance, Outlook \"\"\", fig, 65 let i i T1 IM IM T1 ε ε T1 n banks nv IM ν 3.0 c 0.0 ζ 0.1 A 3.5 a 3.0 shares I n banks banks ν, c c for i ∈ 1 n banks firm ζ, a, A εs zeros n banks εs i min ε, a bank df equilibrium banks, IM, firm, εs layout componentwise circle 1 6, 6 . 1 5 fig visualize bank firm network IM, bank df figure fig attr 1.6, 1.0 , hidespines false, start 1 6, layout, add legend true, show firms false rowgap fig.layout, 1 fig end tool fig let i i bank T2 ε4 0.4 IM IM T2 n banks nv IM ν 3.0 c 0.0 ζ 0.0 A 0.0 a 3.5 ε ε T2 shares I n banks banks ν, c for i ∈ 1 n banks firm ζ, a, A εs zeros n banks εs i min ε, a bank df equilibrium banks, IM, firm, εs layout Shell visualize bank firm network IM, bank df figure fig attr 1.4, 0.8 , hidespines false, start 1 6, layout, add legend vertical, show firms false end TwoColumns tool text, tool fig, 60 md\"\"\" `LaTeXStrings` as `bar labels` \"\"\" md\"\"\" Assignment infrastructure \"\"\" begin hint text Markdown.MD Markdown.Admonition \"hint\", \"Hint\", text almost text Markdown.MD Markdown.Admonition \"warning\", \"Almost there \", text still missing text md\"Replace `missing` with your answer.\" Markdown.MD Markdown.Admonition \"warning\", \"Here we go \", text keep working text md\"The answer is not quite right.\" Markdown.MD Markdown.Admonition \"danger\", \"Keep working on it \", text yays md\"Great \", md\"Yay ❤\", md\"Great 🎉\", md\"Well done \", md\"Keep it up \", md\"Good job \", md\"Awesome \", md\"You got the right answer \", md\"Let's move on to the next section.\" correct text rand yays Markdown.MD Markdown.Admonition \"correct\", \"Got it \", text end members let names map group members do firstname, lastname firstname \" \" lastname end join names, \", \", \" & \" end md\"\"\" Assignment submitted by members group group number \"\"\" function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ', ' ', '.', ',', ' ', ' ', '\"', ' ', ' ', '\\'' length filter \"\" , words end test wordcount \" Hello, it's me. \" 4 test wordcount \"This doesn't really matter.\" 5 show words answer md\" approximately wordcount answer words \" function show words limit answer, limit count wordcount answer if count 1.02 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end "},{"url":"julia-basics/basic-julia/","title":"Basic Julia","description":"","tags":["julia-basics"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 1 section 1 order 1 title \"Basic Julia\" layout \"layout.jlhtml\" tags \"julia basics\" description \"\" using Markdown using InteractiveUtils using PlutoUI md\"\"\" `basic julia.jl` | Version 1.3 | content updated 5 Oct 2026, packages updated 4 Oct 2026 \"\"\" md\" A first glance at the Julia language This notebook briefly summarizes some of the basic Julia syntax that we will need for the problem sets. \" Markdown.MD Markdown.Admonition \"warning\", \"This notebook is taken from\", md\"\"\" Computational Thinking , a live online Julia Pluto textbook. computationalthinking.mit.edu https computationalthinking.mit.edu , original notebook https github.com mitmath 18S191 blob Fall20 lecture notebooks Basic%20Julia%20syntax.jl \"\"\" md\" Variables We can define a variable using ` ` assignment . Then we can use its value in other expressions \" x 3 y 2x md\"By default Julia displays the output of the last operation. You can suppress the output by adding ` ` a semicolon at the end. \" md\"We can ask what type a variable has using `typeof` \" typeof y md\" Functions\" md\"We can use a short form, one line function definition for simple functions \" f x 2 x md\"Typing the function's name gives information about the function. To call it we must use parentheses \" f f 10 md\"For longer functions we use the following syntax with the `function` keyword and `end` \" function g x, y z x y return z^2 end g 1, 2 md\" For loops\" md\"Use `for` to loop through a pre determined set of values \" let s 0 for i in 1 10 s s i end s end md\"Here, `1 10` is a range representing the numbers from 1 to 10 \" typeof 1 10 md\"Above we used a `let` block to define a new local variable `s`. But blocks of code like this are usually better inside functions, so that they can be reused. For example, we could rewrite the above as follows \" function mysum n s 0 for i in 1 n s s i end return s end mysum 100 md\" Conditionals `if`\" md\"We can evaluate whether a condition is true or not by simply writing the condition \" a 3 a 5 md\"We see that conditions have a Boolean `true` or `false` value. We can then use `if` to control what we do based on that value \" if a 5 \"small\" else \"big\" end md\"\"\"Note that the `if` also returns the last value that was evaluated, in this case the string `\"small\"` or `\"big\"`, Since Pluto is reactive, changing the definition of `a` above will automatically cause this to be reevaluated \"\"\" md\" Arrays\" md\" 1D arrays `Vector`s \" md\"We can make a `Vector` 1 dimensional, or 1D array using square brackets \" v 1, 2, 3 typeof v md\"The `1` in the type shows that this is a 1D array. We access elements also using square brackets \" v 2 v 2 10 md\"Note that Pluto does not automatically update cells when you modify elements of an array, but the value does change.\" md\"A nice way to create `Vector`s following a certain pattern is to use an array comprehension \" v2 i^2 for i in 1 10 md\" 2D arrays matrices \" md\"We can make small matrices 2D arrays with square brackets too \" M 1 2 3 4 typeof M md\"The `2` in the type confirms that this is a 2D array.\" md\"This won't work for larger matrices, though. For that we can use e.g.\" zeros 5, 5 md\"Note that `zeros` gives `Float64`s by default. We can also specify a type for the elements \" zeros Int, 4, 5 md\"We can then fill in the values we want by manipulating the elements, e.g. with a `for` loop.\" md\"A nice alternative syntax to create matrices following a certain pattern is an array comprehension with a double `for` loop \" i j for i in 1 5, j in 1 6 md\"\"\" Appendix \"\"\" TableOfContents "},{"url":"julia-basics/more-julia/","title":"More Julia","description":"","tags":["julia-basics"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 1 section 2 order 2 title \"More Julia\" layout \"layout.jlhtml\" tags \"julia basics\" description \"\" using Markdown using InteractiveUtils using DataFrames using DataFrameMacros using Chain chain using PlutoUI md\"\"\" `more julia.jl` | Version 1.1 | content updated 10 May 2022, packages updated 4 Oct 2026 | created by Daniel Schmidt https github.com danieljschmidt \"\"\" md\"\"\" More Julia \"\"\" md\"\"\" The purpose of this notebook is to make you familiar with Julia syntax that is frequently used in the course material. It also points out the peculiarities of Pluto notebooks. \"\"\" md\"\"\" Named tuples and keyword arguments Named tuples Like many other programming languages, Julia allows you to create tuples. The elements of tuples can be accessed by using the corresponding index \"\"\" standard tuple 1, 2 standard tuple 1 md\"\"\" Julia also has named tuples. Just like standard tuples, named tuples allow you to access an element using its index, but alternatively you can also access an element by its name. \"\"\" named tuple a 1, b 2 named tuple.a md\"\"\" This is convenient because it means that you do not need to remember if some parameter is the first element in a tuple or the second one. Below you can see an alternative way of creating named tuples that is frequently used in the course material \"\"\" let a 1 named tuple2 a, b 2 a is equivalent to a a end md\"\"\" Keyword arguments A similar syntax with a semicolon is used for keyword arguments that are identified by name and not by their position as normal function arguments \"\"\" function some function a, b 1 return a b end some function a 3, b 5 let a 3 some function a, b 5 a is equivalent to a a end md\"\"\" Vectorization with dot syntax You can apply a function to all elements of a vector by using the dot syntax \"\"\" 1,2,3 .^ 2 log. 1,2,3 md\"\"\" Note how Julia usually does things in a way that's mathematically consistent. Look at the following code. \"\"\" A ones 3, 3 exp A exp. A A^2 A .^ 2 md\"\"\" What would Python, R or Matlab do? \"\"\" md\"\"\" The pipe operator The pipe operator | makes it possible to write down nested function calls in a more readable way. For example, the two expressions below do the same thing \"\"\" round log named tuple.b named tuple.b | log | round md\"\"\" In case you use R The | operator in Julia is similar to the % % operator in R. \"\"\" md\"\"\" Unicode characters You can use Greek letters and other Unicode characters in your Julia code. For example, type \"\\alpha\" in the cell below without the quotation marks and press Tab on your keyboard. This should create an \\alpha symbol. \"\"\" md\"\"\" See the Julia documention https docs.julialang.org en v1 manual unicode input for a list of supported Unicode characters. For Greek letters, the abbreviations are the same as in LaTeX. \"\"\" md\"\"\" The \\in symbol An elegant way of writing loops is to use the \\in symbol instead of writing \"in\". The \\in symbol can be created by typing \"\\in\" and pressing Tab. \"\"\" i^2 for i ∈ 1 5 md\"\"\" Multiple dispatch Multiple dispatch means, that you can define specific methods or any combination of input types . \"\"\" struct Dog name end ╠═╡ struct Cat name owner end ╠═╡ makes this sound x Dog \"Bark bark, I am x.name \" makes this sound x Cat \"Meeoow, I am x.name , and I love x.owner \" makes this sound x \"bla bla\" ╠═╡ constantin Cat \"Constantin\", \"Franz Joseph\" ╠═╡ makes this sound 1 ╠═╡ makes this sound constantin ╠═╡ bello Dog \"Bello\" makes this sound bello md\"\"\" Working with data Here are a few simple examples of working with DataFrames in Julia. If you are familiar with pandas, dplyr or Stata, have a look at this cheatsheet https dataframes.juliadata.org stable man comparisons . Also, have a look at the documentation of DataFrameMacros.jl https jkrumbiegel.github.io DataFrameMacros.jl stable which makes working with DataFrames much more convenient. \"\"\" md\"\"\" Creating a `DataFrame` \"\"\" df1 DataFrame x 1 10 md\"\"\" Transforming mutating a column \"\"\" transform df1, x ByRow x sqrt x transform df1, sqrt x uses transform from DataFrameMacros.jl md\"\"\" The ``` chain``` macro \"\"\" md\"\"\" The ``` chain``` macro works similar to the pipe operator. In the code for this course, the ``` chain``` macro is often applied to data frames together with macros from the ```DataFrameMacros``` package. \"\"\" df2 DataFrame A 1,2,2,1 , B randn 4 md\"\"\" Consider the data frame above. Let's say you would like to add up the values in the B column separately for each value of A take the absolute value of the resulting sums of B values. Using the ``` chain``` macro, we can perform this task with relatively concise code \"\"\" chain df2 begin groupby A combine sum B , automatically named C sum B specify name transform abs C end md\"\"\" Without the ``` chain``` macro, the code would look like this \"\"\" begin df groups groupby df2, A df sum combine df groups, sum B , C sum B transform df sum, abs C end md\"\"\" Pluto notebooks General advice Press F1 to see shortcuts for Pluto notebooks. Ctrl Click on an underlined variable or function to jump to its definition. Use the Live docs in the bottom right corner to get more information about any Julia function or object. Check the Github wiki https github.com fonsp Pluto.jl wiki for more information on Pluto notebooks. Automated updating of cells When changing a function or variable, Pluto automatically updates all affected cells. For example, change the value of d to some other number and see how the following cell updates automatically \"\"\" d 5 d 10 md\"\"\" This is different from jupyter notebooks in which you have to update related cells manually. The automated updating the advantage that you do not have to keep in mind the order in which to evaluate cells. However, it can also be annoying if some of the affected cells take a long time to run. At the time of writing, there is no way to turn off the automated updating but you can always manually disable cells with long run times by clicking on the three dots in the top right corner of a cell. \"\"\" md\"\"\" Only one expression per cell Pluto notebooks only allow one expression per cell. If you nevertheless want to place several expressions into the same cell, you have to use a begin ... end block \"\"\" begin e 10 f e 5 end md\"\"\" Cannot reuse variable names \"\"\" md\"\"\" Use `let` blocks to specify variable names locally. \"\"\" let g 3 end g md\"\"\" Deactivate cells \"\"\" ╠═╡ sleep 5 ╠═╡ md\"\"\" Imported Packages \"\"\" TableOfContents g 2 g 1 "},{"url":"networks-basics/actors/","title":"Assignment 2: The Movie Database","description":"","tags":["networks-basics"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 2 section 4 order 4 title \"Assignment 2 The Movie Database\" layout \"layout.jlhtml\" tags \"networks basics\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using HTTP HTTP using Chain, DataFrameMacros, DataFrames using CSV using GraphMakie, CairoMakie begin using Graphs using SimpleWeightedGraphs using Graphs betweenness centrality, closeness centrality, degree centrality, eigenvector centrality, katz centrality end using SparseArrays sparse using CategoricalArrays categorical, levels, levelcode using Combinatorics combinations using NetworkLayout using Dates using PlutoUI using MarkdownLiteral markdown md\"`actors.jl` | Version 1.2 | content updated 5 Oct 2026, packages updated 4 Oct 2026 \" md\"\"\" Task 0 A movie you liked 1 point 👉 Pick a movie you liked other than Oppenheimer . \"\"\" md\"\"\" 👉 Explain why you liked it. \"\"\" answer0 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Task 1 Analyze the network 4 points 👉 Describe the network in terms of the measures that are discussed in lectures 1 and 2. You can look at the notebook first networks.jl and the section Language for network analysis for some inspiration. 👉 Interpret all results that you show. 👉 Be accurate but concise. Aim at no more than 300 words. You can spread your answer over multiple cells. Add code and text cells as it suits you. \"\"\" md\"\"\" NOTE It's ok to be below the word limit, but it's not ok to be above \"\"\" answer1 1 md\"\"\" Your answer goes here ... \"\"\" some analysis more analysis answer1 3 md\"\"\" ... write more ... add more cells if you need. If you want to use the word count above, adjust the cell below. \"\"\" md\"\"\" Task 2 Looking under the hood 3 points Now look at section Constructing the network of this notebook. 👉 What does the network show? What are the nodes? What are the edges? What are the edge weights? Answer briefly and concisely. \"\"\" answer2 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Task 3 Adding context 3 points The network shows the following actors in arbitrary order . \"\"\" md\"\"\" How can you measure the importance of an actor? 👉 Adjust the code block below so that the column `importance` holds your measure of importance. \"\"\" md\"\"\" The most important actors according this measure will be labeled in the plot below. \"\"\" md\"\"\" 👉 Explain your measure of importance. 👉 Describe what you see in the plot above. both in 250 words \"\"\" answer3 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Constructing the network \"\"\" md\"\"\" Step 1 Reading the data The data come from The Movie Database TMDB https www.themoviedb.org . This product uses the TMDB API but is not endorsed or certified by TMDB. \"\"\" url to data \"https raw.githubusercontent.com greimel networks course 29967411c0611c957e2c020b6982ef359dc01146 data prep movies \" actors df0 CSV.read HTTP.get url to data \"actors.csv\" .body, DataFrame movies df CSV.read HTTP.get url to data \"movies.csv\" .body, DataFrame md\"\"\" Step 2 \"\"\" md\"\"\" Step 3 Creating an edge list \"\"\" \"\"\" actor pairs df DataFrame Given a DataFrame with columns ` actor id` and ` movie id`, return a DataFrame with columns ` actor1`, ` actor2`, ` weight` where `weight` is the number of movies the two actors appeared in together. \"\"\" function actor pairs df DataFrame, remove singletons false rows NamedTuple for sub in groupby df, movie id actors unique sub.actor id all unordered pairs of actors in this movie for a, b in combinations actors, 2 push rows, actor1 min a,b , actor2 max a,b end end out chain rows begin DataFrame groupby actor1, actor2 combine weight length actor1 1 end if remove singletons subset out, weight 0 end return out end md\"\"\" Step 4 Constructing the network \"\"\" function graph from edge list pairs, actor id df pool categorical vcat pairs.actor1, pairs.actor2 levels pool levels pool n length levels pool map each side to integer codes 1..n using the same levels node1 levelcode. categorical pairs.actor1, levels levels pool node2 levelcode. categorical pairs.actor2, levels levels pool sparse adjacency sum duplicates automatically , then symmetrize A sparse node1, node2, pairs.weight, n, n A A A' | Matrix graph SimpleWeightedGraph A nodes df DataFrame actor id levels pool, node id levelcode. levels pool nodes df leftjoin nodes df, actor id df, on actor id adjacency matrix A, nodes df, graph end md\"\"\" Step 5 Create a list of movies to pick from \"\"\" movies df sub subset movies df, year release date ≥ 2020 bind selected movie Select movies df sub.movie id . movies df sub.title, default 872585 actor id df, actor movie df let actor movie df chain actors df0 begin groupby actor combine movie id movie id transform actor id bycol 1 length actor aside actor id df select , actor, actor id subset selected movie ∈ movie id flatten movie id leftjoin movies df, on movie id select actor id, actor, movie id, title end actor id df, actor movie df end chain actor movie df begin subset movie id selected movie end pairs actor pairs actor movie df graph, nodes df graph from edge list pairs, actor id df let fig, ax, graphplot graph, node color \"orange\", edge width 0.5, figure size 400, 300 hidedecorations ax fig end some dummy analysis begin n edges ne graph n nodes nv graph n edges, n nodes end answer1 2 md\"\"\" ... Continue here ... This network of actors has n nodes nodes and n edges edges. ... \"\"\" answer1 answer1 1, answer1 2, answer1 3 actors chain nodes df begin TODO Adjust the line below transform importance bycol rand nv graph select node id, actor, importance sort importance, rev true end let layout NetworkLayout.Spring graph important actors first actors, 5 node id, actor important actors fig, ax, graphplot graph layout, node color \"orange\", edge width 0.5, node strokewidth i ∈ node id ? 1.0 0.0 for i ∈ 1 nv graph , figure size 400, 300 hidedecorations ax annotation ax, layout node id , text String. actor fig end choice set movies df sub.movie id . movies df sub.title md\"\"\" WIP for next year important movies \"\"\" ╠═╡ important movies chain actor movie df begin leftjoin actors, on actor groupby title combine importance sum importance sort importance, rev true last , size , 1 1 end ╠═╡ ╠═╡ xxx important movies.title i movie ╠═╡ ╠═╡ actors of important movie let title xxx chain actor movie df begin leftjoin nodes df, on actor, actor id subset title title end end ╠═╡ ╠═╡ let layout NetworkLayout.Spring graph node id actors of important movie fig, ax, graphplot graph layout, node color i ∈ node id ? orange gray for i ∈ 1 nv graph , edge width 0.5, node strokewidth i ∈ node id ? 1.0 0.0 for i ∈ 1 nv graph , figure size 400, 300 hidedecorations ax annotation ax, layout node id , text String. actor fig end ╠═╡ ╠═╡ bind i movie PlutoUI.Slider 1 size important movies, 1 , default 1, show value true ╠═╡ md\"\"\" Appendix \"\"\" TableOfContents md\"\"\" Packages \"\"\" md\"\"\" Assignment infrastructure \"\"\" cell id \" \" string PlutoRunner.currently running cell id group members firstname \"Ella Louise\", lastname \"Flores\" , firstname \"Padraig\", lastname \"Cope\" , firstname \"Christy\", lastname \"Denton\" cell2 cell id if group members 1 .firstname \"Ella Louise\" && group members 1 .lastname \"Flores\" markdown \"\"\" danger \"Note \" Before you submit , please replace the randomly generated names in this cell cell2 by the names of your group. \"\"\" end markdown \"\"\" Before you submit ... 👉 Make sure you have added your name and names of your group members in the cells below cell2 . 👉 Make sure that all group members proofread your submission especially your little essay . 👉 Go to the very top of the notebook and click on the symbol in the very top right corner. Export a static html file of this notebook for submission. The source code is embedded in the html file. \"\"\" members let names map group members do firstname, lastname firstname \" \" lastname end join names, \", \", \" & \" end md\"\"\" Assignment 2 A Network of Actors submitted by members In this assignment you will analyze a network of actors constructed from The Movie Database TMDB https www.themoviedb.org . TMDB is a community driven platform that provides extensive information on movies and TV shows. Once you have run the notebook, the picture below shows a network of selected actors . \"\"\" function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ', ' ', '.', ',', ' ', ' ', '\"', ' ', ' ', '\\'' length filter \"\" , words end show words answer md\" approximately wordcount answer words \" begin hint text Markdown.MD Markdown.Admonition \"hint\", \"Hint\", text almost text Markdown.MD Markdown.Admonition \"warning\", \"Almost there \", text still missing text md\"Replace `missing` with your answer.\" Markdown.MD Markdown.Admonition \"warning\", \"Here we go \", text keep working text md\"The answer is not quite right.\" Markdown.MD Markdown.Admonition \"danger\", \"Keep working on it \", text yays md\"Great \", md\"Yay ❤\", md\"Great 🎉\", md\"Well done \", md\"Keep it up \", md\"Good job \", md\"Awesome \", md\"You got the right answer \", md\"Let's move on to the next section.\" correct text rand yays Markdown.MD Markdown.Admonition \"correct\", \"Got it \", text end if answer0 md\"Your answer goes here ...\" keep working md\"Place your cursor in the code cell and replace the dummy text, and evaluate the cell.\" else correct md\"Great, I am looking forward to reading your answer \" end if answer3 md\"Your answer goes here ...\" keep working md\"Place your cursor in the code cell and replace the dummy text, and evaluate the cell.\" else correct md\"Great, we are looking forward to reading your answer \" end function show words limit answer, limit count wordcount answer if count 1.02 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end show words limit answer0, 50 show words limit join answer1, \" \" , 300 show words limit answer2, 250 show words limit answer3, 250 note text title \"FYI\" Markdown.MD Markdown.Admonition \"note\", title, text "},{"url":"networks-basics/eigenvector-centralities/","title":"Eigenvector centralities","description":"","tags":["networks-basics"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 2 section 2 order 2 title \"Eigenvector centralities\" layout \"layout.jlhtml\" tags \"networks basics\" description \"\" using Markdown using InteractiveUtils using PlutoUI using Graphs using SimpleWeightedGraphs using LinearAlgebra using GraphMakie using CairoMakie, AlgebraOfGraphics using DataFrames md\" `eigenvector centralities.jl` | Version 1.2 | content updated 5 Oct 2026, packages updated 4 Oct 2026 \" md\"\"\" How to find important accounts on X? Discuss follower count? Let's consider a group of users ``i \\in \\ 1, \\ldots, n\\ ``. First approach Eigenvector centrality An account is important if it is followed by important accounts How can we capture this mathematically? Consider account ``i`` and recall that the set of ``i``'s followers is ``\\mathcal N i \\ j g ji 1 \\ ``. Define account ``i``'s importance ``c i`` being proportional to the sum of their followers' importance , ```math c i \\alpha \\sum j g \\textcolor red j i c j. ``` Does this definition make sense? We can stack similar equations for all users and obtain the following linear system of equations ```math \\begin align \\begin pmatrix c 1 \\\\ c 2 \\\\ \\vdots \\\\ c n \\end pmatrix & \\alpha \\begin pmatrix g \\textcolor red 1 1 & g \\textcolor red 2 1 & \\cdots & g \\textcolor red n 1 \\\\ g \\textcolor red 1 2 & g \\textcolor red 2 2 & \\cdots & g \\textcolor red n 2 \\\\ \\vdots & \\vdots & & \\vdots \\\\ g \\textcolor red 1 n & g \\textcolor red 2 n & \\cdots & g \\textcolor red n n \\end pmatrix \\begin pmatrix c 1 \\\\ c 2 \\\\ \\vdots \\\\ c n \\end pmatrix \\\\ \\iff \\frac 1 \\alpha 𝒄 & G^T 𝒄 \\end align ``` \"\"\" md\"\"\" This defines an eigenvalue problem ``𝒄`` is an eigenvector of ``G^T``, corresponding to the eigenvalue ``\\frac 1 \\alpha ``. Thanks to the Perron Frobenius theorem https en.wikipedia.org wiki Perron%E2%80%93Frobenius theorem we know that ``𝒄`` and ``\\alpha`` are well defined for strongly connected graphs . The vector ``𝒄`` is non negative, and has a unique direction it is unique after normalization and ``\\frac 1 \\alpha `` is the biggest eigenvalue of ``G^T``. \"\"\" md\"\"\" Computing the eigenvector centrality \"\"\" md\"\"\" Eigenvector centrality computed by hand \"\"\" md\"\"\" Eigenvector centrality using function \"\"\" md\"\"\" When the eigenvector centrality fails \"\"\" graph let n 5 g SimpleGraph n add edge . Ref g , 1 3, 1 3 ' add edge . Ref g , 4 n, 4 n ' rem edge . Ref g , 1 n, 1 n g end graphplot graph, ilabels vertices graph , figure size 300, 300 eigenvector centrality graph eigen Matrix adjacency matrix graph md\"\"\" Counting Walks \"\"\" g let g graph CycleGraph 5 add edge g, 2, 3 g end graphplot g, arrow size 25, ilabels vertices g , figure size 250, 250 G adjacency matrix g G^5 md\"\"\" Variation 1 Katz Bonacich centrality \"\"\" md\"\"\" We stick to the idea of Eigenvector centrality, An account is important if it is followed by important accounts, but vary the mathematical formulation a bit. Everybody gets an exogenous level of importance ``\\beta`` . ```math \\begin align c i & \\alpha \\sum j g \\textcolor red j i c j \\textcolor darkorange \\beta \\\\ \\iff 𝒄 & \\alpha G^T 𝒄 \\textcolor darkorange 𝜷 \\\\ \\stackrel \\implies 𝒄 & I \\alpha G^T ^ 1 𝜷 \\end align ``` The last expression is only true if the so called Leontief inverse of ``\\alpha G^T`` exists. \"\"\" md\"\"\" The Leontief inverse `` I A ^ 1 `` \"\"\" let g SimpleGraph 5 for i ∈ 1 3 for j ∈ i 1 3 add edge g, i, j end end for i ∈ 4 5 for j ∈ i 1 5 add edge g, i, j end end add edge . Ref g , 4 6, 4 6 ' , 1.0 add edge . Ref g , 3,4 , 7 G Matrix adjacency matrix g eig eigen G ρ maximum abs, eig.values α 1 1 ρ sum α G ^i for i ∈ 0 3000 sum α G ^i for i ∈ 0 3001 info ρ centr1 katz centrality g, 0.3 1 ρ centr2 eigenvector centrality g inv I 0.2 Matrix adjacency matrix g centr1 centr2 graphplot g, ilabels round. centr2, digits 3 eigen Matrix adjacency matrix g end md\"\"\" Note \"\"\" md\"\"\" Note that one can find two similar definitions in the literature. ```math \\begin align 𝒄^\\text Katz & I \\alpha G^T ^ 1 I 𝜷 && \\sum i 1 ^\\infty \\alpha G^T ^i 𝜷\\\\ 𝒄^\\text Bonacich & I \\alpha G^T ^ 1 𝜷 && \\sum i 0 ^\\infty \\alpha G^T ^i 𝜷 \\end align ``` We will use whatever definition is more convenient in our applications. \"\"\" md\"\"\" Variation 2 Page Rank ... the algorithm that made Google stand out. Check Wikipedia if you're interested. \"\"\" md\"\"\" Exercises \"\"\" let g PathDiGraph 5 Graph 4 info graphplot g, ilabels vertices g , figure size 300, 300 A adjacency matrix g A^5 end md\"\"\" Appendix \"\"\" TableOfContents md\"\"\" Defining named graphs \"\"\" Gs StarGraph, WheelGraph, CycleGraph, CompleteGraph, PathGraph graphs G 6 for G ∈ Gs my EV centrality let values, vectors eigen Matrix adjacency matrix graphs 2 ' eigenvalue, max index findmax values candidate eigen Matrix adjacency matrix graphs 2 ' .vectors , max index EV centrality candidate . norm candidate sign candidate 1 end eigenvector centrality graphs 2 eigen Matrix adjacency matrix graphs 2 ' .vectors ,6 named graphs DataFrame graph graphs, name string. Symbol. Gs let fig Figure size 600, 350 for i, name, graph ∈ enumerate eachrow named graphs ax Axis fig fldmod1. i, 3 ... , title name, xautolimitmargin 0.1, 0.1 , yautolimitmargin 0.1, 0.1 hidedecorations ax graphplot ax, graph, ilabels round. eigenvector centrality graph , digits 2 end fig end let fig Figure size 600, 350 for i, name, graph ∈ enumerate eachrow named graphs ax Axis fig fldmod1. i, 3 ... , title name hidedecorations ax graphplot ax, graph, ilabels vertices graph end fig end "},{"url":"networks-basics/exercises-week1/","title":"Exercises","description":"","tags":["networks-basics"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 2 section 3 order 3 title \"Exercises\" layout \"layout.jlhtml\" tags \"networks basics\" description \"\" using Markdown using InteractiveUtils using Graphs using MetaGraphs using GraphDataFrameBridge using AlgebraOfGraphics using CairoMakie using GraphMakie using NetworkLayout using DataFrames using CSV CSV using DataFrameMacros, Chain using PlutoUI using StatsBase md\"\"\" `exercises week1.jl` | Version 1.3 | content updated 5 Oct 2026, packages updated 4 Oct 2026 \"\"\" md\"\"\" Exercises for week 1 \"\"\" md\"\"\" Part 1 Theory exercises The first few exercises will deal with the following simple graph. \"\"\" md\" Exercise 1 👉 Calculate by hand the betweenness centrality of node 5 in the simple network above. \" md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Check your answer by activating the cell below. \"\"\" ╠═╡ betweenness centrality simple graph 5 ╠═╡ md\" Exercise 2 Below you can calculate the eigenvector centrality and Katz Bonacich centrality ``\\alpha 0.2`` and exogenous factors ``e i 1`` for all nodes ``i``. 👉 First, guess which nodes have the highest eigenvector centrality. \" md\"\"\" Your guess goes here ... \"\"\" md\"\"\" 👉 Now check your guess with the following code. \"\"\" ╠═╡ eigenvector centrality simple graph ╠═╡ ╠═╡ katz centrality simple graph, 0.2 ╠═╡ ╠═╡ betweenness centrality simple graph ╠═╡ md\" Note that the betweenness centrality picks out nodes 5 and 6 as being most central, which corresponds to our intuition. The eigenvector centrality and Katz Bonacich centrality fail to identify these nodes as being central. We try to obtain some insight into this by making a calculation for the Katz Bonacich centrality. Exercise 3 👉 Write out the series representing the Katz Bonacich centrality for general 0 \\alpha 1 \\lambda \\rm max . Explain why all nodes have the same Katz Bonacich centrality in this case. \" md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Part 2 Computational exercises The next set of exercises will analyze the co authorship network of the Tinbergen Institute that you've seen already. \"\"\" md\"\"\" Exercise 4 Connected components 👉 Identify the components of this network and extract the core. \"\"\" md\"\"\" Exercise 5 Central researchers Let us now find the most central researchers of the Tinbergen institute. \"\"\" md\" 👉 Calculate the top 10 centralities for the largest component in this co authorship network in terms of degree, betweenness, eigenvector centrality and Katz Bonacich centrality with ``\\alpha 0.2`` \" md\"\"\" Exercise 6 Comparing centrality measures 👉 Compare the ranks for different centrality measures. \"\"\" md\" Again we see that the ranking of the nodes in terms of the centrality depends strongly on the measure of centrality used. \" md\"\"\" Appendix \"\"\" md\"\"\" Construct simple network \"\"\" A 1 2 1 3 1 4 2 3 2 4 3 5 4 5 5 6 6 7 6 8 7 9 7 10 8 9 8 10 9 10 df DataFrame A, auto simple graph MetaGraph df, x1, x2 let fig, ax, plt graphplot simple graph, layout Spring , ilabels vertices simple graph , edge color \"gray\", edge width 0.5, node color \"orange\", hidedecorations ax fig end graphplot simple graph md\"\"\" Load TI data \"\"\" node names metagraph getindex. Ref metagraph , 1 nv metagraph , name url ti \"https raw.githubusercontent.com greimel networks course main src assets pub datasets ti netwk0711.csv\" begin using DataDeps ENV \"DATADEPS ALWAYS ACCEPT\" true register DataDep \"TI network\", \"\"\" The co authorship network of the Tinbergen Institute 2007 2011. Made available with the permission of Marco van der Leij. \"\"\", url ti, \"dbb2a1d8ce1120ed274898ce76f84f7ef08f9938ad7f25f74d3b9f202dbc2137\" end begin edge list CSV.File joinpath datadep\"TI network\", \"ti netwk0711.csv\" edge df DataFrame edge list end ti graph MetaGraph edge df, from, to graphplot ti graph, layout Spring , edge color \"gray\", edge width 0.5, node size 10, node color \"orange\", nlabels node names ti graph , node attr strokewidth 1, strokecolor black , list of components contains a list of nodes for each component components connected components ti graph nodes in the largest component core argmax length, components gc ti graph core ti plot graphplot gc, layout Spring , edge color \"gray\", edge width 0.5, node size 10, node color \"orange\", node attr strokewidth 1, strokecolor black , competerank eigenvector centrality ti graph , rev true researchers df let df DataFrame name node names ti graph , index 1 nv ti graph sort df, index end central researchers chain researchers df begin transform eigenvector centrality bycol eigenvector centrality ti graph , degree centrality bycol degree centrality ti graph , bonacich katz centrality bycol katz centrality ti graph, 0.2 , transform rank eigenvector bycol competerank eigenvector centrality, rev true , rank degree bycol competerank degree centrality, rev true , rank bonacich katz bycol competerank bonacich katz centrality, rev true select name, r\"rank\", r\"centrality\", end sort central researchers, rank degree graphplot ti graph, layout Spring , edge color \"gray\", edge width 0.5, node size 10, nlabels ifelse. central researchers.rank degree .≤ 10, if this condition holds central researchers.name, then provide name as label \"\" else provide no label \"\" , node color ifelse. central researchers.rank degree .≤ 10, orange, gray , node attr strokewidth 1, strokecolor black , data central researchers mapping rank bonacich katz, rank eigenvector, visual Scatter | draw md\"\"\" Packages \"\"\" md\"\"\" Graphs \"\"\" md\"\"\" Plotting \"\"\" md\"\"\" Data \"\"\" md\"\"\" Other \"\"\" TableOfContents "},{"url":"networks-basics/first-networks/","title":"First networks (incl Assignment 1)","description":"","tags":["networks-basics"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 2 section 1 order 1 title \"First networks incl Assignment 1 \" layout \"layout.jlhtml\" tags \"networks basics\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using Graphs for analyzing networks using SimpleWeightedGraphs for handling weighted graphs using MetaGraphs using SNAPDatasets cool datasets of big networks using GraphMakie for plotting networks using NetworkLayout layout algorithms using CairoMakie hist using Colors colorant str using Statistics mean using StatsBase ecdf begin using PlutoUI using PlutoUI Slider CairoMakie also exports a Slider end using MarkdownLiteral markdown using DataFrames md\"\"\" `first networks.jl` | Version 1.8 | content updated 5 Oct 2026, packages updated 4 Oct 2026 \"\"\" md\"\"\" First networks in Julia In this section we show you how to create networks in Julia and how to visualize them. 1. special named graphs 2. do it yourself \"\"\" md\"\"\" Networks with names Let us plot our first networks. Below you see star network can you imagine why it is called that way? . You can specify it by \"\"\" n nodes 10 simple network StarGraph n nodes f1 graphplot simple network, ilabels \"Anna\", \"Bob\" vertices simple network md\" Play around with this code. You can change the number of nodes and see you the plot will update automatically. You can also look at different special graphs wheel network `WheelGraph` circle network `CycleGraph` complete network `CompleteGraph` path network `PathGraph` Try it and visualize a few graphs \" md\"\"\" Task 0 3 points 👉 Download and run Julia and Pluto. If you submit this notebook you'll receive the points \"\"\" md\"\"\" Task 1 1 point 👉 Plot a complete network with 6 nodes. Adjust the code above. \"\"\" f1 md\"\"\" Task 2 2 points 👉 Comparing a `StarGraph`, a `WheelGraph`, a `CycleGraph`, a `CompleteGraph` and a `PathGraph` with ``n 6`` nodes. Which network has the most edges? \"\"\" Gs StarGraph, WheelGraph, CycleGraph, CompleteGraph, PathGraph graphs G 6 for G ∈ Gs named graphs DataFrame graph graphs, name string. Symbol. Gs let fig Figure size 600, 350 for i, name, graph ∈ enumerate eachrow named graphs ax Axis fig fldmod1. i, 3 ... , title name hidedecorations ax graphplot ax, graph end fig end let what graph info for G ∈ Gs graph G 6 push what graph, G push info, ne graph end what graph, info end md\"\"\" Your answer goes here \"\"\" begin my network SimpleDiGraph 7 add edge my network, 3, 4 add edge my network, 2, 3 end md\"\"\" Building a network from scratch Below you find a template of building a network from scratch. Play with it make it your own you can set the number of nodes currently nv my network and add a few edges there are currently ne my network . Can you rebuild one of the named networks from above? \"\"\" md\"\"\" Note, that you can build directed graphs using `SimpleDiGraph`. Replace `SimpleDiGraph` by `SimpleGraph` to get an undirected graph. \"\"\" graphplot my network, layout Shell , arrow size 20, node color \"orange\", ilabels vertices my network md\"\"\" Task 3 2 points 👉 Build a `WheelGraph` with ``n 6`` from scratch. \"\"\" task3 graph let graph SimpleGraph 5 add your code here, e.g. add edge graph, 1, 2 graph end let fig Figure size 600, 250 n 6 task comparison WheelGraph n layout Shell nlist 1 a1, graphplot fig 1,1 , task3 graph layout, ilabels vertices task3 graph , axis title \"Your attempt\" a2, graphplot fig 1,2 , task comparison layout, ilabels vertices task comparison , axis title \"Your goal\" hidedecorations a1 hidedecorations a2 fig end md\"\"\" Task 4 2 points 👉 Build a `StarGraph` with ``n 25`` from scratch. Add fewer than 20 lines of code That is, use something more sophisticated than copy paste. E.g., a `for` loop, vectorization, ... \"\"\" task4 graph let graph SimpleGraph 5 add your code here, e.g. add edge graph, 1, 3 task4 graph graph end let fig Figure size 600, 250 task comparison StarGraph 25 layout Shell nlist 1 a1, graphplot fig 1,1 , task4 graph layout, ilabels vertices task4 graph , axis title \"Your attempt\" a2, graphplot fig 1,2 , task comparison layout, ilabels vertices task comparison , axis title \"Your goal\" hidedecorations a1 hidedecorations a2 fig end md\"\"\" End of Assignment Have a look at the rest of the material. It might be helpful for Assignment 2 \"\"\" md\"\"\" Building networks from real world data There are plenty of network datasets out there. You can check out the Stanford Large Network Dataset Collection link https snap.stanford.edu data index.html . A very small subset of these datasets can be downloaded directly from Julia using the package SNAPDatasets.jl link https github.com JuliaGraphs SNAPDatasets.jl . Let us have a look at the Facebook dataset, with 4039 nodes and 88234 edges. link to description https snap.stanford.edu data ego Facebook.html \"\"\" big network loadsnap facebook combined md\"Even though the dataset is rather small compared to others from this collection, we already run into problems when we want to visualize the network. The time it takes to plot a big network is mainly driven by the layout algorithm. That's why I choose the boring Shell algorithm, where all nodes are placed on a circle. This is very fast. If you want, you can try to plot this with the default layout algorithm. On my recent MacBook Pro, this took more than two minutes then I interrupted the execution of the cell. \" graphplot big network, layout Shell , layout SquareGrid , node size 2, edge width 1, node color blue, edge color orange, 0.01 md\"\"\" Language for network analysis We will discuss some useful concepts for analyzing networks. We will divide them into four groups. NOTE The concepts of this section are introduced in the first lectures of the course. Have a look if you're curious. But it is rather meant as a references for your assignments. If you cannot find what you need in this notebook, check out the excellent documentation of Graphs.jl https juliagraphs.org Graphs.jl dev . Counting friends neighborhood degree in out degree distribution, average degree Are my friends friends themselves? clustering average, total Friends of friends of friends ... walk path connected pair distance diameter connected network components Cool kids centralities \"\"\" network big network ∪ k neighbors big network, k for k ∈ 5, 50, 101, 500 ... nodes rand 1 nv big network , 10 | unique md\"\"\" Neighborhood and degree of a node Counting friends The neighborhood of a node ``i`` is the set of friends of nodes that are connected to ``i``. Let ``i `` bind i Slider 1 nv network , default 1, show value true , then the neighborhood of ``i`` is shown below. The degree of a node ``i`` is number of friends connected nodes of ``i``. Show degree bind show degree CheckBox default false \"\"\" md\"\"\" The degree distribution is the distribution of the number of friends. We can compute statistics of the distribution e.g. the average degree round mean degree network , digits 2 . Or we can visualize the full distribution in a histogram. \"\"\" hist degree network , bins 1 25, normalization probability, axis title \"The degree distribution The distribution of the number of friends \", ylabel \"relative frequency\", xlabel \"degree number of friends \" md\"\"\" Clustering Are my friends friends themselves? This time we look at node ``j `` bind j Slider 1 nv network , default 12, show value true . \"\"\" degree of j degree network, j actual links, possible links local clustering network, j md\"\"\" We see that the node has degree of j friends. These degree of j friends can form at most degree of j ⋅ degree of j 1 2 possible links friendships. We see that there are actual links friendships red edges . The clustering coefficient of node j is ``\\frac \\text actual \\text possible `` round local clustering coefficient network, j , digits 2 . Show clustering coefficient bind show clustering CheckBox default false \"\"\" local clustering coefficient network, j global clustering coefficient network 𝒩 neighbors network, j md\"\"\" Distance between nodes Friends of friends of friends ... \"\"\" md\"\"\" walk path connected pair distance diameter connected network components \"\"\" from 13 to 23 path a star network, from, to length path function color nodes graph, sets of nodes default color colorant\"lightgray\" colors Makie.wong colors 1 length sets of nodes default color extended sets sets of nodes..., 1 nv graph groups map 1 nv graph do i findfirst set i ∈ set, extended sets end colors groups end graphplot network, node size 19, edge width 1, ilabels vertices network , node color color nodes network, from, to , edge color e ∈ path || reverse e ∈ path ? red gray for e ∈ edges network function highlight neighbors graph, i color nodes graph, i , neighbors graph, i end graphplot network, edge width 1, ilabels vertices network , node size 20, nlabels show degree ? nothing \"deg \" . string. degree network , nlabels offset Point2f 0.1, 0.0 , node color highlight neighbors network, i , edge color black, 0.5 graphplot network, node size 19, edge width 1, ilabels vertices network , nlabels show clustering ? nothing \"cl \" . string. round. local clustering coefficient network , digits 2 , string. 1 nv network . \" clust. \" . string. round. local clustering coefficient network , digits 2 . \" \", node color highlight neighbors network, j , edge color src e ∈ 𝒩 && dst e ∈ 𝒩 ? red gray for e ∈ edges network md\"\"\" Components, path length and diameter \"\"\" components connected components network largest component argmax length, components subnetwork network largest component diameter subnetwork diameter network md\"\"\" To get the length of shortest path from node `i` to node `j` use `gdistances graph, i j `. \"\"\" distances from 1 gdistances network, 1 dist from 1 to 5 distances from 1 5 function giant component graph components connected components graph compute the size of nodes of each component size of components length. components find the component with maximal number of nodes n nodes, ind findmax size of components return the giant component giant component components ind end giant component my network subgraph, node list induced subgraph network, giant component network graphplot subgraph, node size 20, arrow size 20, node color \"orange\" let d degree network k sort unique d ccdf 1 . ecdf d . k . 1 share of nodes with degree ≥ k scatter k, ccdf, axis xscale log10, yscale log10, xlabel \"degree k\", ylabel \"share of nodes with degree ≥ k\" end diameter big network is connected big network Todo check if this needs to be transposed function distance matrix graph n nv graph number of vertices distance matrix zeros Int, n, n for i, node in enumerate vertices graph distance matrix i, . gdistances graph, node end distance matrix end distance matrix simple network md\" Centralities \" katz centrality big network katz centrality big network, 0.3 betweenness centrality simple network eigenvector centrality simple network closeness centrality simple network md\"\"\" Weighted graphs You can work with weighted networks using the package `SimpleWeightedGraphs`. It offers the types `SimpleWeightedGraph` and `SimpleWeightedDiGraph`. Let's construct a weighted directed network. \"\"\" begin weighted network SimpleWeightedDiGraph 3 add edge weighted network, 1, 2, 0.5 add edge weighted network, 2, 3, 0.8 add edge weighted network, 1, 3, 2.0 end adjacency matrix weighted network edge weights e.weight for e in edges weighted network graphplot weighted network, elabels string. edge weights , ilabels vertices weighted network indegree weighted network outdegree weighted network degree weighted network md\"\"\" Issue with weighted graphs advanced There is a second way of constructing weighted graphs. \"\"\" begin meta graph MetaDiGraph 3 add edge meta graph, 1, 2 add edge meta graph, 2, 3 add edge meta graph, 1, 3 set prop meta graph, 1, 2, weight, 0.5 set prop meta graph, 2, 3, weight, 0.8 set prop meta graph, 1, 3, weight, 2.0 meta graph end md\"\"\" `MetaGraph`s are convenient to work with because they can store names of nodes and other meta data. However, they behave slightly differently than `SimpleWeightedGraphs`. The `adjacency matrix` is a matrix of 0 and 1 not showing the weights . \"\"\" adjacency matrix meta graph . weights meta graph md\"\"\" In order to get the matrix representation of the weighted graph use \"\"\" md\"\"\" This inconsistency will likely be fixed in the future. See this issue on github https github.com JuliaGraphs LightGraphs.jl issues 1519 . \"\"\" md\"\"\" Appendix \"\"\" TableOfContents md\"\"\" Packages \"\"\" md\"\"\" Graphs \"\"\" md\"\"\" Plotting \"\"\" md\"\"\" Statistics \"\"\" md\"\"\" Other \"\"\" md\"\"\" Assignment infrastructure \"\"\" cell id \" \" string PlutoRunner.currently running cell id group number 99 cell1 cell id markdown \"\"\" Before you submit ... 👉 Make sure you have added your names and your group number in the cells below cell1 . 👉 Make sure that all group members proofread your submission. 👉 Go to the very top of the notebook and click on the symbol in the very top right corner. Export a static html file of this notebook for submission. The source code is embedded in the html file. \"\"\" group members firstname \"Ella Louise\", lastname \"Flores\" , firstname \"Padraig\", lastname \"Cope\" , firstname \"Christy\", lastname \"Denton\" cell2 cell id if group number 99 || group members 1 .firstname \"Ella Louise\" && group members 1 .lastname \"Flores\" markdown \"\"\" danger \"Note \" Before you submit , please replace the randomly generated names in this cell cell2 by the names of your group and put the right group number in the cell above. cell1 . \"\"\" end members let names map group members do firstname, lastname firstname \" \" lastname end join names, \", \", \" & \" end assignment cell cell id md\"\"\" Assignment 1 First networks in Julia submitted by members group group number In this assignment you get some experience with the Julia programming language. You will also create and visualize simple networks in Julia. \"\"\" function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ', ' ', '.', ',', ' ', ' ', '\"', ' ', ' ', '\\'' length filter \"\" , words end show words answer md\" approximately wordcount answer words \" begin hint text Markdown.MD Markdown.Admonition \"hint\", \"Hint\", text almost text Markdown.MD Markdown.Admonition \"warning\", \"Almost there \", text still missing text md\"Replace `missing` with your answer.\" Markdown.MD Markdown.Admonition \"warning\", \"Here we go \", text keep working text md\"The answer is not quite right.\" Markdown.MD Markdown.Admonition \"danger\", \"Keep working on it \", text yays md\"Great \", md\"Yay ❤\", md\"Great 🎉\", md\"Well done \", md\"Keep it up \", md\"Good job \", md\"Awesome \", md\"You got the right answer \", md\"Let's move on to the next section.\" correct text rand yays Markdown.MD Markdown.Admonition \"correct\", \"Got it \", text end function show words limit answer, limit count wordcount answer if count 1.02 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end note text title \"FYI\" Markdown.MD Markdown.Admonition \"note\", title, text note markdown \"The assignment starts here link assignment cell \" "},{"url":"production-networks/long-plosser/","title":"Simulating Long & Plosser","description":"","tags":["production-networks"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 6 section 2 order 2 title \"Simulating Long & Plosser\" layout \"layout.jlhtml\" tags \"production networks\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using PlutoUI Slider using Statistics mean using DataFrameMacros using NetworkLayout using Chain using AlgebraOfGraphics using PlutoUI using DataFrames using SimpleWeightedGraphs using GraphMakie, CairoMakie using LinearAlgebra dot, I using PlutoTest using Graphs using GraphMakie automatic md\"\"\" `long plosser.jl` | Version 1.1 | content updated 12 Mar 2023, packages updated 4 Oct 2026 \"\"\" md\"\"\" Simulating the model of Long & Plosser \"\"\" md\"\"\" Some simple Networks \"\"\" md\"\"\" Model parameters \"\"\" md\"\"\" Solving the model \"\"\" md\"\"\" ```math γ I β A' ^ 1 θ \\left \\sum i 0 ^\\infty \\beta^i A' ^i\\right θ θ \\left \\sum i 1 ^\\infty \\beta^i A' ^i\\right θ ``` Thus, ``γ`` is the utility weight weighted Bonacich Katz centrality of the input output network. ``g ij 0`` means ``i`` used for ``j``. \"\"\" get γ θ, β, IO θ' I β IO ' equation 10b Zₜ γ, H, b, β, θ₀ θ₀ H θ₀ β dot γ, b equation 13 Lₜ γ, H, b, β, θ₀ γ . b β H θ₀ β dot γ, b equation 15 H 1.0 FIXME function Xₜ Yₜ, γ, IO, β, N equation 14 β γ i γ j IO i,j Yₜ j for i ∈ 1 N, j ∈ 1 N end function Yₜ₊₁ Lₜ, Xₜ, λₜ₊₁, b, IO, N λₜ₊₁ i Lₜ i ^b i prod Xₜ i, .^ IO i, for i ∈ 1 N end function Yₜ₊₁ V2 Yₜ, λₜ₊₁, H, param γ get γ param Yₜ₊₁ Lₜ γ, H, param , Xₜ Yₜ, γ, param , λₜ₊₁, param end Cₜ Yₜ, γ, θ θ . γ . Yₜ equation 12 Pₜ Yₜ, γ γ . Yₜ equation 16 Wₜ γ, H, θ₀, b θ₀ dot γ, b H equation 17 md\"\"\" Helpers for simulating the model \"\"\" md\"\"\" Represent ``\\log Y t `` as AR 1 \"\"\" function κ param IO, β, b, N param γ get γ param L Lₜ γ, H, param κ zeros N for i in 1 N summand j begin κᵢⱼ β γ i γ j IO i,j if IO i,j 0 IO i,j log κᵢⱼ else 0.0 end end tmpᵢ sum summand j for j ∈ 1 N κ i b i 0 ? tmpᵢ b i log L i tmpᵢ end κ end function yₜ₊₁ yₜ, λₜ₊₁, param IO param yₜ₊₁ κ param . log. λₜ₊₁ . IO yₜ equation 20 end function Yₜ₊₁ V3 Yₜ, λₜ₊₁, param yₜ log. Yₜ Yₜ₊₁ exp. yₜ₊₁ yₜ, λₜ₊₁, param end md\"\"\" Use non stochastic steady state as initial condition \"\"\" function y₀ param try return I param.IO \\ κ param catch info \"there is no steady state\" N param return fill 1 N, N end end Y₀ param exp. y₀ param md\"\"\" Testing if the initial condition is correct This also tests if ``\\kappa`` is correct. \"\"\" md\"\"\" Container for all the output \"\"\" function outputₜ₊₁ Yₜ, λₜ₊₁, H, param γ get γ param Yₜ₊₁ Yₜ₊₁ V3 Yₜ, λₜ₊₁, param Cₜ₊₁ Cₜ Yₜ₊₁, γ, param X Xₜ Yₜ₊₁, γ, param assert vec sum X, dims 1 Cₜ₊₁ ≈ Yₜ₊₁ df DataFrame good 1 param.N, produced Yₜ₊₁, consumed Cₜ₊₁, input Yₜ₊₁ Cₜ₊₁, price Pₜ Yₜ₊₁, γ , productivity λₜ₊₁ end md\"\"\" Running the simulations \"\"\" function IRF param, H, λ vec Y old Y₀ param γ get γ param dfs DataFrame for ₜ₊₁, λₜ₊₁ ∈ enumerate λ vec dfₜ₊₁ outputₜ₊₁ Y old, λₜ₊₁, H, param transform dfₜ₊₁, t ₜ₊₁ push dfs, dfₜ₊₁ Y old . dfₜ₊₁.produced end df vcat dfs... chain df begin stack input, consumed, produced, productivity, price , good, t data mapping t Int L\"t\", value, color good nonnumeric, stack variable, layout variable, t nonnumeric visual Lines draw facet linkyaxes false, end end md\"\"\" Define simple networks \"\"\" function out star economy N, α 1.0 simple true A zeros N, N A 2 end,1 . α if simple A 1,1 α end graph SimpleWeightedDiGraph A' layout Shell nlist 1 graph, layout end function in star economy N, α 1.0 simple true A zeros N, N for i ∈ 2 N if simple A i,i α end A 1,i α N 1 end graph SimpleWeightedDiGraph A' layout Shell nlist 1 graph, layout end function vertical economy N, α 1.0 simple true A zeros N, N for i ∈ 1 N 1 A i,i 1 α end if simple A 1,1 α end graph SimpleWeightedDiGraph A layout Spring SquareGrid cols 1 graph, layout end function complete economy N, α 1.0 ... a α N 1 A fill a, N, N A A a I graph SimpleWeightedDiGraph A layout Shell graph, layout end function ring economy N, α 1.0 ... A zeros N, N for i ∈ 1 N 1 A i,i 1 α end A N,1 α graph SimpleWeightedDiGraph A layout Shell graph, layout end alternative networks out star economy \"out star\", in star economy \"in star\", ring economy \"ring\", complete economy \"complete\", vertical economy \"vertical\" md\"\"\" number of firms ``N`` bind N Slider 1 10, default 4, show value true non labor share ``\\alpha`` bind α Slider 0.1 0.1 0.9, default 0.3, show value true network bind economy Select alternative networks simple version bind simple CheckBox default true show influence bind show influence CheckBox default false \"\"\" influences let graph, layout economy N, α simple G adjacency matrix graph transpose of IO matrix W n nv graph vec ones influence 1 n I α G \\ ones n excess influence influence 1 n I \\ ones n influence, excess influence end param let graph, layout economy N, α simple IO weights graph ' β 0.95 θ fill eps , N θ 1,4 . 1 N 1 eps . 2 θ fill 1 N, N θ 1,4 . 1 N 1 eps . 2 θ₀ 0.1 labor share b map eachrow IO do recipeᵢ ∑aᵢ sum recipeᵢ non labor input share assert 0 ≤ ∑aᵢ ≤ 1 bᵢ 1.0 ∑aᵢ end param b, β, θ, θ₀, IO, N, graph, layout end md\"\"\" duration of shock bind T shocked NumberField 1 3 shocked firm bind i shocked NumberField 0 param.N \"\"\" let N param λ rand N Y old Y₀ param test Yₜ₊₁ V2 Y old, λ, H, param ≈ Yₜ₊₁ V3 Y old, λ, param end let N param Y ones N λ ones N γ get γ param for i ∈ 1 100 Y . Yₜ₊₁ V2 Y, λ, H, param γ end Y alt exp. y₀ param test Y ≈ Y alt end md\"\"\" Appendix \"\"\" TableOfContents md\"\"\" Plotting helpers \"\"\" attr kwargs... arrow size 15, elabels distance 15, edge width 1, nlabels distance 10, kwargs... minimal extend limits 0.05, hidespines false, kwargs... xgridvisible false, xticksvisible false, xticklabelsvisible false, ygridvisible false, yticksvisible false, yticklabelsvisible false, leftspinevisible hidespines, rightspinevisible hidespines, topspinevisible hidespines, bottomspinevisible hidespines, xautolimitmargin extend limits, extend limits , yautolimitmargin extend limits, extend limits , kwargs... fonts regular Makie.MathTeXEngine.texfont , bold Makie.MathTeXEngine.texfont let N param λ₀ ones N λ₁ ones N if i shocked 0 λ₁ i shocked 0.9 end λ vec fill λ₀, T shocked 2 2 N λ vec 1 T shocked . 2 . Ref λ₁ with theme fonts do IRF param, H, λ vec end | as svg end figure scale 1 fonts, size scale 300, scale 300 md\"\"\" Named GraphPlot \"\"\" function text bbox textstring AbstractString, fontsize Union AbstractVector, Number , font, align, rotation, justification, lineheight bb Makie.text bb textstring, Makie.to font font , fontsize return Rect2f Point2f Makie.origin bb 1 2 , Vec2f widths bb 1 2 end begin recipe NamedGraphPlot, graph do scene scatter theme default theme scene, Scatter lineseg theme default theme scene, LineSegments labels theme default theme scene, Makie.Text Attributes graphplot attr Attributes , node attributes Scatter node color lightgray, node strokewidth 0.5, node size automatic, node marker circle, node aspect regular, need for a better name node labels automatic, node font labels theme.fonts.regular, node fontsize labels theme.fontsize end function Makie.plot ngp NamedGraphPlot Extract attributes from plot object graph, graphplot attr, node color, node strokewidth, node size, node aspect, node marker, node labels, node font, node fontsize ngp Compute marker sizes out lift node labels, graph, node size, node fontsize, node font, node aspect do node labels, graph, node size, node fontsize, node font, node aspect if node labels automatic node labels string. 1 nv graph end Extract text sizes and layout accordingly label sizes widths text bbox string label , node fontsize, node font, center, center , 0f0, 0, 0 for label in node labels if regular use circle square, otherwise elipse rectangle if node aspect regular label sizes max pt... for pt in label sizes end We can specify markersize as a Vec2f, which is the eltype of label sizes. Thus, we can explicitly cause the node drawing to be large enough to accomodate the marker size. if node size automatic node size map x 1.7x . 0node fontsize, label sizes end node labels, label sizes, node size end lift node labels, label sizes, node size out node attr marker node marker, color node color, strokewidth node strokewidth, markersize node size, markerspace pixel, gp attr Dict Symbol, Any pairs graphplot attr if haskey gp attr, node attr warn \"Ignoring node attr\" delete gp attr, node attr end gp graphplot ngp, graph gp attr..., node attr positions lift gp layout graph text ngp, positions text node labels, font node font, fontsize node fontsize, align center, center return ngp end end let graph, layout economy N, α simple elabels string. round. weight. edges graph , digits 3 if show influence excess influence, influence influences norm influence excess influence mean excess influence norm influence excess influence maximum excess influence node color cgrad heat norm influence else node color lightgray end with theme fonts do namedgraphplot graph node color, figure figure , axis minimal hidespines false , graphplot attr attr elabels, layout end | as svg end function static viz param, H, λₜ₊₁ Y old Y₀ param is shocked ifelse. λₜ₊₁ . 1, red, lightgray df outputₜ₊₁ Y old, λₜ₊₁, H, param X Xₜ df.produced, get γ param , param test vec sum X, dims 1 df.consumed ≈ df.produced fig Figure plt chain df begin stack consumed, input , good, variable name usage data mapping good, value \"production\", color usage \"\", stack usage visual BarPlot end fg draw fig 1,2 2,1 , plt , legend position top, legend fig 1,2 1,1 , fg orientation horizontal, titleposition left graph, layout param elabels string. round. weight. edges graph , digits 3 ax, plt namedgraphplot fig 1,1 , graph, axis minimal hidespines false , graphplot attr layout, arrow size 15, elabels , node color is shocked lines fig 2, 1 , get γ param , axis title L\" γ \", xlabel \"goods\" lines fig 2, 2 , df.price, axis title \"price\", fig end let λₜ₊₁ ones param.N if i shocked 0 λₜ₊₁ i shocked 0.9 end with theme fonts do static viz param, H, λₜ₊₁ | as svg end end "},{"url":"production-networks/production/","title":"The economy as a network of sectors","description":"","tags":["production-networks"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 6 section 1 order 1 title \"The economy as a network of sectors\" layout \"layout.jlhtml\" tags \"production networks\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using SimpleWeightedGraphs using PlutoUI TableOfContents, Slider, CheckBox, as svg using CairoMakie.Makie.MathTeXEngine texfont using DataFrameMacros using DataFrames using Chain chain begin using OffsetArrays using Statistics mean using SparseArrays sparse using LinearAlgebra I, dot, diag, Diagonal, norm import Downloads using Distributions using AxisKeys KeyedArray using NamedArrays NamedArray using CategoricalArrays cut using Colors RGBA end using GraphMakie, CairoMakie using AlgebraOfGraphics using NetworkLayout begin using Graphs using SimpleWeightedGraphs AbstractSimpleWeightedGraph, SimpleWeightedDiGraph const LG Graphs function weighted adjacency matrix graph Graphs.AbstractGraph dir in A LG.weights graph . adjacency matrix graph if dir in return A elseif dir out return A' else error \"provide dir ∈ in, out \" end end LG.adjacency matrix graph AbstractSimpleWeightedGraph LG.weights graph . 0 function LG.katz centrality graph AbstractGraph, α Real 0.3 dir in, node weights ones nv graph v node weights A weighted adjacency matrix graph dir v I α A \\ v v norm v end function LG.eigenvector centrality graph AbstractGraph dir in A weighted adjacency matrix graph dir eig LG.eigs A, which LG.LM , nev 1 eigenvector eig 2 centrality abs. vec eigenvector end LG.indegree graph AbstractSimpleWeightedGraph sum weighted adjacency matrix graph , dims 1 column sum LG.outdegree graph AbstractSimpleWeightedGraph sum weighted adjacency matrix graph , dims 2 row sum end using PlutoTest test md\"\"\" `production.jl` | Version 1.8 | content updated 10 Mar 2023, packages updated 4 Oct 2026 \"\"\" md\"\"\" The Economy as a Network of Sectors Here is what we will cover. Part A Shock Propagation in an Input Output Network \\ based on Long & Plosser 1983 https www.jstor.org stable 1840430 , Journal of Political Economy and Carvalho 2014 https www.aeaweb.org articles.php?doi 10.1257 jep.28.4.23 , Journal of Economic Perspectives . 1. Introduce Input Output Tables. Re interpret them as a network of economic sectors connected by input output linkages 2. Visualize and analyze this intersectoral network 3. Simulate the dynamic production network model of Long & Plosser 1983 https www.jstor.org stable 1840430 \\ Visualize propagation of shocks | discuss the role of centrality Part B Network Origins of Aggregate Fluctuations \\ based on Acemoglu, Carvalho, Ozdaglar & Tahbaz Salehi 2012 https economics.mit.edu files 8135 , Econometrica 4. Solve the static production network model of Acemoglu, Carvalho, Ozdaglar & Tahbaz Salehi 2012 https economics.mit.edu files 8135 see the lecture notes 5. Show that sector specific shocks don't necessarily wash out in equilibrium see the lecture notes 6. Show by simulation that iid industry specific shocks will lead to aggregate flucuations Exercises 7. Simulate how the Covid shocks propagates through the economy Additional Reading What if? The Economic Effects for Germany of a Stop of Energy Imports from Russia Bachmann, Baqaee, Bayer, Kuhn, Löschel, Moll, Peichl, Pittel & Schularick, 2022 Micro Propagation and Macro Aggregation Baqaee & Rubbo, 2022 \"\"\" md\"\"\" Appetizers This plot shows how a shock to single sector propagates to other sectors. \"\"\" md\"\"\" This plot shows how the aggregate economy reacts to shocking two groups of sectors. The groups are equally big, but differ by their centrality. \"\"\" md\"\"\" This plot shows how industry specific iid shocks can either i wash out, or ii translate into aggregate fluctuations, depending on the network structure. \"\"\" md\"\"\" 1. Input Output Tables Production Recipes for the Economy \"\"\" md\"\"\" The list of industries \"\"\" md\"\"\" The Input Output Table \"\"\" md\"\"\" The Input Output table as a sparse matrix \"\"\" graphplot SimpleWeightedDiGraph wgts' md\"\"\" Important industries \"\"\" md\"\"\" 2. Analyzing the Intersectoral Network Recall, ``G W'``. Also, in order to satisfy the assumptions of the model, we have to normalize the row sums to 1. \"\"\" md\"\"\" 3. Simulating a Dynamic Production Network Model The model solution comes from equations 10b , 12 , 14 , 15 in Long & Plosser 1987, p. 48 https www.jstor.org stable 1840430 \"\"\" function params W N size W, 1 θ fill 1 N 1 , N utility weights of commodities θ₀ 1 N 1 utility weight of leisure β 0.95 H 1 α 0.3 param α, β, θ, θ₀, H end get γ W, param I param.β W \\ param.θ function L W, param α, β, θ, θ₀, H param γ get γ W, param L β . γ . 1 α . θ₀ 1 α β sum γ . H end C Y, W, param param.θ . get γ W, param . Y function welfare y, param dot y, param.θ end function κ W, param N size W, 1 α, β param γ get γ W, param κ 1 α . log. L W, param for i in 1 N tmp sum W i,j 0 ? 0 W i,j log β γ i W i,j γ j for j in 1 N κ i κ i α tmp end κ end y₀ W, param I param.α W \\ κ W, param y next y, ε, W, param κ W, param param.α W y ε function impulse response T, W, param, shocked nodes, ε₀ T shock 0, T₀ 3 y y₀ W, param N size W, 2 t indices T₀ T y out OffsetArray zeros N, length t indices , 1 N, t indices w out OffsetArray zeros length t indices , t indices y out , T₀ . y w out T₀ welfare y, param for t in T₀ 1 T ε zeros N if t ∈ T shock ε shocked nodes . ε₀ end y y next y, ε, W, param y out , t . y w out t welfare y, param end y out . y out . y out , T₀ . 1 w out . w out . w out T₀ . 1 production y out, welfare w out end md\"\"\" Simple Networks \"\"\" function my out StarGraph N A zeros N, N A ,1 . 1 SimpleWeightedDiGraph A' end function my complete DiGraph N A fill 1 N 1 , N, N A A 1 N 1 I SimpleWeightedDiGraph A' end begin grph my complete DiGraph 10 grph my out StarGraph 10 grph CycleDiGraph 10 end begin AA weighted adjacency matrix grph | Matrix | transpose param params AA production impulse response 10, AA, param, 1 , 0.3, T shock 0 2 color extr extrema production end t range axes production, 2 | x range first x , last x , step step x md\"\"\" ``t`` bind t Slider t range, default 1, show value true \"\"\" md\"\"\" Big Network from Input Output Tables \"\"\" md\"\"\" 4. & 5. see lecture notes \"\"\" md\"\"\" 6. Network Origins of Aggregate Fluctuations Instead of studying shocks to individual sectors, we will now simulate shocks to the whole economy. We assume that for each sector ``i`` and time period ``t``, the sector specific log productivity follows a white noise process ``\\varepsilon it \\sim N 0, \\sigma^2 ``. We will simulate our welfare measure flow utility . \"\"\" function simulate business cycles graph dist Normal 0, 1 , T₀ 15, T 100 N nv graph W weighted adjacency matrix graph ' param params W y y₀ W, param t indices T₀ T y out OffsetArray zeros N, length t indices , 1 N, t indices w out OffsetArray zeros length t indices , t indices ε rand dist, N, T y out , T₀ 0 . y w out T₀ 0 . welfare y, param for t in 1 T y y next y, view ε ,t , W, param y out , t . y w out t welfare y, param end y out . y out . y out , T₀ . 1 w out . w out . w out T₀ . 1 y out, w out end fluct fig let fig Figure ax Axis fig 1,1 N 400 grph my out StarGraph N fluc simulate business cycles grph for i, row in enumerate eachrow fluc.y out lines ax, collect axes fluc.y out, 2 , collect row , color black, 0.1 end lines ax, collect axes fluc.y out, 2 , collect fluc.w out , linewidth 2, color red ax0 ax ax Axis fig 2,1 grph CycleDiGraph N fluc simulate business cycles grph for i, row in enumerate eachrow fluc.y out lines ax, collect axes fluc.y out, 2 , collect row , color black, 0.1 end lines ax, collect axes fluc.y out, 2 , collect fluc.w out , linewidth 2, color red linkaxes ax0, ax hidexdecorations ax0 fig end fluct fig md\"\"\" 7. Assignment The Covid Crisis \"\"\" md\"\"\" For this problem set you will simulate a Covid crisis using the model from the lecture. Task 1 Which industries were hit by Covid? 3 points Find 5 groups of industries that were hit by the Corona crisis directly that is, not through propagation within the production network. You can look through the industry definitions in `df nodes1` below or go to the BEA website https www.bea.gov data industries . 👉 Put the codes of these industries into the `hit industries` vector below. \"\"\" hit industries \"111200\", \"111300\" md\"\"\" 👉 Explain your choice. 300 words \"\"\" answer1 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Task 2 Simulate a Covid crisis 4 points 👉 By putting your selected industries into the `hit industries` vector in Task 1 , you have already simulated the Covid crisis. You can adjust the length of the shock assume a period is a quarter and the magnitude of the shock. Duration of the shock bind shock duration Slider 1 10, default 2, show value true Magnitude of the shock bind shock size Slider 0.1 0.1 2.0, default 0.5, show value true \"\"\" md\"\"\" 👉 Explain your findings in 200 words. Think about how much of the welfare loss is due to the directly hit industries, how much is due to network effects? \"\"\" answer2 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Task 3 Is this model suitable for this exercise? 3 points 👉 Explain in 200 words how well you think that the model simulation can capture the real world Covid crisis? \"\"\" answer3 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Before you submit ... 👉 Make sure you have added your names and your group number in the cells below. 👉 Make sure that that all group members proofread your submission especially your little essays . 👉 Go to the very top of the notebook and click on the symbol in the very top right corner. Export a static html file of this notebook for submission. The source code is embedded in the html file. \"\"\" group number 99 group members firstname \"Ella Louise\", lastname \"Flores\" , firstname \"Padraig\", lastname \"Cope\" , firstname \"Christy\", lastname \"Denton\" md\"\"\" Appendix \"\"\" TableOfContents fonts regular texfont , bold texfont bold , italic texfont italic fig attr size 350, 300 figure padding 3, fonts, size fig attr xscale 1, yscale xscale figure padding 3, size xscale 200, yscale 200 , fonts minimal extend limits 0.1, hidespines true, kwargs... xgridvisible false, xticksvisible false, xticklabelsvisible false, ygridvisible false, yticksvisible false, yticklabelsvisible false, leftspinevisible hidespines, rightspinevisible hidespines, topspinevisible hidespines, bottomspinevisible hidespines, xautolimitmargin extend limits, extend limits , yautolimitmargin extend limits, extend limits , kwargs... fig let g grph wgt Matrix weights graph . adjacency matrix graph wg SimpleWeightedDiGraph wgt fig Figure fig attr 2.5, 1.25 ... node color parent production ,t graphplot fig 1,1 1,1 , g ilabels vertices g , layout Spring , node color, node attr colorrange color extr , edge color gray, axis minimal hidespines false, alignmode Inside Colorbar fig 1,2 limits color extr ax2 Axis fig 1,3 , xlabel L\"t\", alignmode Inside for i in 1 nv g lines ax2, collect axes production, 2 , parent production i, vlines ax2, t, linestyle dash, color gray end Label fig 0, , \"Shock transmission in a production network\" fig end fig fig md\"\"\" Downloading the Input Output Table for the US \"\"\" md\"\"\" Data is usually messy. Here is some evidence. \"\"\" md\"\"\" The vector of input industries is not the vector of output industries. \"\"\" md\"\"\" Here are the industries that are only outputs . \"\"\" md\"\"\" Here are the industries that are only inputs . \"\"\" md\"\"\" Cleaning the Input Output Table \"\"\" begin function nodes weights from edges from, to, weight get the list of nodes node names unique from to | sort enumerate the nodes node id index node dict Dict n i for i,n in enumerate node names add columns with node id i from node dict n for n in from i to node dict n for n in to N length node names create the weight matrix wgts sparse i from, i to, weight, N, N drop industries that are not used as inputs drop findall dropdims sum wgts, dims 2 , dims 2 .≈ 0 node names node names Not drop , sparse wgts wgts Not drop , Not drop end nodes weights from edges df, from, to, weight nodes weights from edges df ,from , df ,to , df ,weight end md\"\"\" List of Sectors \"\"\" md\"\"\" Package Environment \"\"\" import CSV, HTTP, ZipFile, XLSX begin url \"https apps.bea.gov industry xls io annual CxI DR 2007 2012 DOM DET.xlsx\" file Downloads.download url f XLSX.readxlsx file sh f \"2007\" end begin code column sh \"A6 A410\" | vec .| string output row name column sh \"B6 B410\" | vec .| string code row sh \"C5 OQ5\" | vec .| string input column name row sh \"C4 OQ4\" | vec .| string io matrix sh \"C6 OQ410\" .| float df in DataFrame code vec code row , name vec name row df out DataFrame code vec code column , name vec name column , io1 NamedArray io matrix, code row, code column , output, input io2 KeyedArray io matrix, output code row, input code column io1 end all code column . code row out not in chain df out begin filter code in df in.code , select code, name end in not out chain df in begin subset code ByRow x x ∉ df out.code subset code ∈ df out.code filter code in df out.code , select code, name end begin df io DataFrame io matrix, code column df io , output code row select df io, output, end df io begin io edges0 stack df io, Not \"output\" , variable name \"input\" subset io edges0, value 0 end begin node names, wgts nodes weights from edges io edges0, input, output, value droptol wgts, 0.0 node names, wgts end sum wgts . 0 403^2 extrema wgts begin used inputs sum wgts, dims 2 | vec row sums hist used inputs, axis title \"Inputs Used per Dollar of Output\", end begin used as input sum wgts, dims 1 | vec col sums filter √eps , used as input hist used as input, axis title \"Used as Inputs in Other Sectors\", end extrema wgts network SimpleWeightedDiGraph wgts' begin sorted nodes sortperm outdegree centrality network , rev true sorted nodes sortperm katz centrality network , rev true sorted nodes sortperm eigenvector centrality network , rev true n 40 bot n sorted nodes end n 1 end top n sorted nodes 1 n end fig welfare let nodes vec bot n \"bottom\", top n \"top\" nodes bot n, top n A weighted adjacency matrix network ' fig Figure fig attr 1.4, 1.2 ... ax Axis fig 1,1 , title \"Welfare loss after shock\\nto different industries\" for i, nodes in enumerate nodes vec welfare impulse response 10, A, params A , nodes 1 , 0.5, T shock 0 2 lines ax, collect axes welfare, 1 , parent welfare , label nodes 2 \" length nodes 1 \" end axislegend ax, position rb fig end fig welfare begin wgts n wgts . sum wgts, dims 2 | dropzeros network n SimpleWeightedDiGraph wgts n' extrema wgts n end unweighted network SimpleDiGraph wgts . 0.01 begin df all outerjoin df in, df out, on code, name n rows size df all, 1 assert length unique df all.code n rows assert length unique df all.name n rows df all end subset df all, code ∈ node names begin df nodes subset df all, code ∈ node names df nodes.inputs used sum wgts, dims 2 | vec df nodes.used as input sum wgts, dims 1 | vec transform df nodes, node id bycol 1 length code df nodes end sort df nodes, inputs used, rev true begin df nodes1 df nodes df nodes1.eigv c eigenvector centrality network, dir in df nodes1.eigv c out eigenvector centrality network, dir out df nodes1.katz c katz centrality network df nodes1.katz c katz centrality network, dir out end sort df nodes1, eigv c, rev true df nodes1 hit nodes df subset df nodes, code ∈ hit industries fig covid let hit nodes hit nodes df.node id n hit length hit nodes nodes vec bot n 1 n hit \"bottom\", top n 1 n hit \"top\", hit nodes \"Covid\" A weighted adjacency matrix network ' fig Figure fig attr 1.5, 1 ... ax Axis fig 1,1 , title \"Welfare loss after shock\\nto different industries\" for i, nodes in enumerate nodes vec welfare impulse response 10, A, params A , nodes 1 , shock size, T shock 0 shock duration lines ax, collect axes welfare, 1 , parent welfare , label nodes 2 \" length nodes 1 \" end axislegend ax, position rb fig 1,2 , ax fig end md\"\"\" Plotting \"\"\" md\"\"\" Patch 1 Weights and Centralities \"\"\" md\"\"\" Assignment infrastructure \"\"\" begin hint text Markdown.MD Markdown.Admonition \"hint\", \"Hint\", text almost text Markdown.MD Markdown.Admonition \"warning\", \"Almost there \", text still missing text md\"Replace `missing` with your answer.\" Markdown.MD Markdown.Admonition \"warning\", \"Here we go \", text keep working text md\"The answer is not quite right.\" Markdown.MD Markdown.Admonition \"danger\", \"Keep working on it \", text yays md\"Great \", md\"Yay ❤\", md\"Great 🎉\", md\"Well done \", md\"Keep it up \", md\"Good job \", md\"Awesome \", md\"You got the right answer \", md\"Let's move on to the next section.\" correct text rand yays Markdown.MD Markdown.Admonition \"correct\", \"Got it \", text end function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ', ' ', '.', ',', ' ', ' ', '\"', ' ', ' ', '\\'' length filter \"\" , words end test wordcount \" Hello, it's me. \" 4 test wordcount \"This doesn't really matter.\" 5 show words answer md\" approximately wordcount answer words \" show words answer1 function show words limit answer, limit count wordcount answer if count ≤ 1.1 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end show words limit answer2, 200 show words limit answer3, 200 members let names map group members do firstname, lastname firstname \" \" lastname end join names, \", \", \" & \" end md\"\"\" submitted by members group group number \"\"\" "},{"url":"social-networks/comparisons/","title":"Social comparisons","description":"","tags":["social-networks"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 4 section 2 order 2 title \"Social comparisons\" layout \"layout.jlhtml\" tags \"social networks\" description \"\" using Markdown using InteractiveUtils using PlutoUI Slider, TableOfContents, CheckBox, NumberField begin fancy false using CairoMakie using NetworkLayout NetworkLayout end using CategoricalArrays using DataFrames using Dates year using LinearAlgebra I, dot md\"\"\" danger \"Under construction \" This notebook is being reworked. \"\"\" md\"\"\" `comparisons.jl` | Version 1.2 | content updated 14 Oct 2021, packages updated 4 Oct 2026 \"\"\" md\"\"\" Social Comparisons, Income Inequality and the Mortgage Boom This lecture is loosely based on this paper https www.greimel.eu static falling behind paper.pdf . Here is what we will cover. Lecture Notes 1. We will discuss some evidence that our economic decisions are influenced by our peers. Our consumption of visible goods depends on the consumption of our peers' visible goods. Neighbors of lottery winners buy bigger cars https www.aeaweb.org articles?id 10.1257 aer.101.5.2226 Nonrich consume more visible goods when top incomes rise https www.mitpressjournals.org doi abs 10.1162 REST a 00613 Home owners are less happy with their house when a big house is built nearby https papers.ssrn.com sol3 papers.cfm?abstract id 3378131 2. Discuss how consumption network effects can be estimated paper https academic.oup.com restud article 87 1 130 5486072 3. We will model the group of peers as a social network. Building on the lecture on Network Games . Pluto Notebook 4. We will have a look at the Distributional National Accounts data set and visualize rising income inequality and the household debt boom in the US. Data and paper http gabriel zucman.eu usdina , Julia package to manage dataset https github.com greimel DINA.jl 5. Generate a debt boom from rising inequality using our model \"\"\" md\"\"\" Distributional National Accounts We will first take a look at a few facts from the US distributional national accounts data Piketty, Saez & Zucman, 2018 and then try explain them using our simple model of social comparisons. \"\"\" md\"\"\" note \"Note\" The DINA dataset can only be downloaded in bulk. It is 1GB in zipped form. You can use my package DINA.jl https github.com greimel DINA.jl to easily download and store the data. Here we will work with summary statistics that can are taken from the docs of DINA.jl https greimel.github.io DINA.jl latest . \"\"\" md\"\"\" The US Household Debt Boom \"\"\" md\"\"\" The US Inequality Boom \"\"\" md\"\"\" Simulating the model \"\"\" par md md\"\"\" ``\\beta`` discount factor assume ``\\beta 1 1 r `` ``\\theta`` utility weight of housing ``\\phi`` strength of the comparison motive ``p`` house price \"\"\" par md par β 0.95, θ 0.30, ϕ 0.7, p 1 h next, h₀, y₀, groups, m next let β, θ, ϕ, p par groups \"bottom 50\", \"middle 40\", \"top 10\" κ₀ θ 1 θ 1 β κ₁ 1 β θ p κ₂ 1 θ y₀ 0.5, 1, 2 G 0 0 0.5 0 0 0.5 0. 0 0 h next y, h κ₁ y κ₂ ϕ G h function m next y, h h n h next y, h β . y p κ₀ h n ϕ G h end h₀ I ϕ κ₂ G \\ κ₁ y₀ h next, h₀, y₀, groups, m next end begin N length h₀ T 10 h sim zeros N, T m sim zeros N, T h sim , 1 h₀ end begin y panel zeros N, T y panel , 1 . y₀ m sim , 1 . m next y₀, h₀ for t in 2 T y panel 1, t y panel 1, t 1 y panel 2, t y panel 2, t 1 y panel 3, t 1.1 y panel 3, t 1 end for t in 2 T h sim , t h next y panel , t , h sim , t 1 m sim , t m next y panel , t , h sim , t 1 end end y panel begin sim df grp groups i , t for i in 1 N, t in 1 T | vec | DataFrame sim df.y y panel | vec sim df.h h sim | vec sim df.m m sim | vec transform sim df, h, y ByRow house2inc transform sim df, m, y ByRow mort2inc sim df end let fig Figure ax h Axis fig 1,1 2,1 , title \"Housing\" ax y Axis fig 1,1 2,3 , title \"Income\" ax m Axis fig 1,1 2,2 , title \"Mortgage\" ax h2y Axis fig 1,1 1,1 , title \"%Δ Housing Income\" ax d2y Axis fig 1,1 1,2 , title \"%Δ Mortgage Income\" col Makie.wong colors for i, gdf in enumerate groupby sim df, grp grp only unique gdf.grp lines ax y, gdf.t, gdf.y, label grp, color col i lines ax h, gdf.t, gdf.h, label grp, color col i lines ax m, gdf.t, gdf.m, label grp, color col i lines ax h2y, gdf.t, gdf.house2inc . gdf.house2inc 1 , label grp, color col i lines ax d2y, gdf.t, gdf.mort2inc . gdf.mort2inc 1 , label grp, color col i end leg attr orientation horizontal, tellheight true, tellwidth false leg attr tellwidth false Legend fig 1,1 1,3 , ax d2y leg attr... fig end md\"\"\" Appendix \"\"\" md\"\"\" Controlling for consumer price inflation to be improved \"\"\" md\"\"\" Package environment \"\"\" import CSV, HTTP function csv from url url csv CSV.File HTTP.get url .body df DataFrame csv end begin dina df csv from url \"https greimel.github.io DINA.jl dev dina aggregated.csv\" transform dina df, three groups categorical, renamecols false levels dina df.three groups, \"bottom 50\", \"middle 40\", \"top 10\" wgt dweght inc peinc byvar inc dbt var ownermort, rentalmort, nonmort, hwdeb var byvar dbt var dina df end agg df let df dina df df1 select df, group id, age, year, wgt, var... df2 combine groupby df1, year , v, wgt x,w dot x,w sum w v for v in var ... transform df2, d, inc ByRow string d \"2inc\" for d in dbt var ... end debt fig let d agg df fig Figure Define Layout, Labels, Titles Label fig 1,1 , \"Growth of Household Debt To Income in the USA\", tellwidth false axs Axis fig 2,1 1,i for i in 1 2 box attr color gray90, label attr padding 3,3,3,3 , Box fig 2,1 1,1, Top box attr... Label fig 2,1 1,1, Top , \"relative to 1980\" label attr... Box fig 2,1 1,2, Top box attr... Label fig 2,1 1,2, Top , \"relative to total debt in 1980\" label attr... Plot i80 findfirst d.year . 1980 for i,dbt in enumerate dbt var var string dbt \"2inc\" for j, fractionof in enumerate var, hwdeb2inc lines axs j , d.year, d ,var d i80,fractionof , label string dbt end end Legend leg attr orientation horizontal, tellheight true, tellwidth false leg Legend fig 3,1 , axs 1 leg attr... fig end begin gdpdef CSV.File IOBuffer \"\"\" DATE GDPDEF 1947 01 01 12.2662500000000000 1948 01 01 12.9542500000000000 1949 01 01 12.9345000000000000 1950 01 01 13.0880000000000000 1951 01 01 14.0227500000000000 1952 01 01 14.2650000000000000 1953 01 01 14.4392500000000000 1954 01 01 14.5722500000000000 1955 01 01 14.8172500000000000 1956 01 01 15.3225000000000000 1957 01 01 15.8322500000000000 1958 01 01 16.1905000000000000 1959 01 01 16.4132500000000000 1960 01 01 16.6380000000000000 1961 01 01 16.8140000000000000 1962 01 01 17.0190000000000000 1963 01 01 17.2137500000000000 1964 01 01 17.4767500000000000 1965 01 01 17.7955000000000000 1966 01 01 18.2945000000000000 1967 01 01 18.8252500000000000 1968 01 01 19.6257500000000000 1969 01 01 20.5900000000000000 1970 01 01 21.6772500000000000 1971 01 01 22.7747500000000000 1972 01 01 23.7565000000000000 1973 01 01 25.0605000000000000 1974 01 01 27.3225000000000000 1975 01 01 29.8405000000000000 1976 01 01 31.4877500000000000 1977 01 01 33.4400000000000000 1978 01 01 35.7845000000000000 1979 01 01 38.7665000000000000 1980 01 01 42.2740000000000000 1981 01 01 46.2737500000000000 1982 01 01 49.1317500000000000 1983 01 01 51.0447500000000000 1984 01 01 52.8917500000000000 1985 01 01 54.5665000000000000 1986 01 01 55.6680000000000000 1987 01 01 57.0402500000000000 1988 01 01 59.0510000000000000 1989 01 01 61.3700000000000000 1990 01 01 63.6722500000000000 1991 01 01 65.8217500000000000 1992 01 01 67.3197500000000000 1993 01 01 68.9162500000000000 1994 01 01 70.3870000000000000 1995 01 01 71.8645000000000000 1996 01 01 73.1792500000000000 1997 01 01 74.4417500000000000 1998 01 01 75.2792500000000000 1999 01 01 76.3655000000000000 2000 01 01 78.0732500000000000 2001 01 01 79.7897500000000000 2002 01 01 81.0505000000000000 2003 01 01 82.5510000000000000 2004 01 01 84.7730000000000000 2005 01 01 87.4147500000000000 2006 01 01 90.0637500000000000 2007 01 01 92.4825000000000000 2008 01 01 94.2887500000000000 2009 01 01 95.0027500000000000 2010 01 01 96.1067500000000000 2011 01 01 98.1152500000000000 2012 01 01 99.9987500000000000 2013 01 01 101.7512500000000000 2014 01 01 103.6322500000000000 2015 01 01 104.6225000000000000 2016 01 01 105.7190000000000000 2017 01 01 107.7050000000000000 2018 01 01 110.2917500000000000 2019 01 01 112.2615000000000000 2020 01 01 113.6112500000000000 \"\"\" | DataFrame gdpdef.year year. gdpdef.DATE end begin df dina df df1 select df, group id, three groups, age, year, wgt, var... filter age in 65 , df1 transform df1, grp id ByRow x ifelse x 5, \"bottom 50\", ifelse x 9, \"middle 40\", \"top 10\" three grps df2 combine groupby df1, three groups, year , v, wgt x,w dot x,w sum w v for v in var ... df3 leftjoin df2, gdpdef, on year rename df3, GDPDEF prices filter prices ismissing, df3 disallowmissing df3 df3.prices df3.prices . first filter year 1980 , df3 .prices transform df3, v, prices ByRow \"r string v \" for v in var ... transform df3, ownermort, inc ByRow \"mort2inc\" end d2y fig let fig Figure ax Axis fig 1,1 , title \"Mortgage to income by income group\" for i,d in enumerate groupby df3, three groups i80 findfirst d.year . 1980 lines ax, d.year, d.mort2inc . d.mort2inc i80 , label string only unique d.three groups end Legend fig 1,2 , ax fig end d2y fig ineq fig let fig Figure ax Axis fig 1,1 , title \"Growth of real pre tax incomes across income groups\" r inc Symbol \"r \" string inc for i,d in enumerate groupby df3, three groups i80 findfirst d.year . 1980 lines ax, d.year, d ,r inc . d i80,r inc , label string only unique d.three groups end vlines ax, 1980, 2007 , color gray, linestyle dash Legend fig 1,2 , ax fig end ineq fig TableOfContents "},{"url":"social-networks/facebook/","title":"Social connectedness","description":"","tags":["social-networks"],"text":" A Pluto.jl notebook v1.0.4 frontmatter chapter 4 section 1 order 1 title \"Social connectedness\" layout \"layout.jlhtml\" tags \"social networks\" description \"\" using Markdown using InteractiveUtils This Pluto notebook uses bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of bind gives bound variables a default value instead of an error . macro bind def, element format off return quote local iv try Base.loaded modules Base.PkgId Base.UUID \"6e696c72 6542 2067 7265 42206c756150\" , \"AbstractPlutoDingetjes\" .Bonds.initial value catch b missing end local el esc element global esc def Core.applicable Base.get, el ? Base.get el iv el el end format on end using PlutoUI Select using PlutoTeachingTools Columns using PlutoUI CheckBox begin binned scatter plot weighted means of `y` within `nbins` quantile bins of `x` struct BinScatter nbins Int end function bs BinScatter e AlgebraOfGraphics.ProcessedLayer entry map e do p, n x, y p w get n, weights, ones length x df dropmissing DataFrame x, y, w q quantile df.x, Weights df.w , range 0, 1, length bs.nbins 1 df.grp cut df.x, unique q , extend true binned combine groupby df, grp , x, w x, w mean x, Weights w x, y, w y, w mean y, Weights w y binned.x, binned.y , end plottype AlgebraOfGraphics.Makie.plottype entry.plottype, Scatter AlgebraOfGraphics.ProcessedLayer entry plottype end binscatter nbins 20 AlgebraOfGraphics.transformation BinScatter nbins end using NaturalEarth using GADM using AlgebraOfGraphics using AlgebraOfGraphics to geometry, trivialtransformation using Makie Scatter, Poly, Lines, Legend, Figure, Axis, Colorbar, lines , scatter, scatter , poly , vlines , hlines , image , hidedecorations , hidespines using Makie Label, Bottom, linkaxes using Makie L str, colgap using Colors RGBA using DataFrameMacros using Chain chain using DataFrames DataFrames, DataFrame, select, select , transform, transform , combine, leftjoin, innerjoin, rightjoin, groupby, ByRow, Not, disallowmissing , dropmissing , dropmissing, disallowmissing, stack, rename using CategoricalArrays cut using Statistics mean using SparseArrays sparse using LinearAlgebra I, dot, diag, Diagonal, norm using StatsBase quantile, Weights, weights using PlutoUI TableOfContents using GeometryBasics begin using Graphs using SimpleWeightedGraphs SimpleWeightedGraph const LG Graphs weighted adjacency matrix graph AbstractGraph LG.weights graph . adjacency matrix graph LG.adjacency matrix graph SimpleWeightedGraph LG.weights graph . 0 function LG.katz centrality graph AbstractGraph, α Real 0.3 node weights ones nv graph v node weights A weighted adjacency matrix graph v I α A \\ v v norm v end function LG.eigenvector centrality graph AbstractGraph A weighted adjacency matrix graph eig LG.eigs A, which LG.LM , nev 1 eigenvector eig 2 centrality abs. vec eigenvector end LG.outdegree G AbstractGraph vec sum weighted adjacency matrix G , dims 2 LG.indegree G AbstractGraph vec sum weighted adjacency matrix G , dims 1 end md\"\"\" `facebook.jl` | Version 1.12 | content updated 4 Oct 2026, packages updated 4 Oct 2026 \"\"\" md\"\"\" Social Connectedness What Friendships on Facebook Tell Us About the World Here is what we will cover. Lecture Notes 1. Define the Social Connectedness Index, discuss its limitations 2. Measuring concentration of Social Networks 3. Approximating friends' characteristics Pluto Notebook 4. Visualize social connectedness of a region 5. Regard the social connectedness index as the weights of network of regions. 6. Compute the network concentration of US counties 7. Analyze the US presidential election 2020 using these concepts \"\"\" md\"\"\" Visualizing Social Connectedness There at least two ways to visualize social connectedness. 1. Choropleth maps https en.wikipedia.org wiki Choropleth map allow visualizing the social connectedness of one region with other regions. 2. Heatmaps allow visualizing social connectedness of the full network. \"\"\" country \"IT\" md\"\"\" Visualizing the full network with a Heatmap \"\"\" md\"\"\" Social Connectedness as Weights of a Network of Regions \"\"\" md\"\"\" US Counties and US elections \"\"\" county name \"Cook\" state \"Illinois\" county name \"Los Angeles\" state \"\" county name \"New York\" state \"\" md\"\"\" Network Concentration \"\"\" add0 infty from, to, dist from to ? 0.0 ismissing dist ? Inf dist distance 150 format a, b, i kwargs... \" i\" md\"\"\" Show all the points? bind show all points CheckBox default false Color all the points? bind color all points CheckBox default false \"\"\" md\"\"\" US Presidential Elections 2020 \"\"\" md\"\"\" Network concentration and election outcomes \"\"\" md\"\"\" Partisan exposure and election outcomes see Assignment \"\"\" md\"\"\" Assignment 4 The Social Connectedness Index \"\"\" md\"\"\" Task 1 Social connectedness is not distance 2 points The social connectedness is strongly correlated with distance. The closest geographical regions often have the highest social connectedness index. 👉 Think about a country for which you expect high social connectedness with a country far away. Replace the variable `country` now country with the two letter abbreviation of the country of your choice. 👉 Explain in 200 words why you would expect high social connectedness with this distant country. Common history? A stereotype? \"\"\" answer1 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Task 2 Measuring centrality in the network of regions 4 points Take another look at the list of most central countries according to the social connectedness index. Shown below. \"\"\" md\"\"\" Are you surprised by this list? Would you have expected some other countries at the top? There are two possibilities. 1. Our prior beliefs are wrong. 2. We don't measure what we want to measure. Before we update our beliefs, let us think a bit about measuring centrality. 👉 2.1 | 1 points Discuss what problems you see with our measure of centrality. 200 words \"\"\" answer21 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 2.2 | 2 points Suggest an improved measure of centrality. Explain which of the problems you identified above are mitigated and how. 200 words \"\"\" answer22 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 2.3 | 1 point Calculate your suggested centrality measure and compare it to the measure from the lecture. \"\"\" your analysis goes here answer23 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Task 3 Partisan exposure and election outcomes 4 points In the figure below you find the partisan exposure measure which approximates the fraction of friends that votes Republican against the outcome of the election. Each dot corresponds to one county. \"\"\" md\"\"\" There is a pretty strong correlation between these two measures. To some extent, this strong correlation is purely by construction. 👉 3.1 | 1.5 points Why is that? Explain what's going on. 100 words \"\"\" answer31 md\"\"\" Your answer goes here ... \"\"\" threshold 300 md\"\"\" One way to remedy this sitation is to comment out line 6. Still, let us be cautious in interpreting this correlation causally. One concern is, that this correlation is driven by spatial autocorrelation . That is, regions that are close are similar in many dimensions. 👉 3.2 | 1.5 points Why can't we interpret the correlation causally if there is spatial autocorrelation? Why is the problem alleviated a bit by commenting out line 7. What changes if you increase the threshold currently threshold ? 200 words \"\"\" answer32 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" 👉 3.3 | 1 points Are there other reasons to believe that the correlation is not causal? Explain. 200 words \"\"\" answer33 md\"\"\" Your answer goes here ... \"\"\" md\"\"\" Before you submit ... 👉 Make sure you have added your names and your group number in the cells below. 👉 Make sure that that all group members proofread your submission especially your little essay . 👉 Make sure that you are within the word limit . Short and concise answers are appreciated. Answers longer than the word limit will lead to deductions. 👉 Go to the very top of the notebook and click on the symbol in the very top right corner. Export a static html file of this notebook for submission. The source code is embedded in the html file. \"\"\" group members firstname \"Ella Louise\", lastname \"Flores\" , firstname \"Padraig\", lastname \"Cope\" , firstname \"Christy\", lastname \"Denton\" group number 99 if group number 99 || group members 1 .firstname \"Ella Louise\" && group members 1 .lastname \"Flores\" md\"\"\" danger \"Note \" Before you submit , please replace the randomly generated names above by the names of your group and put the right group number in this cell 378c8a92 7129 4655 ac0b f6aa02c600c6 and this cell f5882ac7 b1f2 4285 9bab 8abdd975afd1 \"\"\" end md\"\"\" Appendix to Task 3 \"\"\" md\"\"\" Appendix \"\"\" minimalaxis args... xticksvisible false, yticksvisible false, topspinevisible false, bottomspinevisible false, leftspinevisible false, rightspinevisible false, xgridvisible false, ygridvisible false, xticklabelsvisible false, yticklabelsvisible false, args... md\"\"\" Specifying data deps \"\"\" dist urls \"500mi\" \"https nber.org distance 2010 sf1 county sf12010countydistance500miles.csv.zip\", \"100mi\" \"https data.nber.org distance 2010 sf1 county sf12010countydistance100miles.csv.zip\" sci url pre \"https data.humdata.org dataset e9988552 74e4 4ff4 943f c782ac8bca87 resource \" sci urls countries \"652cf9c9 541f 47de 8d53 ff818062bd0c download country.csv\", US counties \"97dc352f c9c5 47d6 a6ef 88709e14006c download us counties.csv\", begin using DataDeps ENV \"DATADEPS ALWAYS ACCEPT\" \"true\" for id, url in sci urls register DataDep \"SCI 2026 id\", \"\"\" \"\"\", sci url pre url end for id, url in dist urls register DataDep \"county dist id\", \"\"\" \"\"\", url, sci checksums id , post fetch method unpack end register DataDep \"US Elections\", \"\"\" \"\"\", \"https raw.githubusercontent.com tonmcg US County Level Election Results 08 20 master 2016 US County Level Presidential Results.csv\", \"https raw.githubusercontent.com tonmcg US County Level Election Results 08 20 master 2020 US County Level Presidential Results.csv\" , \"5e31e327837c1c6459e4d65ad248913b7503c47ac17f777a4c3659c1fa30cfa4\" end function urls to files urls map urls do id, url file split url, \" \" | last | string id replace file, \".zip\" \"\" end | Dict end sci files urls to files sci urls md\"\"\" Downloading the SCI Data \"\"\" md\"\"\" Constructing a Network From SCI Data \"\"\" function make sci graph df sci get the list of nodes node names unique df sci.user loc df sci.fr loc enumerate the nodes node id index node dict Dict n i for i,n in enumerate node names add columns with node id chain df sci begin transform user loc, fr loc . ByRow x node dict x . from, to sort from, to end create the weight matrix sparse wgts sparse df sci.from, df sci.to, df sci.scaled sci wgts float. Matrix sparse wgts wgts wgts Diagonal diag wgts wgts . maximum wgts node names, wgts end md\"\"\" Downloading the Maps \"\"\" function extract shapes df shp table chain shp table begin DataFrame select begin shape to geometry trivialtransformation, geometry population POP EST gdp GDP MD iso3c ADM0 A3 country ADMIN end subset ismissing shape disallowmissing end end md\"\"\" Translating Country Codes \"\"\" md\"\"\" use old version of spreadsheet because of `\"NA\"` vs `NA` issue https github.com datasets country codes issues 91 \"\"\" url country codes \"https raw.githubusercontent.com JuliaFinance Countries.jl refs heads main src data country codes.csv\" md\"\"\" Matching SCI and Map Shapes \"\"\" md\"\"\" Preparations County level analysis \"\"\" md\"\"\" Matching County Names \"\"\" node county ids md\"\"\" The SCI data contain data on county equivalent entities from U.S. protectorates and freely associated states e.g. American Samoa, Puerto Rico, Guam . For these entities the don't have additional data, so we drop them. \"\"\" filter in county acs df.fips , node county ids md\"\"\" Unfortunately, the map data don't contain FIPS codes, but county names. These are not in the same format as the names in `county acs df`. We need to remove identifiers like \"County\", \"Parish\", etc from the name. We need to handle capitalization and spaces in spanish names We need to handle the use of \"St.\" vs \"Saint\" \"\"\" filter out Alaska and Hawaii for plotting county shapes df filter state in \"Hawaii\", \"Alaska\" , county dict shapes function clean county name for matching county county match county repl \" County\" \"\", \" Parish\" \"\", \" City\" \"\", \" city\" \"\", \" and Borough\" \"\", \" Borough\" \"\", \" Census Area\" \"\", \" Municipality\" \"\", \"\\xf1\" \"n\", ñ n \"St.\" \"Saint\", \"Ste.\" \"Sainte\", \"Oglala Lakota\" \"Shannon\", \" \" \"\" for r in repl county match replace county match, r end county match lowercase county match end md\"\"\" Population data \"\"\" pop url \"https www2.census.gov programs surveys popest datasets 2010 2019 counties totals co est2019 alldata.csv\" md\"\"\" Shapes \"\"\" function get county shapes country code \"USA\" lev2 GADM.get country code, depth 2 chain lev2 begin DataFrame select state NAME 1, county NAME 2, shape to geometry trivialtransformation, geom transform county match clean county name for matching county end end md\"\"\" Package Environment \"\"\" md\"\"\" Plotting \"\"\" import CairoMakie md\"\"\" Data \"\"\" import CSV, HTTP, ZipFile function county dist data id urls dist urls id string id files urls to files urls valid ids first. urls if id ∉ valid ids ArgumentError \"provide one of valid ids\" | throw end path joinpath datadep str \"county dist id\" , files id CSV.File path | DataFrame end dff county dist data \"500mi\" function SCI data id urls sci urls id Symbol id files urls to files urls valid ids first. urls if id ∉ valid ids ArgumentError \"provide one of valid ids\" | throw end path joinpath datadep str \"SCI 2026 id\" , files id df CSV.File path select user region, friend region, scaled sci | DataFrame rename df, user region user loc, friend region fr loc end county df SCI data US counties begin node county ids, wgts2 make sci graph county df g county SimpleWeightedGraph wgts2 end county centrality df DataFrame fips node county ids, eigv c eigenvector centrality g county let fig Figure ax Axis fig 1,1 , title \"Social connectedness between US counties\" image ax, RGBA. 0,0,0, min. 1.0, wgts2 . 10 000 fig end get county sci SCI data US counties country df SCI data countries node names, wgts make sci graph country df g SimpleWeightedGraph wgts function elections data year path joinpath datadep\"US Elections\", \" year US County Level Presidential Results.csv\" CSV.File path | DataFrame end df elect0 elections data 2020 function csv from url url, args... kwargs... csv CSV.File HTTP.get url .body, args... kwargs... df DataFrame csv end codes df csv from url url country codes iso2c to fips begin df chain codes df begin select iso2c \"ISO3166 1 Alpha 2\" , iso3c \"ISO3166 1 Alpha 3\" , fips FIPS, country official name en, continent Continent DataFrames.dropmissing end subset df, iso3c ∈ \"CAN\", \"USA\", \"MEX\" missing countries DataFrame iso2c \"XK\", iso3c \"KOS\", country \"Kosovo\", fips \"KV\", continent \"EU\" , iso2c \"TW\", iso3c \"TWN\", country \"Taiwan\", fips \"TW\", continent \"AS\" df missing countries end begin df nodes0 DataFrame node names, id 1 length node names df nodes0 leftjoin df nodes0, iso2c to fips, on node names iso2c | disallowmissing sort df nodes0, continent end md\"\"\" Need help with finding the country code? bind abbrev let df sort df nodes0, country Select df.node names . df.country, default \"AT\" end \"\"\" md\"\"\" Here it is \" abbrev \" \"\"\" begin labels combine groupby df nodes0, continent , continent length width labels.start 0 cumsum labels.width 1 end 1 labels.mid labels.start labels.width . 2 labels end shapes df chain begin naturalearth \"admin 0 countries\", 110 this resolves to `ne 110m admin 0 countries.geojson` DataFrame extract shapes df unique transform shape shape isa Polygon ? MultiPolygon shape shape leftjoin iso2c to fips, on iso3c, makeunique true end begin df nodes df nodes0 df nodes.eigv c eigenvector centrality g df nodes.katz c katz centrality g df nodes1 rightjoin shapes df, df nodes, on iso2c node names, makeunique true, matchmissing equal select df nodes1, eigv c, katz c, shape dropmissing df nodes1 end let fig Figure size 350, 350 , figure padding 3 ax Axis fig 1,1 , title \"Social Connectedness Between Countries\", xgridvisible false, ygridvisible false, aspect 1 vlines ax, labels.start, color gray80 hlines ax, labels.start, color gray80 ax.xticks labels.mid, labels.continent ax.yticks labels.mid, labels.continent image ax, RGBA. 0,0,0, min. 1.0, wgts df nodes.id, df nodes.id . 100 , interpolate false fig end sort df nodes, eigv c, rev true df nodes1 sort df nodes, eigv c, rev true CairoMakie.poly shapes df.shape, strokewidth 0.5 subset shapes df, ismissing continent nomatch chain shapes df begin subset ismissing iso2c filter ∉ .iso2c , node names end function sci country chain SCI data countries begin subset user loc country select Not user loc leftjoin , iso2c to fips, on fr loc iso2c subset ismissing country disallowmissing leftjoin , shapes df, on iso3c, makeunique true subset ismissing shape subset fr loc country disallowmissing end end sort sci country , scaled sci, rev true no data chain iso2c to fips begin subset iso2c ∉ node names leftjoin shapes df, on iso3c, makeunique true subset ismissing shape disallowmissing end sci country fig let fig Figure ax Axis fig 1,1 , title \"Social connectedness with country\" hidedecorations ax hidespines ax sci country sci country color variable log. sci country.scaled sci . 100 000 attr tellwidth true, width 30 Plot the chosen country poly ax, filter iso2c x ismissing x && x country , shapes df .shape, color red Plot the countries for which there is no SCI data poly ax, no data.shape, color gray95 Plot the countries with sci data poly ax, sci country.shape, color color variable cb Colorbar fig 1,2 , limits extrema color variable attr..., label \"log sci \" fig end sci country fig let fig Figure figure padding 3, size 550, 400 ax Axis fig 1,1 , title \"Centrality According to Facebook\", aspect 1 hidedecorations ax hidespines ax color variable log. df nodes1.eigv c attr tellwidth true, width 15 Plot the countries for which there is no SCI data poly ax, no data.shape, color gray95 Plot the countries with sci data poly ax, df nodes1.shape, color color variable cb Colorbar fig 1,2 , limits extrema color variable attr..., label \"log centrality \" colgap fig.layout, 2 fig end all in iso2c to fips.iso2c , node names subset iso2c to fips, iso2c ∈ nomatch too small pop df chain pop url begin csv from url select REGION, DIVISION, STATE, COUNTY, STNAME, CTYNAME, CENSUS2010POP transform fips str string STATE lpad string COUNTY , 3, '0' select fips Meta.parse fips str , state STNAME, county CTYNAME, population CENSUS2010POP, divisor STNAME \" \" CTYNAME transform county match clean county name for matching county subset state county end df c chain county df begin add distances leftjoin , dff, on user loc county1, fr loc county2 set distance to infinity if there are no data transform distance add0 infty user loc, fr loc, mi to county add population leftjoin , pop df, on fr loc fips subset ismissing population disallowmissing population end concentration df0 combine groupby df c, user loc do all close subset all, distance distance concentration dot close.scaled sci, close.population dot all.scaled sci, all.population concentration end extrema skipmissing df c.mi to county sci with distance chain df c begin select user loc, fr loc, scaled sci, distance end df elect innerjoin df elect0, pop df, on county fips fips exposure df chain sci with distance begin groupby user loc combine do gdf chain gdf begin subset user loc fr loc subset user loc ≠ fr loc subset distance threshold innerjoin , df elect, on fr loc county fips aside wgts .scaled sci . .population rep exp mean .per gop, weights wgts , dem exp mean .per dem, weights wgts , vot exp dot .scaled sci, .total votes sum wgts end end rename user loc fips end df elect exposure chain df elect begin select fips county fips, per gop, per dem, turnout total votes population innerjoin exposure df, on fips end chain df elect exposure begin data mapping rep exp \"approximate share of Republican friends\", per gop \"Republican vote share 2020\" visual Scatter, color black, 0.3 , markersize 5 draw figure size 300, 250 end function get county shapes info df shapes df get county shapes chain pop df begin join population with shapes leftjoin , shapes df, on state, county match , makeunique true drop counties for which there is no shape mostly Alaska aside begin not matched subset , any ismissing. county 1, fips not matched filter county 1, fips x,y any ismissing. x,y , end subset ismissing shape drop Alaska and Hawaii for better plotting subset state ∉ \"Alaska\", \"Hawaii\" select county 1 county, Not county 1, county match disallowmissing end end county shapes df get county shapes info df fips, df let df subset county shapes df, contains county name county if size df , 1 1 fips only df .fips else subset df , state state if size df , 1 1 fips only df .fips else df end end fips, df end let df chain county df begin subset user loc fips select fips fr loc, scaled sci innerjoin county shapes df, , on fips end plt data df visual Poly mapping shape, color scaled sci log define plot attributes figure figure padding 3, size 450, 300 axis minimalaxis title \"Social Connectedness with county name\", aspect 1.5, titlefont regular draw plt axis, figure end concentration df let df innerjoin county shapes df, concentration df0, on fips user loc n 20 q quantile df.concentration, weights df.population , 0 1 n 1 chain df begin transform conc grp bycol cut concentration, q, extend true, labels format transform conc grp alt parse Int, string conc grp % 2 end df end let chain concentration df begin groupby conc grp combine population mean population, weights population , concentration mean concentration, weights population aside info scatter .concentration, log. .population , figure size 350, 250 end f Figure size 500, 250 , figure padding 3 chain concentration df begin transform log pop log population data mapping concentration, log pop \"log population \" visual Scatter, markersize show all points ? 4 0 color all points ? mapping color conc grp alt nonnumeric \"\" mapping mapping weights population binscatter visual color red draw f, end f end let plt data concentration df visual Poly mapping shape, color concentration Set plot attributes figure figure padding 3, size 450, 300 axis minimalaxis title L\"Network Concentration % of friends ≤ % distance \\text mi \", aspect 1.5 draw plt axis, figure end df conc elect innerjoin select concentration df, fips, concentration , select df elect, county fips, per gop, total votes , on fips county fips chain df conc elect begin data mapping concentration \"concentration\", per gop \"Republican vote share\", weights total votes visual Scatter, color blue, 0.1 binscatter draw figure size 300, 250 end import Shapefile using WorldBankData md\"\"\" Other \"\"\" md\"\"\" Patch 1 Weights and Centralities \"\"\" md\"\"\" Patch 2 Dense Graphs \"\"\" let note LG Graphs struct DenseWeightedGraph T, M AbstractMatrix T LG.AbstractGraph T wgts M end LG.is directed graph DenseWeightedGraph issymmetric weights graph LG.weights graph DenseWeightedGraph graph.wgts LG.adjacency matrix graph DenseWeightedGraph LG.weights graph . 0 LG.nv graph DenseWeightedGraph size LG.weights graph , 1 LG.ne graph DenseWeightedGraph sum adjacency matrix graph LG.has edge graph DenseWeightedGraph, i, j LG.weights graph i,j 0 LG.inneighbors graph DenseWeightedGraph, i LG.weights graph ,i . 0 LG.outneighbors graph DenseWeightedGraph, j LG.weights graph i, . 0 end md\"\"\" Assignment infrastructure \"\"\" members let names map group members do firstname, lastname firstname \" \" lastname end join names, \", \", \" & \" end md\" Assignment submitted by members group group number \" md\"\"\" submitted by members group group number \"\"\" function wordcount text stripped text strip replace string text , r\"\\s\" \" \" words split stripped text, ' ',' ','.',',',' ',' ','\"',' ',' ' length words end show words answer md\" approximately wordcount answer words \" begin hint text Markdown.MD Markdown.Admonition \"hint\", \"Hint\", text almost text Markdown.MD Markdown.Admonition \"warning\", \"Almost there \", text still missing text md\"Replace `missing` with your answer.\" Markdown.MD Markdown.Admonition \"warning\", \"Here we go \", text keep working text md\"The answer is not quite right.\" Markdown.MD Markdown.Admonition \"danger\", \"Keep working on it \", text yays md\"Great \", md\"Yay ❤\", md\"Great 🎉\", md\"Well done \", md\"Keep it up \", md\"Good job \", md\"Awesome \", md\"You got the right answer \", md\"Let's move on to the next section.\" correct text rand yays Markdown.MD Markdown.Admonition \"correct\", \"Got it \", text end hint md\"A possible approach Is there a variation of Eigenvector centrality, that allows you to take into account the size population of a country? Feel free to take another route.\" hint md\"Uncomment line 5 in the cell below.\" function show words limit answer, limit count wordcount answer if count 1.02 limit return show words answer else return almost md\"You are at count words. Please shorten your text a bit, to get below limit words .\" end end show words limit answer1, 200 show words limit answer21, 200 show words limit answer22, 200 show words limit answer31, 100 show words limit answer32, 200 show words limit answer33, 200 md\"\"\" Other stuff \"\"\" TableOfContents "}]