Skip to content

Instantly share code, notes, and snippets.

@mkitti
Created January 23, 2022 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkitti/b34206ee3dcd4699ed4062d986d61206 to your computer and use it in GitHub Desktop.
Save mkitti/b34206ee3dcd4699ed4062d986d61206 to your computer and use it in GitHub Desktop.
# Implementing cell 6 of https://github.com/barbagroup/CFDPython/blob/master/lessons/06_Array_Operations_with_NumPy.ipynb
# Inspried during stream of https://www.twitch.tv/brainrpg
function main()
nx = 81
ny = 81
nt = 100
c = 1
dx = 2 / (nx - 1)
dy = 2 / (ny - 1)
sigma = .2
dt = sigma * dx
# This lighter weight than using StepRangeLen via range
# "Compared to using range, directly constructing a LinRange should have less overhead but won't try to correct for floating point errors"
x = LinRange(0, 2, nx)
y = LinRange(0, 2, ny)
u = ones(ny, nx)
@time begin
t = 1:nt
# u[19:40, 19:40] .= 2
u[Int(.5 / dy - 1): Int(1 / dy), Int(.5 / dx - 1):Int(1 / dx)] .= 2
u_yx = @view u[begin+1:end, begin+1:end]
un = similar(u)
un_yx = @view un[begin+1:end, begin+1:end]
un_y = @view un[begin+1:end, :]
un_x = @view un[: , begin+1:end]
# Strongly consider the use of @inbounds
for tn in t
# The copy may not be necessary in this iteration, but may be needed later
# Here we replace un in-place to prevent allocation and to reuse the views
un .= u
u_yx .= un_yx .-
c * dt / dx * diff(un_y, dims=2) .-
c * dt / dy * diff(un_x, dims=1)
u[begin, : ] .= 1
u[end , : ] .= 1
u[: , begin] .= 1
u[: , end ] .= 1
end
end
return u
end # function main
@mkitti
Copy link
Author

mkitti commented Jan 23, 2022

Instead of un .= u we could also do copyto!(un, u)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment