├── README.md ├── advanced ├── 7-apollo │ ├── command-module.jl │ ├── constants.jl │ ├── main.jl │ ├── moon.jl │ ├── system.jl │ └── types.jl └── 8-queuing │ ├── main.jl │ └── queuingSystem.jl ├── beginner ├── 1-helloworld │ ├── hello.jl │ └── main.jl ├── 2-primes │ └── main.jl └── 3-quadratic │ ├── derivative.jl │ ├── main.jl │ └── quadratic.jl └── intermediate ├── 4-statistics ├── gasoline.csv ├── main.jl ├── mainols.jl └── ols.jl └── 5-rabbitsfoxes └── main.jl /README.md: -------------------------------------------------------------------------------- 1 | julia-tutorials 2 | =============== 3 | 4 | A collection of tutorials for the Julia Language, using the Julia Studio IDE. 5 | 6 | Copyright 2012-2013 Forio 7 | -------------------------------------------------------------------------------- /advanced/7-apollo/command-module.jl: -------------------------------------------------------------------------------- 1 | function acceleration(time::Float64, pos::Vector{Float64}) 2 | moon_pos = moon_position(time) 3 | 4 | distance_from_earth = pos 5 | distance_to_moon = pos - moon_pos 6 | mag_e = norm(distance_from_earth) 7 | mag_m = norm(distance_to_moon) 8 | return -G * (ME * distance_from_earth / mag_e^3 + MM * distance_to_moon / mag_m^3) 9 | end 10 | 11 | 12 | function update(me::Command_Module, time::Float64, h::Float64) 13 | acceleration0 = acceleration(time, me.position) 14 | velocityE = me.velocity + h * acceleration0 15 | positionE = me.position + h * me.velocity 16 | velocityH = me.velocity + h * 0.5 * (acceleration0 + acceleration(time + h, positionE)) 17 | positionH = me.position + h * 0.5 * (me.velocity + velocityH) 18 | 19 | me.velocity = velocityH 20 | me.position = positionH 21 | 22 | me.positionH = positionH 23 | me.velocityH = velocityH 24 | me.positionE = positionE 25 | me.velocityE= velocityE 26 | 27 | me 28 | end -------------------------------------------------------------------------------- /advanced/7-apollo/constants.jl: -------------------------------------------------------------------------------- 1 | module constants 2 | 3 | export ME, RE, G, MM, RM, MCM, DISTANCE_TO_MOON, MOON_PERIOD, MOON_INITIAL_ANGLE, ORIGIN 4 | export TOTAL_DURATION, MARKER_TIME, TOLERANCE, INITIAL_POSITION, INITIAL_VELOCITY 5 | 6 | const ME = 5.97e24 # mass of earth in kg 7 | const RE = 6.378e6 # radius of earth in m (at equator) 8 | const G = 6.67e-11 # gravitational constant in m3 / kg s2 9 | const MM = 7.35e22 # mass of moon in kg 10 | const RM = 1.74e6 # radius of moon in m 11 | const MCM = 5000. # mass of command module in kg 12 | const DISTANCE_TO_MOON = 400.5e6 # m (actually, not at all a constant) 13 | const MOON_PERIOD = 27.3 * 24.0 * 3600. # s 14 | const MOON_INITIAL_ANGLE = pi / 180. * -61. # radians 15 | const ORIGIN = [0., 0.] # Vector that represents the origin 16 | 17 | const TOTAL_DURATION = 12. * 24. * 3600.# s 18 | const MARKER_TIME = 0.5 * 3600. # (used in error correction) s 19 | const TOLERANCE = 100000. # (used in error correction) m 20 | 21 | const INITIAL_POSITION = [-6.701e6, 0.] # Initial vector for the spacecraft in m 22 | const INITIAL_VELOCITY = [0., -10.818e3] # Initial velocity for spacecraft in m/s 23 | 24 | end 25 | -------------------------------------------------------------------------------- /advanced/7-apollo/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | # Problem: Save the Apollo 13 Astronauts 4 | 5 | using constants 6 | using types 7 | include("moon.jl") 8 | include("command-module.jl") 9 | include("system.jl") 10 | 11 | # initialization of our bodies 12 | earth = Body(ME, [0.0, 0.0], RE, ORIGIN) 13 | moon = Moon(MM, [0., 0.], RM, moon_position(0.0)) 14 | command_module = Command_Module(MCM, INITIAL_VELOCITY, 5.0, INITIAL_POSITION, INITIAL_POSITION, INITIAL_POSITION, INITIAL_VELOCITY, INITIAL_VELOCITY) 15 | world = EarthMoonSystem(0.0, earth, moon, command_module) 16 | 17 | function simulate() 18 | boost = 15. # m/s Change this to the correct value from the list above after everything else is done. 19 | position_list = Vector{Float64}[] # m 20 | current_time = 1. 21 | h = 0.1 # s, set as initial step size right now but will store current step size 22 | h_new = h # s, will store the adaptive step size of the next step 23 | mcc2_burn_done = false 24 | dps1_burn_done = false 25 | 26 | while current_time <= TOTAL_DURATION 27 | update(world, current_time, h) 28 | 29 | if !mcc2_burn_done && current_time >= 101104 30 | println("mcc2_burn fired") 31 | world.command_module.velocity -= 7.04 / norm(world.command_module.velocity) * world.command_module.velocity 32 | 33 | mcc2_burn_done = true 34 | end 35 | 36 | if !dps1_burn_done && current_time >= 212100 37 | println("dps1_burn5 fired") 38 | world.command_module.velocity += boost / norm(world.command_module.velocity) * world.command_module.velocity 39 | 40 | dps1_burn_done = true 41 | end 42 | 43 | positionE = world.command_module.positionE 44 | positionH = world.command_module.positionH 45 | velocityE = world.command_module.velocityE 46 | velocityH = world.command_module.velocityH 47 | 48 | error_amt = norm(positionE - positionH) + TOTAL_DURATION * norm(velocityE - velocityH) 49 | h_new = min(0.5 * MARKER_TIME, max(0.1, h * sqrt(TOLERANCE / error_amt))) # restrict step size to reasonable range 50 | 51 | current_time += h 52 | h = h_new 53 | 54 | push!(position_list, copy(world.command_module.position)) 55 | end 56 | 57 | return position_list 58 | end 59 | println("starting") 60 | @time pos = simulate() 61 | println(typeof(pos)) 62 | writecsv("output.csv", pos) 63 | -------------------------------------------------------------------------------- /advanced/7-apollo/moon.jl: -------------------------------------------------------------------------------- 1 | function moon_position(time::Float64) 2 | moon_angle = MOON_INITIAL_ANGLE + 2.0pi * time / MOON_PERIOD 3 | x::Float64 = DISTANCE_TO_MOON * cos(moon_angle) 4 | y::Float64 = DISTANCE_TO_MOON * sin(moon_angle) 5 | 6 | return [x, y] 7 | end 8 | 9 | function update(me::Moon, time) 10 | me.position = moon_position(time) 11 | 12 | me 13 | end -------------------------------------------------------------------------------- /advanced/7-apollo/system.jl: -------------------------------------------------------------------------------- 1 | function update(me::EarthMoonSystem, time::Float64, h::Float64) 2 | me.time = time 3 | 4 | update(me.moon, time) 5 | update(me.command_module, time, h) 6 | 7 | return me 8 | end 9 | -------------------------------------------------------------------------------- /advanced/7-apollo/types.jl: -------------------------------------------------------------------------------- 1 | module types 2 | 3 | export Body, Moon, Command_Module, EarthMoonSystem 4 | 5 | type Body{T} 6 | mass::T 7 | velocity::Vector{T} 8 | radius::T 9 | position::Vector{T} 10 | end 11 | 12 | typealias Moon Body 13 | 14 | type Command_Module{T} 15 | mass::T 16 | velocity::Vector{T} 17 | radius::T 18 | position::Vector{T} 19 | positionE::Vector{T} 20 | positionH::Vector{T} 21 | velocityE::Vector{T} 22 | velocityH::Vector{T} 23 | end 24 | 25 | type EarthMoonSystem 26 | time::Float64 27 | earth::Body 28 | moon::Moon 29 | command_module::Command_Module 30 | end 31 | 32 | end 33 | -------------------------------------------------------------------------------- /advanced/8-queuing/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | using queuingSystem 4 | 5 | ## USER DECISIONS 6 | 7 | warm_up_time = 43.0 8 | run_time = 20160.0 9 | 10 | # Standard Deviation = Mean * Coefficient of Variance 11 | coeff_of_variance = 1 12 | 13 | # Average Arrival Time 14 | mean_iat = 3.0 15 | 16 | # Average length of service 17 | mean_los = 9.0 18 | 19 | # Number of servers 20 | num_servers = 4 21 | 22 | ## END USER DECISIONS 23 | 24 | # Standard deviation in length of service 25 | std_dev_los = mean_los * coeff_of_variance 26 | 27 | # Standard deviation in arrival time 28 | std_dev_iat = mean_iat * coeff_of_variance 29 | 30 | # Initialize some empty vectors to hold our arrival rates 31 | # and service times 32 | arrival_times = Float64[] 33 | service_times = Float64[] 34 | 35 | max_arrivals = 15000 # simulate for no more than 15,000 customers 36 | prev_arrival = 0 # first arrival is at time = 0 37 | 38 | # Generate some random numbers to represent customer arrivals and service times 39 | for i=1:max_arrivals 40 | # Generate a random arrival time using the normal distribution 41 | prev_arrival += random_gaussian(mean_iat,std_dev_iat) 42 | 43 | # Generate a random service time using the normal distribution 44 | prev_los = random_gaussian(mean_los,std_dev_los) 45 | 46 | # Equivalent to push(arrival_times, prev_arrival) 47 | # Push our random values into an array 48 | arrival_times = push!(arrival_times, prev_arrival) 49 | service_times = push!(service_times, prev_los) 50 | end 51 | 52 | # Create our new queuing system 53 | qs = Queuing_System(arrival_times, service_times, warm_up_time, run_time, num_servers) 54 | 55 | # Run the simulation 56 | run_to_end(qs) 57 | -------------------------------------------------------------------------------- /advanced/8-queuing/queuingSystem.jl: -------------------------------------------------------------------------------- 1 | module queuingSystem 2 | 3 | export random_gaussian, Queuing_System, run_to_end 4 | 5 | function random_gaussian(mean::Float64, std_dev::Float64) 6 | mean + (rand() - 0.5) * std_dev 7 | end 8 | 9 | type Queuing_System 10 | ## These variables are set directly by the creator 11 | arrival_times::Array{Float64,1} 12 | service_times::Array{Float64,1} 13 | warm_up_time::Float64 14 | run_time::Float64 15 | servers::Int 16 | 17 | ## Internal variables - Set by constructor 18 | sim_time::Float64 19 | warmed_up::Bool 20 | in_system::Int 21 | arrival_index::Int 22 | service_index::Int 23 | 24 | next_to_complete::Int 25 | open_server::Int 26 | next_completion::Array{Float64,1} ## by server 27 | next_arrival::Float64 28 | next_exit::Float64 29 | 30 | # Constructor definition 31 | function Queuing_System(arrival_times::Array{Float64,1}, 32 | service_times::Array{Float64,1}, 33 | warm_up_time::Float64, 34 | run_time::Float64, 35 | servers::Int) 36 | sim_time = 0.0 37 | warmed_up = false 38 | in_system = 0 39 | arrival_index = 2 40 | service_index = 1 41 | 42 | next_to_complete = typemax(Int) 43 | open_server = 1 44 | 45 | next_completion = fill(typemax(Int), servers) 46 | 47 | next_arrival = arrival_times[1] 48 | next_exit = typemax(Int) 49 | 50 | new(arrival_times, 51 | service_times, 52 | warm_up_time, 53 | run_time, 54 | servers, 55 | sim_time, 56 | warmed_up, 57 | in_system, 58 | arrival_index, 59 | service_index, 60 | next_to_complete, 61 | open_server, 62 | next_completion, 63 | next_arrival, 64 | next_exit 65 | ) 66 | end 67 | end 68 | 69 | function warm_up(qs::Queuing_System) 70 | println("Warming up") 71 | while qs.sim_time < qs.warm_up_time 72 | next_event(qs) 73 | end 74 | qs.warmed_up = true 75 | println("Warmed up") 76 | end 77 | 78 | function run_to_end(qs::Queuing_System) 79 | if !qs.warmed_up 80 | warm_up(qs) 81 | end 82 | 83 | while qs.sim_time < qs.warm_up_time + qs.run_time 84 | next_event(qs) 85 | end 86 | end 87 | 88 | function next_event(qs::Queuing_System) 89 | # If we have customers arriving before the next customer exits 90 | if qs.next_arrival <= qs.next_exit 91 | 92 | # Update the sim time to the time at which the next customer arrives 93 | qs.sim_time = qs.next_arrival 94 | 95 | # Increment the number of customers in the system 96 | qs.in_system += 1 97 | 98 | # Get the next arrival after this one 99 | qs.next_arrival = next_arrival(qs) 100 | 101 | # If we have fewer customers in the system then servers 102 | # We can go ahead and process our next customer 103 | if qs.in_system <= qs.servers 104 | # When will the available server finish processing its next customer? 105 | qs.next_completion[qs.open_server] = qs.sim_time + next_service(qs) 106 | speak(qs, "Customer arrived at server $(qs.open_server) will be done at $(qs.next_completion[qs.open_server])") 107 | else 108 | # In the case where we have more customers in the system than servers 109 | # Customers will have to wait in queue 110 | speak(qs,"Customer arrived and is waiting in line") 111 | end 112 | 113 | else 114 | # A customer is exiting before the next arrival 115 | 116 | # Set sim time to the time of the next exit 117 | qs.sim_time = qs.next_exit 118 | 119 | # Decrement the number of customers in the system 120 | qs.in_system -= 1 121 | 122 | # Set this to a dummy value for now 123 | qs.next_completion[qs.next_to_complete] = typemax(Int) 124 | 125 | speak(qs, "Person exited from server $(qs.next_to_complete)") 126 | 127 | # If we have more customers in the system than servers 128 | if qs.in_system >= qs.servers 129 | # When will the next available server finish processing its current customer? 130 | qs.next_completion[qs.next_to_complete] = qs.sim_time + next_service(qs) 131 | speak(qs,"Customer exited line to see server $(qs.next_to_complete) will be done at $(qs.next_completion[qs.next_to_complete])") 132 | end 133 | end 134 | 135 | qs.next_exit = typemax(Int) 136 | qs.next_to_complete = -1 137 | qs.open_server = -1 138 | 139 | # For each server 140 | for i=1:qs.servers 141 | # If this server will finish before our current next_exit time 142 | if qs.next_completion[i] < qs.next_exit 143 | # Set the next exit time to that of server i 144 | qs.next_exit = qs.next_completion[i] 145 | 146 | # Designate this server as the next server to complete 147 | qs.next_to_complete = i 148 | end 149 | 150 | # Set an open server if one is available 151 | if qs.next_completion[i] == typemax(Int) && qs.open_server == -1 152 | qs.open_server = i 153 | end 154 | end 155 | end 156 | 157 | # Gets the next arrival time 158 | function next_arrival(qs::Queuing_System) 159 | val = qs.arrival_times[qs.arrival_index] 160 | qs.arrival_index += 1 161 | val 162 | end 163 | 164 | # Gets them next service time 165 | function next_service(qs::Queuing_System) 166 | val = qs.service_times[qs.service_index] 167 | qs.service_index += 1 168 | val 169 | end 170 | 171 | # Outputs time and a message 172 | function speak(qs::Queuing_System, words::String) 173 | if qs.warmed_up 174 | println("$(qs.sim_time) : $words") 175 | end 176 | end 177 | 178 | end 179 | -------------------------------------------------------------------------------- /beginner/1-helloworld/hello.jl: -------------------------------------------------------------------------------- 1 | println("Hello, World!") -------------------------------------------------------------------------------- /beginner/1-helloworld/main.jl: -------------------------------------------------------------------------------- 1 | include("hello.jl") 2 | -------------------------------------------------------------------------------- /beginner/2-primes/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | function is_divisible(dividend, divisor) 4 | return dividend % divisor == 0 5 | end 6 | 7 | function is_prime(n::Int64) 8 | if n <= 3 9 | return true 10 | end 11 | 12 | if n % 2 == 0 13 | return false 14 | end 15 | 16 | # initialize a counter variable 17 | i = 3 18 | 19 | while i <= sqrt(n) 20 | if n % i == 0 21 | return false 22 | end 23 | 24 | i += 2 25 | end 26 | 27 | return true 28 | end 29 | 30 | print(is_prime(10002021)) 31 | -------------------------------------------------------------------------------- /beginner/3-quadratic/derivative.jl: -------------------------------------------------------------------------------- 1 | function derivative(fn) 2 | return function(x) 3 | h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x 4 | 5 | xph = x + h 6 | dx = xph - x 7 | 8 | return (fn(xph) - fn(x)) / dx 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /beginner/3-quadratic/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | include("quadratic.jl") 4 | 5 | println(quadratic((x) -> 2x^2 + 30x + 9)) 6 | -------------------------------------------------------------------------------- /beginner/3-quadratic/quadratic.jl: -------------------------------------------------------------------------------- 1 | include("derivative.jl") 2 | 3 | function quadratic(f) 4 | # Compute the first derivative of f 5 | f1 = derivative(f) 6 | 7 | # Get the y intercept (explictly passing a floating point number) 8 | c = f(0.0) 9 | 10 | # Get the y intercept of the first derivative 11 | b = f1(0.0) 12 | 13 | a = f(1.0) - b - c 14 | 15 | # Our old friend the quadratic formula 16 | # Notice how Julia lets you return multiple values 17 | # Multiple values should be separated by a comma and 18 | # are returned as a tuple 19 | return (-b + sqrt(b^2 -4a*c + 0im)) / 2a, (-b - sqrt(b^2 -4a*c + 0im)) / 2a 20 | end 21 | -------------------------------------------------------------------------------- /intermediate/4-statistics/gasoline.csv: -------------------------------------------------------------------------------- 1 | 1,55.33,1.72,54,1.66219,92.19 2 | 2,59.13,1.2,53,1.58399,92.74 3 | 3,57.39,1.42,55,1.61731,91.88 4 | 4,56.43,1.78,55,1.66228,92.8 5 | 5,55.98,1.58,54,1.63195,92.56 6 | 6,56.16,2.12,56,1.68034,92.61 7 | 7,54.85,1.17,54,1.58206,92.33 8 | 8,52.83,1.5,58,1.54998,92.22 9 | 9,54.52,0.87,57,1.5623,91.56 10 | 10,54.12,0.88,57,1.57818,92.17 11 | 11,51.72,0,56,1.60401,92.75 12 | 12,51.29,0,58,1.59594,92.89 13 | 13,53.22,1.31,58,1.54814,92.79 14 | 14,54.76,1.67,58,1.63134,92.55 15 | 15,53.34,1.81,59,1.60228,92.42 16 | 16,54.84,2.87,60,1.54949,92.43 17 | 17,54.03,1.19,60,1.57841,92.77 18 | 18,51.44,0.42,59,1.61183,92.6 19 | 19,53.54,1.39,59,1.51081,92.3 20 | 20,57.88,1.28,62,1.56443,92.3 21 | 21,60.93,1.22,62,1.53995,92.48 22 | 22,59.59,1.13,61,1.56949,91.61 23 | 23,61.42,1.49,62,1.4133,91.3 24 | 24,56.6,2.1,62,1.54777,91.37 25 | 25,59.94,2.29,61,1.65523,91.25 26 | 26,58.3,3.11,62,1.29994,90.76 27 | 27,58.25,3.1,63,1.19975,90.9 28 | 28,55.53,2.88,64,1.20817,90.43 29 | 29,59.79,1.48,62,1.30621,90.83 30 | 30,57.51,0.87,60,1.29842,92.18 31 | 31,62.82,0.88,59,1.40483,91.73 32 | 32,62.57,0.42,60,1.45056,91.1 33 | 33,60.23,0.12,59,1.54357,91.74 34 | 34,65.08,0.1,60,1.6894,91.46 35 | 35,65.58,0.05,59,1.74695,91.44 36 | 36,65.64,0.05,60,1.74919,91.56 37 | 37,65.28,0.42,60,1.78053,91.9 38 | 38,65.03,0.65,59,1.78104,91.61 39 | 39,67.84,0.49,54,1.72387,92.09 40 | 40,73.74,0,54,1.73496,90.64 41 | 41,72.66,0,55,1.71966,91.09 42 | 42,71.31,3.44,55,1.60325,90.51 43 | 43,72.3,4.02,55,1.66783,90.24 44 | 44,68.81,6.88,55,1.69836,91.01 45 | 45,66.61,2.31,52,1.77967,91.9 46 | 46,63.66,2.99,52,1.81271,91.92 47 | 47,63.85,0.24,50,1.81485,92.16 48 | 48,67.25,0,53,1.72526,91.36 49 | 49,67.19,0,52,1.86782,92.16 50 | 50,62.34,0,48,2.00677,92.68 51 | 51,62.98,0,47,1.95366,92.88 52 | 52,69.89,0,55,1.89387,92.59 53 | 53,73.13,0,57,1.81651,91.35 54 | 54,65.09,1.01,57,1.45939,90.29 55 | 55,64.71,0.61,55,1.38934,90.71 56 | 56,64.05,1.64,57,1.33945,90.41 57 | 57,63.97,2.8,60,1.42094,90.43 58 | 58,70.48,4.64,60,1.5768,89.87 59 | 59,71.11,3.56,60,1.41229,89.98 60 | 60,69.05,2.51,60,1.54605,90 61 | 61,71.99,1.28,55,1.55182,89.66 62 | 62,72.03,1.28,56,1.6039,90.08 63 | 63,69.9,2.19,56,1.67265,90.67 64 | 64,72.16,0.51,56,1.55242,90.59 65 | 65,70.97,0.09,55,1.45728,91.06 66 | 66,70.55,0.05,52,1.26174,90.69 67 | 67,69.73,0.06,54,1.28802,91.11 68 | 68,69.93,0.05,55,1.36399,90.32 69 | 69,70.6,0,55,1.4221,90.36 70 | 70,75.54,0,55,1.67219,90.57 71 | 71,49.14,0,40,2.1714,94.17 72 | 72,49.1,0,42,2.31909,94.39 73 | 73,44.66,4.99,42,2.14314,93.42 74 | 74,44.64,3.73,44,2.08081,94.65 75 | 75,4.23,10.76,41,2.1707,97.61 76 | 76,5.53,7.99,40,1.99418,97.08 77 | 77,17.11,5.06,47,1.61437,95.12 78 | 78,67.6,1.84,55,1.64758,91.86 79 | 79,64.81,2.24,54,1.69592,91.61 80 | 80,63.13,1.6,52,1.66118,92.17 81 | 81,63.48,3.46,52,1.48216,91.56 82 | 82,62.25,3.56,50,1.49734,92.16 -------------------------------------------------------------------------------- /intermediate/4-statistics/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | data = readcsv("gasoline.csv") 4 | 5 | # Get the columns that correspond with our X values 6 | # and create a new matrix to hold them 7 | # syntax: data[row, column] 8 | # to get a whole row do data[row, :] 9 | # to get a whole column do data[:, column] 10 | # to get a range of columns do data[:, column_a:column_b] 11 | 12 | x = data[:, 2:4] 13 | y = data[:, 6] 14 | 15 | # Call linreg 16 | coefs = linreg(x, y) 17 | -------------------------------------------------------------------------------- /intermediate/4-statistics/mainols.jl: -------------------------------------------------------------------------------- 1 | using ols 2 | 3 | data = readcsv("gasoline.csv") 4 | 5 | # Get the columns that correspond with our X values 6 | # and create a new matrix to hold them 7 | # syntax: data[row, column] 8 | # to get a whole column do data[:, column] 9 | # to get a whole row do data[row, :] 10 | x = [data[:,2] data[:,3] data[:,4]] 11 | y = data[:,6] 12 | 13 | # Create a new OLS object 14 | reg = tols(y, x, "Octane Rating", ["Error", "Component 1", "Component 2", "Component 3"]) 15 | summary(reg) 16 | 17 | -------------------------------------------------------------------------------- /intermediate/4-statistics/ols.jl: -------------------------------------------------------------------------------- 1 | module ols 2 | 3 | export tols, summary 4 | 5 | # Author: Adam Savitzky 6 | # Email: asavitzky@forio.com 7 | # Github: github.com/adambom 8 | 9 | # Ported from the Python implemented by Vincent Nijs 10 | # http://www.scipy.org/Cookbook/OLS?action=AttachFile&do=get&target=ols.0.2.py 11 | 12 | # Julia type for multiple (multivariate) regression using OLS 13 | # For least squared regression on linear equations of multiple independent variables 14 | # y = a1 * x1 + a2 * x2 + ... an * xn 15 | # Y = AX + E 16 | 17 | # Input 18 | ## y = dependent variable 19 | ## y_varnm = string with the variable label for y 20 | ## x = independent variables, note that a constant is added by default 21 | ## x_varnm = list of variable labels for the independent variables 22 | 23 | # Usage 24 | ## Instantiate a new ols type 25 | ### reg = ols(y, x, "y", ["x1", "x2", "x3"]) 26 | ### Coefficients: reg.b 27 | ### R-Squared: reg.R2 28 | ### F-Statistic: reg.F 29 | ### Summary: summary(reg) 30 | 31 | type tols 32 | y::Array{Float64} 33 | x::Array{Float64} 34 | y_varnm::String 35 | x_varnm::Array{String, 1} 36 | inv_xx::Array{Float64} 37 | b::Array{Float64, 1} 38 | nobs::Int 39 | ncoef::Int 40 | df_e::Int 41 | df_r::Int 42 | er::Array 43 | sse::Float64 44 | se::Array{Float64, 1} 45 | t::Array{Float64} 46 | #p::Array 47 | R2::Float64 48 | R2adj::Float64 49 | F::Float64 50 | #Fpv::Float64 51 | 52 | function tols(y, x, y_varnm, x_varnm) 53 | x = hcat(ones(size(x, 1)), x) 54 | xT = transpose(x) 55 | 56 | inv_xx = inv(xT * x) 57 | xy = xT * y 58 | b = inv_xx * xy # estimate coefficients 59 | 60 | nobs = size(y, 1) # number of observations 61 | ncoef = size(x, 2) # number of coefficients 62 | df_e = nobs - ncoef # degrees of freedom, error 63 | df_r = ncoef - 1 # degrees of freedom, regression 64 | 65 | er = y - x * b # residuals 66 | sse = e^2/df_e # SSE 67 | se = sqrt(diag(sse * inv_xx)) # coef. standard errors 68 | t = b / se # coef. t-statistics 69 | # p = (1 - cdf(abs(t), df_e)) * 2 # coef. p-values 70 | 71 | R2 = 1 - var(er) / var(y) # model R-squared 72 | R2adj = 1 - (1 - R2) * ((nobs - 1) / (nobs - ncoef)) # adjusted R-square 73 | 74 | F = (R2 / df_r) / ((1 - R2) / df_e) # model F-statistic 75 | # Fpv = 1 - cdf(F, df_r, df_e) # F-statistic p-value 76 | 77 | new(y, x, y_varnm, x_varnm, inv_xx, b, nobs, ncoef, df_e, df_r, er, sse, se, t, R2, R2adj, F) 78 | end 79 | end 80 | 81 | function dw(self::tols) 82 | # Calculates the Durbin-Waston statistic 83 | de = self.er - 1. 84 | result = dot(de, de) / dot(self.er, self.er) 85 | return result 86 | end 87 | 88 | function ll(self::tols) 89 | # Calculate model log-likelihood and two information criteria 90 | 91 | # Model log-likelihood, AIC, and BIC criterion values 92 | loglike = -(self.nobs / 2) * (1 + log(2pi)) - (self.nobs / 2) * log(dot(self.er, self.er) / self.nobs) 93 | aic = -2loglike / self.nobs + (2 * self.ncoef / self.nobs) 94 | bic = -2loglike / self.nobs + (self.ncoef * log(self.nobs)) / self.nobs 95 | 96 | return loglike, aic, bic 97 | end 98 | 99 | function summary(self::tols) 100 | # print model output to screen 101 | 102 | t = time() 103 | 104 | # extra stats 105 | loglike, aic, bic = ll(self) 106 | #JB, JBpv, skew, kurtosis = self.JB() 107 | #omni, omnipv = self.omni() 108 | 109 | println("==============================================================================") 110 | #println("Dependent Variable: " + self.y_varnm) 111 | println("Method: Least Squares") 112 | println("Time: $t") 113 | println("No. obs: $(self.nobs)") 114 | println("No. variables: $(self.ncoef)") 115 | println("==============================================================================") 116 | println("variable coefficient std. Error t-statistic") 117 | println("==============================================================================") 118 | for i in 1:length(self.x_varnm) 119 | println("$(self.x_varnm[i]) $(self.b[i]) $(self.se[i]) $(self.t[i])") 120 | end 121 | println("========================================================================================") 122 | println("Model Stats Residual Stats") 123 | println("========================================================================================") 124 | println("R-Squared $(self.R2) Durbin-Watson Stat: $(dw(self))") 125 | println("Adjusted R-Squared $(self.R2adj) Omnimbus Stat: ?") 126 | println("F-Statistic $(self.F) Prob(Omnibus stat): ?") 127 | println("Log-Likelihood $loglike Prob(JB): ?") 128 | println("AIC Criterion $aic Skew: ?") 129 | println("BIC Criterion $bic Kurtosis: ?") 130 | println("========================================================================================") 131 | end 132 | 133 | function linreg{T<:Number}(X::StridedVecOrMat{T}, y::Vector{T}) 134 | hcat(ones(T, size(X,1)), X)\y 135 | end 136 | 137 | end 138 | -------------------------------------------------------------------------------- /intermediate/5-rabbitsfoxes/main.jl: -------------------------------------------------------------------------------- 1 | # This code and all turorial code can be found on https://github.com/forio/julia-tutorials 2 | 3 | #Time parameters 4 | start_time = 0 5 | end_time = 100 6 | 7 | #How much time passes between each successive calculation 8 | time_step = 1/4 # years 9 | end_step = int(((end_time-start_time)/time_step)) 10 | 11 | initial_rabbits = 30000 #The number of rabbits when the simulation is started. (Rabbits) 12 | initial_foxes = 15 #The number of foxes when the simulation is started (Foxes) 13 | rabbits_killed_per_fox_birth = 1000 #The number of rabbits that must be killed for a fox to be born. (Rabbits/Fox) 14 | chance_a_rabbit_will_die_during_a_meeting = 0.50 #The chance a rabbit will die when a rabbit fox cross paths. (dmnl) 15 | chance_of_rabbit_and_fox_meeting = 0.02 #The chance that a rabbit and fox will cross paths. (dmnl) 16 | rabbit_growth_rate = 0.20 # The percent of the rabbit population that will be born this time step. (1/Year) 17 | fox_death_rate = 0.10 #The percent of the fox population that will die this time step from old age. (1/Year) 18 | 19 | rabbits_over_time = fill(0.0, end_step+1) 20 | foxes_over_time = fill(0.0, end_step+1) 21 | model_time = fill(0.0, end_step+1) 22 | 23 | rabbits = initial_rabbits 24 | foxes = initial_foxes 25 | 26 | rabbits_over_time[1] = rabbits 27 | foxes_over_time[1] = foxes 28 | 29 | #Run the model 30 | for sim_step = 1:end_step 31 | # Get the time from the step 32 | sim_time = start_time + sim_step * time_step 33 | model_time[sim_step] = sim_time 34 | 35 | #first we must calculate our flows (our rates) 36 | rabbit_births = rabbits * rabbit_growth_rate 37 | rabbits_eaten = min(rabbits, chance_a_rabbit_will_die_during_a_meeting * chance_of_rabbit_and_fox_meeting * foxes * rabbits) 38 | 39 | fox_births = 1/rabbits_killed_per_fox_birth * rabbits_eaten 40 | fox_deaths = foxes * fox_death_rate 41 | 42 | #then we update our stocks 43 | foxes = foxes + fox_births - fox_deaths 44 | rabbits = rabbits + rabbit_births - rabbits_eaten 45 | 46 | #stock values always update in the next time step 47 | rabbits_over_time[sim_step+1] = rabbits 48 | foxes_over_time[sim_step+1] = foxes 49 | end 50 | 51 | println("Time,Rabbits (Thousands),Foxes") 52 | for i = 1:end_step 53 | print(model_time[i]) 54 | print(",") 55 | print(rabbits_over_time[i]/1000) 56 | print(",") 57 | println(foxes_over_time[i]) 58 | end 59 | --------------------------------------------------------------------------------