TExcelTAD
Home › Julia › Julia Mini Project

Julia Mini Project

In this project you'll build a small weather station analyser, one step at a time. It brings together much of the course: structs and parametric types, parsing strings, dictionaries, multiple dispatch, broadcasting, the Statistics, Dates and Printf standard libraries, and error handling.

By the end, the program reads raw CSV text like this:

text
station,date,temp_c,rain_mm
Oslo,2025-03-01,-2.5,0.0
Lima,2025-03-01,24.1,0.0
...

and prints a report with per-station statistics, the wettest days and detected anomalies. Every step is a complete program you can run and modify. Because the playgrounds can't read files, the data is an inline string — in a real script you'd use read("weather.csv", String) or the CSV.jl package.

Step 1: Model one reading

A reading has a station name, a date, a temperature and a rainfall amount. An immutable struct with concrete field types is both safe and fast. A custom show method gives it a readable printout.

julia · try it yourself
using Dates

struct Reading
    station::String
    date::Date
    temp::Float64      # °C
    rain::Float64      # mm
end

Base.show(io::IO, r::Reading) =
    print(io, r.station, " ", r.date, ": ", r.temp, "°C, ", r.rain, " mm")

r = Reading("Oslo", Date(2025, 3, 1), -2.5, 0.0)
println(r)
println(dayname(r.date), " ", r.temp < 0 ? "(frost)" : "")
Oslo 2025-03-01: -2.5°C, 0.0 mm
Saturday (frost)

Step 2: Parse CSV text, safely

Real data is messy. parse_line turns one line into a Reading, and throws an ArgumentError with a clear message when a line is malformed. load skips the header, collects good readings and reports bad lines instead of crashing.

julia · try it yourself
using Dates

struct Reading
    station::String
    date::Date
    temp::Float64
    rain::Float64
end

function parse_line(line::AbstractString)
    parts = split(strip(line), ",")
    length(parts) == 4 || throw(ArgumentError("expected 4 fields, got $(length(parts))"))
    station, d, t, r = parts
    temp = tryparse(Float64, t)
    rain = tryparse(Float64, r)
    (temp === nothing || rain === nothing) && throw(ArgumentError("bad number in \"$line\""))
    return Reading(String(station), Date(d), temp, rain)
end

function load(text)
    readings = Reading[]
    for (n, line) in enumerate(split(strip(text), '\n'))
        n == 1 && continue                      # header
        try
            push!(readings, parse_line(line))
        catch e
            println("skipping line $n: ", sprint(showerror, e))
        end
    end
    return readings
end

raw = """
station,date,temp_c,rain_mm
Oslo,2025-03-01,-2.5,0.0
Oslo,2025-03-02,abc,1.2
Lima,2025-03-01,24.1,0.0
Lima,2025-03-02
"""
data = load(raw)
println(length(data), " readings loaded")
println(data[2].station, " ", data[2].temp)
skipping line 3: ArgumentError: bad number in "Oslo,2025-03-02,abc,1.2"
skipping line 5: ArgumentError: expected 4 fields, got 2
2 readings loaded
Lima 24.1

Step 3: Group by station and compute statistics

A Dict{String, Vector{Reading}} groups the readings by station. get! creates the empty vector the first time a station is seen. Then Statistics does the maths, with broadcasting-free generator expressions like mean(r.temp for r in rs).

julia · try it yourself
using Dates, Statistics, Printf

struct Reading
    station::String
    date::Date
    temp::Float64
    rain::Float64
end

data = [
    Reading("Oslo", Date(2025, 3, 1), -2.5, 0.0),
    Reading("Oslo", Date(2025, 3, 2), 1.0, 4.2),
    Reading("Oslo", Date(2025, 3, 3), 3.5, 7.9),
    Reading("Lima", Date(2025, 3, 1), 24.1, 0.0),
    Reading("Lima", Date(2025, 3, 2), 25.3, 0.0),
    Reading("Lima", Date(2025, 3, 3), 23.8, 0.4),
]

function group_by_station(readings)
    groups = Dict{String, Vector{Reading}}()
    for r in readings
        push!(get!(groups, r.station, Reading[]), r)
    end
    return groups
end

groups = group_by_station(data)
@printf("%-6s %6s %6s %6s %8s\n", "City", "min", "mean", "max", "rain")
for name in sort(collect(keys(groups)))
    rs = groups[name]
    temps = [r.temp for r in rs]
    @printf("%-6s %6.1f %6.1f %6.1f %8.1f\n",
            name, minimum(temps), mean(temps), maximum(temps), sum(r.rain for r in rs))
end
City      min   mean    max     rain
Lima     23.8   24.4   25.3      0.4
Oslo     -2.5    0.7    3.5     12.1

Step 4: Units with multiple dispatch

Users in some countries prefer Fahrenheit and inches. Rather than sprinkling if unit == ... checks everywhere, we define small unit types and let dispatch pick the conversion. Adding a new unit later means adding methods, not editing existing code.

julia · try it yourself
abstract type TempUnit end
struct Celsius <: TempUnit end
struct Fahrenheit <: TempUnit end

abstract type RainUnit end
struct Millimetres <: RainUnit end
struct Inches <: RainUnit end

convert_temp(c, ::Celsius) = c
convert_temp(c, ::Fahrenheit) = c * 9 / 5 + 32
convert_rain(mm, ::Millimetres) = mm
convert_rain(mm, ::Inches) = mm / 25.4

symbol(::Celsius) = "°C"
symbol(::Fahrenheit) = "°F"
symbol(::Millimetres) = "mm"
symbol(::Inches) = "in"

describe(temp, rain, tu::TempUnit, ru::RainUnit) =
    string(round(convert_temp(temp, tu), digits=1), symbol(tu), ", ",
           round(convert_rain(rain, ru), digits=2), " ", symbol(ru))

println(describe(24.1, 12.7, Celsius(), Millimetres()))
println(describe(24.1, 12.7, Fahrenheit(), Inches()))
println(describe.([0.0, 100.0], 25.4, Ref(Fahrenheit()), Ref(Inches())))
24.1°C, 12.7 mm
75.4°F, 0.5 in
["32.0°F, 1.0 in", "212.0°F, 1.0 in"]

The last line broadcasts describe over two temperatures; Ref(...) keeps the unit objects from being iterated.

Step 5: Find anomalies

A reading is an anomaly if its temperature is more than 1.5 standard deviations from its station's mean. We compute z-scores with broadcasting, and findall returns the positions of the unusual days.

julia · try it yourself
using Dates, Statistics

temps = [4.1, 5.0, 4.6, 12.9, 5.3, 4.4, -3.8, 5.1]
days = Date(2025, 4, 1):Day(1):Date(2025, 4, 8)

z = (temps .- mean(temps)) ./ std(temps)
println(round.(z, digits=2))
for i in findall(abs.(z) .> 1.5)
    kind = z[i] > 0 ? "unusually warm" : "unusually cold"
    println(days[i], " (", dayabbr(days[i]), "): ", temps[i], "°C, ", kind)
end
[-0.13, 0.07, -0.02, 1.83, 0.13, -0.07, -1.9, 0.09]
2025-04-04 (Fri): 12.9°C, unusually warm
2025-04-07 (Mon): -3.8°C, unusually cold

Step 6: The complete report

Now we put it together. A parametric Summary{T} struct holds per-station results, and a single report function prints everything. The data has a malformed line on purpose, to show that the loader copes with it.

julia · try it yourself
using Dates, Statistics, Printf

struct Reading
    station::String
    date::Date
    temp::Float64
    rain::Float64
end

struct Summary{T <: Real}
    station::String
    mean_temp::T
    total_rain::T
    wettest::Reading
    anomalies::Vector{Reading}
end

function load(text)
    out = Reading[]
    for line in split(strip(text), '\n')[2:end]
        f = split(line, ",")
        t = length(f) == 4 ? tryparse(Float64, f[3]) : nothing
        r = length(f) == 4 ? tryparse(Float64, f[4]) : nothing
        if t === nothing || r === nothing
            println("warning: skipped \"", line, "\"")
            continue
        end
        push!(out, Reading(f[1], Date(f[2]), t, r))
    end
    return out
end

function summarize(name, rs)
    temps = [r.temp for r in rs]
    z = (temps .- mean(temps)) ./ std(temps)
    wettest = rs[argmax([r.rain for r in rs])]
    return Summary(name, mean(temps), sum(r.rain for r in rs), wettest, rs[abs.(z) .> 1.5])
end

function report(readings)
    stations = sort(unique(r.station for r in readings))
    for name in stations
        s = summarize(name, filter(r -> r.station == name, readings))
        @printf("%-5s mean %5.1f°C  rain %5.1f mm  wettest %s (%.1f mm)\n",
                s.station, s.mean_temp, s.total_rain, s.wettest.date, s.wettest.rain)
        for a in s.anomalies
            println("      anomaly: ", a.date, " at ", a.temp, "°C")
        end
    end
end

raw = """
station,date,temp_c,rain_mm
Oslo,2025-03-01,-2.5,0.0
Oslo,2025-03-02,1.0,4.2
Oslo,2025-03-03,0.5,7.9
Oslo,2025-03-04,9.8,0.0
Oslo,2025-03-05,0.2,1.1
Oslo,2025-03-06,-1.0,0.0
Lima,2025-03-01,24.1,0.0
Lima,2025-03-02,25.3,0.0
Lima,2025-03-03,23.8,0.4
Lima,2025-03-04,n/a,0.0
Lima,2025-03-05,24.6,0.0
"""
report(load(raw))
warning: skipped "Lima,2025-03-04,n/a,0.0"
Lima  mean  24.5°C  rain   0.4 mm  wettest 2025-03-03 (0.4 mm)
Oslo  mean   1.3°C  rain  13.2 mm  wettest 2025-03-03 (7.9 mm)
      anomaly: 2025-03-04 at 9.8°C

Oslo's 9.8 °C on 4 March stands out from an otherwise cold week, so it's flagged.

Ideas to extend the project

  • Add a Kelvin unit and print the report in any unit chosen by the user.
  • Compute a 3-day moving average of temperatures with a comprehension.
  • Group the readings by week (week(r.date)) instead of by station.
  • Write tests for load and summarize with the Test standard library (@testset, @test).
  • On your own computer, read a real CSV file with CSV.jl into a DataFrame, and plot temperatures with Plots.jl:
julia
using CSV, DataFrames, Plots
df = CSV.read("weather.csv", DataFrame)
plot(df.date, df.temp_c, group=df.station, ylabel="°C")

Test yourself

In Step 3, what does get!(groups, r.station, Reading[]) do when the station is not yet a key?

  1. Throws a KeyError
  2. Inserts an empty vector for that station and returns it
  3. Returns nothing
  4. Returns the whole dictionary

Why does Step 4 use unit types like Celsius() instead of strings like "C"?

  1. Strings are slower to print
  2. So multiple dispatch selects the conversion and new units only need new methods
  3. Julia has no string comparison
  4. Types use less memory than strings

In Step 5, what does findall(abs.(z) .> 1.5) return?

  1. The anomalous temperatures
  2. The indices where the condition is true
  3. A Bool
  4. The number of anomalies