Skip to content

Commit

Permalink
Merge pull request #385 from SpeedyWeather/mk/show
Browse files Browse the repository at this point in the history
Pretty printing for structs
  • Loading branch information
milankl authored Sep 13, 2023
2 parents 183a454 + 3ad6cdb commit ee923e7
Show file tree
Hide file tree
Showing 18 changed files with 123 additions and 101 deletions.
3 changes: 3 additions & 0 deletions src/SpeedyTransforms/aliasing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ function RingGrids.get_nlat_half( trunc::Integer,
return roundup_fft(ceil(Int,((1+dealiasing)*trunc+1)/4))
end

# inverse of get_nlat_half to reobtain dealiasing
get_dealiasing(trunc,nlat_half) = (4nlat_half)/(trunc+1) - 1

"""
$(TYPEDSIGNATURES)
For the grid resolution parameter `nlat_half` (e.g. 24 for a 48-ring FullGaussianGrid)
Expand Down
14 changes: 10 additions & 4 deletions src/SpeedyTransforms/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,14 @@ function Base.show(io::IO,S::SpectralTransform{NF}) where NF
s = S.recompute_legendre ? Base.summarysize(S.Λ) : Base.summarysize(S.Λs)
s_str = prettymemory(s)

println(io,"$(typeof(S))(")
println(io," Spectral: T$mmax, $(lmax+1)x$(mmax+1) LowerTriangularMatrix{Complex{$NF}}")
println(io," Grid: $(RingGrids.get_nlat(Grid,nlat_half))-ring $Grid{$NF}")
print(io," Legendre: recompute polynomials $(S.recompute_legendre), $s_str)")
dealias = get_dealiasing(mmax,nlat_half)
truncations = ["<linear","linear","quadratic","cubic",">cubic"]
truncation = truncations[clamp(floor(Int,dealias)+1,1,5)]
dealiasing = @sprintf("%.3g",dealias)

println(io,"$(typeof(S)):")
println(io,"├ Spectral: T$mmax, $(lmax+1)x$(mmax+1) LowerTriangularMatrix{Complex{$NF}}")
println(io,"├ Grid: $(RingGrids.get_nlat(Grid,nlat_half))-ring $Grid{$NF}")
println(io,"├ Truncation: dealiasing = $dealiasing ($truncation)")
print(io,"└ Legendre: recompute polynomials $(S.recompute_legendre) ($s_str)")
end
8 changes: 3 additions & 5 deletions src/dynamics/atmospheres.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,7 @@ Base.@kwdef struct EarthAtmosphere <: AbstractAtmosphere
end

function Base.show(io::IO,atm::AbstractAtmosphere)
print(io,"$(typeof(atm)):")
for key in propertynames(atm)
val = getfield(atm,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(atm))")
keys = propertynames(atm)
print_fields(io,atm,keys)
end
6 changes: 6 additions & 0 deletions src/dynamics/constants.jl
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ Base.@kwdef struct DynamicsConstants{NF<:AbstractFloat} <: AbstractDynamicsConst
temp_ref_profile::Vector{NF}
end

function Base.show(io::IO,C::DynamicsConstants)
println(io,"$(typeof(C)) <: AbstractDynamicsConstants")
keys = propertynames(C)
print_fields(io,C,keys)
end

"""
$(TYPEDSIGNATURES)
Generator function for a DynamicsConstants struct.
Expand Down
8 changes: 3 additions & 5 deletions src/dynamics/drag.jl
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
function Base.show(io::IO,F::AbstractDrag)
print(io,"$(typeof(F)) <: AbstractDrag:")
for key in propertynames(F)
val = getfield(F,key)
val isa AbstractArray || print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(F)) <: AbstractDrag")
keys = propertynames(F)
print_fields(io,F,keys)
end

## NO DRAG
Expand Down
8 changes: 3 additions & 5 deletions src/dynamics/forcing.jl
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
function Base.show(io::IO,F::AbstractForcing)
print(io,"$(typeof(F)) <: AbstractForcing:")
for key in propertynames(F)
val = getfield(F,key)
val isa AbstractArray || print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(F)) <: AbstractForcing")
keys = propertynames(F)
print_fields(io,F,keys)
end

## NO FORCING
Expand Down
13 changes: 4 additions & 9 deletions src/dynamics/horizontal_diffusion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,10 @@ function HyperDiffusion(spectral_grid::SpectralGrid;kwargs...)
return HyperDiffusion{NF}(;trunc,nlev,kwargs...)
end

function Base.show(io::IO,HD::HyperDiffusion)
print(io,"$(typeof(HD)):")
keys = (:trunc,:nlev,:power,:time_scale,:resolution_scaling,:power_stratosphere,
:tapering_σ,:adaptive,:vor_max,:adaptive_strength)
for key in keys
val = getfield(HD,key)
s = "\n $key::$(typeof(val)) = $val"
print(io,s)
end
function Base.show(io::IO,HD::HorizontalDiffusion)
println(io,"$(typeof(HD))")
keys = propertynames(HD)
print_fields(io,HD,keys,arrays=false)
end

"""$(TYPEDSIGNATURES)
Expand Down
20 changes: 6 additions & 14 deletions src/dynamics/implicit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,9 @@ function ImplicitShallowWater(spectral_grid::SpectralGrid;kwargs...)
end

function Base.show(io::IO,I::ImplicitShallowWater)
print(io,"$(typeof(I)):")
keys = (:trunc,)
for key in keys
val = getfield(I,key)
s = "\n $key::$(typeof(val)) = $val"
print(io,s)
end
println(io,"$(typeof(I)) <: AbstractImplicit")
keys = propertynames(I)
print_fields(io,I,keys)
end

# function barrier to unpack the constants struct for shallow water
Expand Down Expand Up @@ -192,13 +188,9 @@ function ImplicitPrimitiveEq(spectral_grid::SpectralGrid,kwargs...)
end

function Base.show(io::IO,I::ImplicitPrimitiveEq)
print(io,"$(typeof(I)):")
keys = (:trunc,:nlev,)
for key in keys
val = getfield(I,key)
s = "\n $key::$(typeof(val)) = $val"
print(io,s)
end
println(io,"$(typeof(I)) <: AbstractImplicit")
keys = propertynames(I)
print_fields(io,I,keys)
end

# function barrier to unpack the constants struct for primitive eq models
Expand Down
8 changes: 3 additions & 5 deletions src/dynamics/initial_conditions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,9 @@ Base.@kwdef struct ZonalJet <: InitialConditions
end

function Base.show(io::IO,IC::InitialConditions)
print(io,"$(typeof(IC)) <: InitialConditions:")
for key in propertynames(IC)
val = getfield(IC,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(IC)) <: InitialConditions")
keys = propertynames(IC)
print_fields(io,IC,keys)
end

"""
Expand Down
18 changes: 17 additions & 1 deletion src/dynamics/models.jl
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,20 @@ end
Returns true if the model `M` has a prognostic variable `var_name`, false otherwise.
The default fallback is that all variables are included. """
has(M::Type{<:ModelSetup}, var_name::Symbol) = var_name in (:vor, :div, :temp, :humid, :pres)
has(M::ModelSetup, var_name) = has(typeof(M), var_name)
has(M::ModelSetup, var_name) = has(typeof(M), var_name)

function Base.show(io::IO,M::ModelSetup)
println(io,"$(typeof(M))")
for key in propertynames(M)[1:end-1]
val = getfield(M,key)
println(io,"$key: $(typeof(val))")
end
println(io,"└ feedback: $(typeof(M.feedback))")
end

function Base.show(io::IO,S::Simulation)
println(io,"$(typeof(S))")
println(io,"$(typeof(S.model))")
println(io,"$(typeof(S.prognostic_variables))")
print(io, "$(typeof(S.diagnostic_variables))")
end
25 changes: 4 additions & 21 deletions src/dynamics/orography.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ function NoOrography(spectral_grid::SpectralGrid)
return NoOrography{NF,Grid{NF}}(orography,geopot_surf)
end

function Base.show(io::IO,orog::NoOrography)
print(io,"$(typeof(orog))")
function Base.show(io::IO,orog::AbstractOrography)
println(io,"$(typeof(orog)) <: AbstractOrography")
keys = propertynames(orog)
print_fields(io,orog,keys)
end

# no further initialization needed
Expand All @@ -44,15 +46,6 @@ Base.@kwdef struct ZonalRidge{NF<:AbstractFloat,Grid<:AbstractGrid{NF}} <: Abstr
geopot_surf::LowerTriangularMatrix{Complex{NF}}
end

function Base.show(io::IO,orog::ZonalRidge)
print(io,"$(typeof(orog)):")
keys = (:η₀,:u₀)
for key in keys
val = getfield(orog,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
end

"""
$(TYPEDSIGNATURES)
Generator function pulling the resolution information from `spectral_grid`."""
Expand Down Expand Up @@ -146,16 +139,6 @@ function EarthOrography(spectral_grid::SpectralGrid;kwargs...)
return EarthOrography{NF,Grid{NF}}(;orography,geopot_surf,kwargs...)
end

function Base.show(io::IO,orog::EarthOrography)
print(io,"$(typeof(orog)):")
keys = (:path,:file,:scale,:smoothing,:smoothing_power,
:smoothing_strength,:smoothing_truncation)
for key in keys
val = getfield(orog,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
end

"""
$(TYPEDSIGNATURES)
Initialize the arrays `orography`,`geopot_surf` in `orog` by reading the
Expand Down
8 changes: 3 additions & 5 deletions src/dynamics/planets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ Base.@kwdef struct Earth <: AbstractPlanet
end

function Base.show(io::IO,planet::AbstractPlanet)
print(io,"$(typeof(planet)):")
for key in propertynames(planet)
val = getfield(planet,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(planet)) <: AbstractPlanet")
keys = propertynames(planet)
print_fields(io,planet,keys)
end
22 changes: 15 additions & 7 deletions src/dynamics/spectral_grid.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,22 @@ SpectralGrid(Grid::Type{<:AbstractGrid};kwargs...) = SpectralGrid(;Grid,kwargs..
SpectralGrid(NF::Type{<:AbstractFloat},Grid::Type{<:AbstractGrid};kwargs...) = SpectralGrid(;NF,Grid,kwargs...)

function Base.show(io::IO,SG::SpectralGrid)
(;NF,trunc,Grid,dealiasing,radius,nlat_half,npoints,nlev,vertical_coordinates) = SG
truncation = if dealiasing < 2 "linear" elseif dealiasing < 3 "quadratic" else "cubic" end
res = sqrt(4π*radius^2/npoints)/1000 # in [km]
(;NF,trunc,Grid,radius,nlat_half,npoints,nlev,vertical_coordinates) = SG
# truncation = if dealiasing < 2 "linear" elseif dealiasing < 3 "quadratic" else "cubic" end

# resolution information
res_ave = sqrt(4π*radius^2/npoints)/1000 # in [km]
res_eq_x = 2π*radius/RingGrids.get_nlon_max(Grid,nlat_half)/1000
lat = get_lat(Grid,nlat_half)
res_eq_y = (lat[nlat_half] - lat[nlat_half+1])*radius/1000

s(x) = @sprintf("%.3g",x)

println(io,"$(typeof(SG)):")
println(io," Spectral: T$trunc LowerTriangularMatrix{Complex{$NF}}, radius = $radius m")
println(io," Grid: $npoints-element, $(get_nlat(Grid,nlat_half))-ring $Grid{$NF} ($truncation)")
println(io," Resolution: $(@sprintf("%.3g",res))km (average)")
print(io," Vertical: $nlev-level $(typeof(vertical_coordinates))")
println(io," Spectral: T$trunc LowerTriangularMatrix{Complex{$NF}}, radius = $radius m")
println(io," Grid: $(get_nlat(Grid,nlat_half))-ring $Grid{$NF}, $npoints grid points")
println(io," Resolution: $(s(res_ave))km (average), $(s(res_eq_x))km × $(s(res_eq_y))km (Equator)")
print(io," Vertical: $nlev-level $(typeof(vertical_coordinates))")
end

"""
Expand Down
8 changes: 3 additions & 5 deletions src/dynamics/time_integration.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,9 @@ function Leapfrog(spectral_grid::SpectralGrid;kwargs...)
end

function Base.show(io::IO,L::Leapfrog)
print(io,"$(typeof(L)):")
for key = propertynames(L)
val = getfield(L,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(L)) <: TimeStepper")
keys = propertynames(L)
print_fields(io,L,keys)
end

"""
Expand Down
8 changes: 4 additions & 4 deletions src/dynamics/vertical_coordinates.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ SigmaCoordinates(σ_half::AbstractVector) = SigmaCoordinates(nlev=length(σ_half
SigmaCoordinates(σ_half::AbstractRange) = SigmaCoordinates(collect(σ_half))

function Base.show(io::IO::SigmaCoordinates)
println("$(σ.nlev)-level SigmaCoordinates:")
println("$(σ.nlev)-level SigmaCoordinates")
nchars = length(string.nlev))
format = Printf.Format("%$(nchars)d")
for k=1:σ.nlev
println(" k=",Printf.format(format,k-1),".5 -- ",@sprintf("%1.4f".σ_half[k]))
println("├─ ", @sprintf("%1.4f".σ_half[k])," k = ",Printf.format(format,k-1),".5")
σk =.σ_half[k] + σ.σ_half[k+1])/2
println(" k=",Printf.format(format,k)," × ",@sprintf("%1.4f",σk))
println("│× ",@sprintf("%1.4f",σk)," k = ",Printf.format(format,k))
end
print(" k=",Printf.format(format,σ.nlev),".5 -- ",@sprintf("%1.4f".σ_half[end]))
print("└─ ",@sprintf("%1.4f".σ_half[end])," k = ",Printf.format(format,σ.nlev),".5")
end

"""Coefficients of the generalised logistic function to describe the vertical coordinate.
Expand Down
8 changes: 3 additions & 5 deletions src/output/output.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@ Base.@kwdef struct Keepbits
end

function Base.show(io::IO,K::Keepbits)
print(io,"$(typeof(K)):")
for key in propertynames(K)
val = getfield(K,key)
print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(K))")
keys = propertynames(K)
print_fields(io,K,keys)
end

# default number format for output
Expand Down
8 changes: 3 additions & 5 deletions src/physics/pretty_printing.jl
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
# print all fields with type <: Number
function Base.show(io::IO,P::AbstractParameterization)
print(io,"$(typeof(P)):")
for key in propertynames(P)
val = getfield(P,key)
val isa Number && print(io,"\n $key::$(typeof(val)) = $val")
end
println(io,"$(typeof(P)) <: $(supertype(typeof(P)))")
keys = propertynames(P)
print_fields(io,P,keys)
end
31 changes: 30 additions & 1 deletion src/utility_functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,33 @@ end
A = nans(dims...)
Allocate A::Array{Float64} with NaNs."""
nans(dims...) = nans(Float64,dims...)
nans(dims...) = nans(Float64,dims...)

"""
$(TYPEDSIGNATURES)
Prints to `io` all fields of a struct `A` identified by their
`keys`."""
function print_fields(io::IO,A,keys;arrays::Bool=false)
keys_filtered = arrays ? keys : filter(key -> ~(getfield(A,key) isa AbstractArray),keys)
n = length(keys_filtered)
filtered = n < length(keys)
for (i,key) in enumerate(keys_filtered)
last = (i == n) & ~filtered
key = keys[i]
val = getfield(A,key)
~last ? println(io,"$key::$(typeof(val)) = $val") :
print(io, "$key::$(typeof(val)) = $val")
end
if filtered # add the names of arrays
s = "└── arrays: "
for key in keys
if ~(key in keys_filtered)
s *= "$key, "
end
end

# remove last ", "
s_without_comma = s[1:prevind(s,findlast(==(','), s))]
print(io,s_without_comma)
end
end

0 comments on commit ee923e7

Please sign in to comment.