licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
393
const _package_version = Base.VersionNumber( TOML.parsefile(joinpath(dirname(@__DIR__), "Project.toml"))["version"] ) function _initialize_download_cache() folder_name = "downloaded_files-$(_package_version)" global download_cache = Scratch.get_scratch!(@__MODULE__, folder_name) return nothing end function __init__() _initialize_download_cache() return nothing end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
216
Base.@kwdef struct Class domain::String system::String value::String end function DiagnosisClass(; system, value) domain = "diagnosis" class = Class(; domain, system, value) return class end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
286
function construct_icd10(icd10::AbstractString) system = "ICD10" value = icd10_add_dots(icd10) return DiagnosisClass(; system, value) end function construct_ccs10(ccs10::AbstractString) system = "CCS10" value = ccs10 return DiagnosisClass(; system, value) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
276
function construct_icd9(icd9::AbstractString) system = "ICD9" value = icd9_add_dots(icd9) return DiagnosisClass(; system, value) end function construct_ccs9(ccs9::AbstractString) system = "CCS9" value = ccs9 return DiagnosisClass(; system, value) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
1396
function icd10_add_dots(icd10::AbstractString) ### Input is too short for a dot r1 = r"^([A-Z][A-Z\d][A-Z\d])$" m1 = match(r1, icd10) if m1 !== nothing return "$(m1[1])"::String end ### Input contains a dot r2 = r"^([A-Z][A-Z\d][A-Z\d])\.([A-Z\d][A-Z\d]?[A-Z\d]?[A-Z\d]?)$" m2 = match(r2, icd10) if m2 !== nothing return "$(m2[1]).$(m2[2])"::String end ### Input does not contain a dot r3 = r"^([A-Z][A-Z\d][A-Z\d])([A-Z\d][A-Z\d]?[A-Z\d]?[A-Z\d]?)$" m3 = match(r3, icd10) if m3 !== nothing return "$(m3[1]).$(m3[2])"::String end msg = "Invalid ICD-10-CM code: $(icd10)" throw(ErrorException(msg)) end function icd10_remove_dots(icd10::AbstractString) ### Input is too short for a dot r1 = r"^([A-Z][A-Z\d][A-Z\d])$" m1 = match(r1, icd10) if m1 !== nothing return "$(m1[1])"::String end ### Input contains a dot r2 = r"^([A-Z][A-Z\d][A-Z\d])\.([A-Z\d][A-Z\d]?[A-Z\d]?[A-Z\d]?)$" m2 = match(r2, icd10) if m2 !== nothing return "$(m2[1])$(m2[2])"::String end ### Input does not contain a dot r3 = r"^([A-Z][A-Z\d][A-Z\d])([A-Z\d][A-Z\d]?[A-Z\d]?[A-Z\d]?)$" m3 = match(r3, icd10) if m3 !== nothing return "$(m3[1])$(m3[2])"::String end msg = "Invalid ICD-10-CM code: $(icd10)" throw(ErrorException(msg)) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
2238
function icd9_add_dots(icd9::AbstractString) ### Input is too short for a dot # Regular codes and V codes r1 = r"^([\dV]\d\d)$" m1 = match(r1, icd9) if m1 !== nothing return "$(m1[1])"::String end # E codes r2 = r"^(E\d\d\d)$" m2 = match(r2, icd9) if m2 !== nothing return "$(m2[1])"::String end ### Input contains a dot # Regular codes and V codes r3 = r"^([\dV]\d\d)\.(\d\d?\d?)$" m3 = match(r3, icd9) if m3 !== nothing return "$(m3[1]).$(m3[2])"::String end # E codes r4 = r"^(E\d\d\d)\.(\d)$" m4 = match(r4, icd9) if m4 !== nothing return "$(m4[1]).$(m4[2])"::String end ### Input does not contain a dot # Regular codes and V codes r3 = r"^([\dV]\d\d)(\d\d?\d?)$" m3 = match(r3, icd9) if m3 !== nothing return "$(m3[1]).$(m3[2])"::String end # E codes r4 = r"^(E\d\d\d)(\d)$" m4 = match(r4, icd9) if m4 !== nothing return "$(m4[1]).$(m4[2])"::String end msg = "Invalid ICD-9-CM code: $(icd9)" throw(ErrorException(msg)) end function icd9_remove_dots(icd9::AbstractString) ### Input is too short for a dot # Regular codes and V codes r1 = r"^([\dV]\d\d)$" m1 = match(r1, icd9) if m1 !== nothing return "$(m1[1])"::String end # E codes r2 = r"^(E\d\d\d)$" m2 = match(r2, icd9) if m2 !== nothing return "$(m2[1])"::String end ### Input contains a dot # Regular codes and V codes r3 = r"^([\dV]\d\d)\.(\d\d?\d?)$" m3 = match(r3, icd9) if m3 !== nothing return "$(m3[1])$(m3[2])"::String end # E codes r4 = r"^(E\d\d\d)\.(\d)$" m4 = match(r4, icd9) if m4 !== nothing return "$(m4[1])$(m4[2])"::String end ### Input does not contain a dot # Regular codes and V codes r3 = r"^([\dV]\d\d)(\d\d?\d?)$" m3 = match(r3, icd9) if m3 !== nothing return "$(m3[1])$(m3[2])"::String end # E codes r4 = r"^(E\d\d\d)(\d)$" m4 = match(r4, icd9) if m4 !== nothing return "$(m4[1])$(m4[2])"::String end msg = "Invalid ICD-9-CM code: $(icd9)" throw(ErrorException(msg)) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
2144
@testset "TODO: fix this code" begin Class = DiagnosisClassification.Class generate_ccs9_to_icd9 = DiagnosisClassification.generate_ccs9_to_icd9 construct_icd9 = DiagnosisClassification.construct_icd9 construct_ccs9 = DiagnosisClassification.construct_ccs9 generate_ccs10_to_icd10 = DiagnosisClassification.generate_ccs10_to_icd10 construct_icd10 = DiagnosisClassification.construct_icd10 construct_ccs10 = DiagnosisClassification.construct_ccs10 @testset "generate_ccs9_to_icd9" begin ccs9_to_icd9_struct = generate_ccs9_to_icd9() ccs9_to_icd9 = ccs9_to_icd9_struct.ccs9_to_icd9 ccs9_to_ccs_description = ccs9_to_icd9_struct.ccs9_to_ccs_description @test ccs9_to_icd9 isa Dict{Class, Set{Class}}; @test ccs9_to_ccs_description isa Dict{Class, String}; @test !isempty(ccs9_to_icd9); @test !isempty(ccs9_to_ccs_description); @test ccs9_to_ccs_description[construct_ccs9("1")] == "Tuberculosis" @test ccs9_to_ccs_description[construct_ccs9("1")] != "Septicemia" @test construct_icd9("011.00") in ccs9_to_icd9[construct_ccs9("1")]; @test !(construct_icd9("031.2") in ccs9_to_icd9[construct_ccs9("1")]); end @testset "generate_ccs10_to_icd10" begin ccs10_to_icd10_struct = generate_ccs10_to_icd10() ccs10_to_icd10 = ccs10_to_icd10_struct.ccs10_to_icd10 ccs10_to_ccs_description = ccs10_to_icd10_struct.ccs10_to_ccs_description @test ccs10_to_icd10 isa Dict{Class, Set{Class}}; @test ccs10_to_ccs_description isa Dict{Class, String}; @test !isempty(ccs10_to_icd10); @test !isempty(ccs10_to_ccs_description); @test ccs10_to_ccs_description[construct_ccs10("INF001")] == "Tuberculosis" @test ccs10_to_ccs_description[construct_ccs10("INF001")] != "Septicemia" @test construct_icd10("A15.7") in ccs10_to_icd10[construct_ccs10("INF001")]; @test !(construct_icd10("A31.2") in ccs10_to_icd10[construct_ccs10("INF001")]); end end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
814
@testset "dict_utils" begin setindex_no_overwrite! = DiagnosisClassification.setindex_no_overwrite! setindex_same_value! = DiagnosisClassification.setindex_same_value! @testset "setindex_no_overwrite!" begin dict = Dict{String, String}() @test setindex_no_overwrite!(dict, "hello", "world") isa Nothing @test_throws ErrorException setindex_no_overwrite!(dict, "hello", "world2") end @testset "setindex_same_value!" begin dict = Dict{String, String}() @test setindex_same_value!(dict, "hello", "world") isa Nothing @test setindex_same_value!(dict, "hello", "world") isa Nothing @test setindex_same_value!(dict, "hello", "world") isa Nothing @test_throws ErrorException setindex_same_value!(dict, "hello", "world2") end end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
792
@testset "download" begin ensure_downloaded_files = DiagnosisClassification.ensure_downloaded_files force_download_files = DiagnosisClassification.force_download_files @test ensure_downloaded_files() isa String @test ensure_downloaded_files() isa String mktempdir() do dir @test force_download_files(dir) isa Nothing end ccs9_filename = joinpath(ensure_downloaded_files(), "ccs9.txt") ccs10_filename = joinpath(ensure_downloaded_files(), "ccs10.csv") @test isfile(ccs9_filename) @test isfile(ccs10_filename) @test !isempty(strip(read(ccs9_filename, String))); @test !isempty(strip(read(ccs10_filename, String))); ccs10_file = CSV.File(ccs10_filename) @test length(ccs10_file) > 100 @test length(ccs10_file[1]) > 5 end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
161
@testset "init" begin _initialize_download_cache = DiagnosisClassification._initialize_download_cache @test _initialize_download_cache() isa Nothing end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
450
using DiagnosisClassification using Test import CSV @testset "DiagnosisClassification.jl" begin include("dict_utils.jl") include("download.jl") include("init.jl") include("types.jl") @testset "convenience" begin include("convenience/icd9.jl") include("convenience/icd10.jl") end @testset "dots" begin include("dots/icd9.jl") include("dots/icd10.jl") end include("TODO.jl") end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
324
@testset "types" begin Class = DiagnosisClassification.Class DiagnosisClass = DiagnosisClassification.DiagnosisClass @testset begin domain = "diagnosis" system = "hello" value = "world" @test DiagnosisClass(; system, value) == Class(; domain, system, value) end end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
585
@testset "icd10" begin DiagnosisClass = DiagnosisClassification.DiagnosisClass construct_icd10 = DiagnosisClassification.construct_icd10 construct_ccs10 = DiagnosisClassification.construct_ccs10 @test construct_icd10("W55.29XA") == DiagnosisClass(; system = "ICD10", value = "W55.29XA", ) @test construct_icd10("W5529XA") == DiagnosisClass(; system = "ICD10", value = "W55.29XA", ) @test construct_ccs10("helloworld123") == DiagnosisClass(; system = "CCS10", value = "helloworld123", ) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
537
@testset "icd9" begin DiagnosisClass = DiagnosisClassification.DiagnosisClass construct_icd9 = DiagnosisClassification.construct_icd9 construct_ccs9 = DiagnosisClassification.construct_ccs9 @test construct_icd9("V01.71") == DiagnosisClass(; system = "ICD9", value = "V01.71", ) @test construct_icd9("V0171") == DiagnosisClass(; system = "ICD9", value = "V01.71", ) @test construct_ccs9("123") == DiagnosisClass(; system = "CCS9", value = "123", ) end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
3889
@testset "icd10" begin icd10_add_dots = DiagnosisClassification.icd10_add_dots icd10_remove_dots = DiagnosisClassification.icd10_remove_dots @testset "icd10_add_dots" begin test_cases = [ # Input is too short for a dot "W55" => "W55", "Z67" => "Z67", # Input contains a dot "W55.2" => "W55.2", "W55.29" => "W55.29", "W55.29X" => "W55.29X", "W55.29XA" => "W55.29XA", "Z67.4" => "Z67.4", "Z67.41" => "Z67.41", # Input does not contain a dot "W552" => "W55.2", "W5529" => "W55.29", "W5529X" => "W55.29X", "W5529XA" => "W55.29XA", "Z674" => "Z67.4", "Z6741" => "Z67.41", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd10_add_dots(input) == expected_output end @test_throws ErrorException icd10_add_dots("") end @testset "icd10_remove_dots" begin test_cases = [ # Input is too short for a dot "W55" => "W55", "Z67" => "Z67", # Input contains a dot "W55.2" => "W552", "W55.29" => "W5529", "W55.29X" => "W5529X", "W55.29XA" => "W5529XA", "Z67.4" => "Z674", "Z67.41" => "Z6741", # Input does not contain a dot "W552" => "W552", "W5529" => "W5529", "W5529X" => "W5529X", "W5529XA" => "W5529XA", "Z674" => "Z674", "Z6741" => "Z6741", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd10_remove_dots(input) == expected_output end @test_throws ErrorException icd10_remove_dots("") end @testset "Roundtrip icd10_add_dots" begin test_cases = [ # Input is too short for a dot "W55" => "W55", "Z67" => "Z67", # Input contains a dot "W55.2" => "W552", "W55.29" => "W5529", "W55.29X" => "W5529X", "W55.29XA" => "W5529XA", "Z67.4" => "Z674", "Z67.41" => "Z6741", # Input does not contain a dot "W552" => "W552", "W5529" => "W5529", "W5529X" => "W5529X", "W5529XA" => "W5529XA", "Z674" => "Z674", "Z6741" => "Z6741", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd10_remove_dots(icd10_add_dots(input)) == expected_output end end @testset "Roundtrip icd10_remove_dots" begin test_cases = [ # Input is too short for a dot "W55" => "W55", "Z67" => "Z67", # Input contains a dot "W55.2" => "W55.2", "W55.29" => "W55.29", "W55.29X" => "W55.29X", "W55.29XA" => "W55.29XA", "Z67.4" => "Z67.4", "Z67.41" => "Z67.41", # Input does not contain a dot "W552" => "W55.2", "W5529" => "W55.29", "W5529X" => "W55.29X", "W5529XA" => "W55.29XA", "Z674" => "Z67.4", "Z6741" => "Z67.41", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd10_add_dots(icd10_remove_dots(input)) == expected_output end end end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
code
3595
@testset "icd9" begin icd9_add_dots = DiagnosisClassification.icd9_add_dots icd9_remove_dots = DiagnosisClassification.icd9_remove_dots @testset "icd9_add_dots" begin test_cases = [ # Input is too short for a dot "003" => "003", "V01" => "V01", "E000" => "E000", # Input contains a dot "003.2" => "003.2", "003.20" => "003.20", "V01.7" => "V01.7", "V01.71" => "V01.71", "E000.0" => "E000.0", # Input does not contain a dot "0032" => "003.2", "00320" => "003.20", "V017" => "V01.7", "V0171" => "V01.71", "E0000" => "E000.0", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd9_add_dots(input) == expected_output end @test_throws ErrorException icd9_add_dots("") end @testset "icd9_remove_dots" begin test_cases = [ # Input is too short for a dot "003" => "003", "V01" => "V01", "E000" => "E000", # Input contains a dot "003.2" => "0032", "003.20" => "00320", "V01.7" => "V017", "V01.71" => "V0171", "E000.0" => "E0000", # Input does not contain a dot "0032" => "0032", "00320" => "00320", "V017" => "V017", "V0171" => "V0171", "E0000" => "E0000", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd9_remove_dots(input) == expected_output end @test_throws ErrorException icd9_remove_dots("") end @testset "Roundtrip icd9_add_dots" begin test_cases = [ # Input is too short for a dot "003" => "003", "V01" => "V01", "E000" => "E000", # Input contains a dot "003.2" => "0032", "003.20" => "00320", "V01.7" => "V017", "V01.71" => "V0171", "E000.0" => "E0000", # Input does not contain a dot "0032" => "0032", "00320" => "00320", "V017" => "V017", "V0171" => "V0171", "E0000" => "E0000", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd9_remove_dots(icd9_add_dots(input)) == expected_output end end @testset "Roundtrip icd9_remove_dots" begin test_cases = [ # Input is too short for a dot "003" => "003", "V01" => "V01", "E000" => "E000", # Input contains a dot "003.2" => "003.2", "003.20" => "003.20", "V01.7" => "V01.7", "V01.71" => "V01.71", "E000.0" => "E000.0", # Input does not contain a dot "0032" => "003.2", "00320" => "003.20", "V017" => "V01.7", "V0171" => "V01.71", "E0000" => "E000.0", ] for test_case in test_cases input = test_case[1] expected_output = test_case[2] @test icd9_add_dots(icd9_remove_dots(input)) == expected_output end end end
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
docs
668
# DiagnosisClassification [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaHealth.github.io/DiagnosisClassification.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaHealth.github.io/DiagnosisClassification.jl/dev) [![Build Status](https://github.com/JuliaHealth/DiagnosisClassification.jl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/JuliaHealth/DiagnosisClassification.jl/actions/workflows/ci.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/JuliaHealth/DiagnosisClassification.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/JuliaHealth/DiagnosisClassification.jl)
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
1.0.0
e044808e0bffd6932140479d57d2ed7e8b565be2
docs
254
```@meta CurrentModule = DiagnosisClassification ``` # DiagnosisClassification Documentation for [DiagnosisClassification](https://github.com/JuliaHealth/DiagnosisClassification.jl). ```@index ``` ```@autodocs Modules = [DiagnosisClassification] ```
DiagnosisClassification
https://github.com/JuliaHealth/DiagnosisClassification.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
1476
using Documenter, CanopyOptics using Literate, UnitfulEquivalences, Distributions, Plots pyplot() ENV["PYTHON"]="" function build() tutorials = ["bilambertian.jl", "specular.jl"] # , tutorials_paths = [joinpath(@__DIR__, "src", "pages", "tutorials", tutorial) for tutorial in tutorials] for tutorial in tutorials_paths Literate.markdown(tutorial, joinpath(@__DIR__, "src", "pages", "tutorials")) end tutorials_md = [joinpath("pages", "tutorials", tutorial[1:end-3]) * ".md" for tutorial in tutorials] pages = Any[ "Home" => "index.md", "Tutorials" => tutorials_md ] mathengine = MathJax(Dict( :TeX => Dict( :equationNumbers => Dict(:autoNumber => "AMS"), :Macros => Dict(), ), )) format = Documenter.HTML( #assets = [ # asset("https://fonts.googleapis.com/css?family=Montserrat|Source+Code+Pro&display=swap", class=:css), # ], prettyurls = get(ENV, "CI", nothing) == "true", mathengine = mathengine, collapselevel = 1, ) makedocs( sitename = "Canopy Optics", format = format, clean = false, modules = [CanopyOptics], pages = pages) end build() deploydocs( repo = "github.com/RemoteSensingTools/CanopyOptics.jl.git", target = "build", push_preview = true, )
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
1698
# # Bilambertian Canopy Scattering # Using packages: using Plots, Distributions using CanopyOptics theme(:ggplot2) # Compute quadrature points: μ,w = CanopyOptics.gauleg(20,0.0,1.0) # Use standard planophile leaf distribution: LD = CanopyOptics.planophile_leaves2() # Use a Bilambertian model and specify Reflectance R and Transmission T BiLambMod = CanopyOptics.BiLambertianCanopyScattering(R=0.4,T=0.2) # Compute Scattering Matrices 𝐙⁺⁺, 𝐙⁻⁺ for 0th Fourier moment: 𝐙⁺⁺, 𝐙⁻⁺ = CanopyOptics.compute_Z_matrices(BiLambMod, μ, LD, 0) # Plots matrices (shows single scattering contributions for incoming and outgoing directions) l = @layout [a b] p1 = contourf(μ, μ, 𝐙⁻⁺, title="Z⁻⁺ (Reflection)", xlabel="μꜜ", ylabel="μꜛ") p2 = contourf(μ, μ, 𝐙⁺⁺, title="Z⁺⁺ (Transmission)", xlabel="μꜛ", ylabel="μꜛ") plot(p1, p2, layout = l, margin=5Plots.mm) plot!(size=(900,350)) # ### Animation over different Beta leaf distributions steps = 0.1:0.1:5 α = [collect(steps); 5*ones(length(steps))] β = [ 5*ones(length(steps)); reverse(collect(steps));] x = 0:0.01:1 anim = @animate for i ∈ eachindex(α) LD = CanopyOptics.LeafDistribution(Beta(α[i],β[i]), 2/π) Z⁺⁺, Z⁻⁺ = CanopyOptics.compute_Z_matrices(BiLambMod, μ, LD, 0) l = @layout [a b c] p0 = plot(rad2deg.(π * x/2), pdf.(LD.LD,x), legend=false, ylim=(0,3), title="Leaf angle distribution", xlabel="Θ (degrees)") p1 = contourf(μ, μ, Z⁻⁺, title="Z⁻⁺ (Reflection)", xlabel="μꜜ", ylabel="μꜛ",clims=(0.5,2)) p2 = contourf(μ, μ, Z⁺⁺, title="Z⁺⁺ (Transmission)", xlabel="μꜛ", ylabel="μꜛ",clims=(0.5,2)) plot(p0, p1, p2, layout = l, margin=5Plots.mm) plot!(size=(1100,300)) end gif(anim, "anim_fps10.gif", fps = 10)
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
1793
# # Specular Canopy Scattering # Using packages: using Plots, Distributions using CanopyOptics pyplot() # theme(:ggplot2) # Create a specular model with refractive index and "roughness" κ specularMod = CanopyOptics.SpecularCanopyScattering(nᵣ=1.5, κ=0.2) # Use standard planophile leaf distribution: LD = CanopyOptics.planophile_leaves2() # Create some discretized angles: # Azimuth (in radians) ϕ = range(0.0, 2π, length=200); # Polar angle as cos(Θ) μ,w = CanopyOptics.gauleg(180,0.0,1.0); # Create directional vectors: dirs = [CanopyOptics.dirVector_μ(a,b) for a in μ, b in ϕ]; # Compute specular reflectance: R = CanopyOptics.compute_reflection.([specularMod], [dirs[50,1]], dirs, [LD]); # Polar plot of reflectance contourf(ϕ, acos.(μ), R,proj=:polar, ylim=(0,π/2), alpha=0.8) # ### Animation over different Beta leaf distributions steps = 0.1:0.1:5 α = [collect(steps); 5*ones(length(steps))] β = [ 5*ones(length(steps)); reverse(collect(steps));] x = 0:0.01:1 l = @layout [a b; c d; e f] anim = @animate for i ∈ eachindex(α) LD = CanopyOptics.LeafDistribution(Beta(α[i],β[i]), 2/π) R = CanopyOptics.compute_reflection.([specularMod], [dirs[120,1]], dirs, [LD]) pZ = [] for m=0:3 Z⁺⁺, Z⁻⁺ = CanopyOptics.compute_Z_matrices(specularMod, μ, LD, m) push!(pZ, contourf(μ, μ, Z⁻⁺, title="Z⁻⁺ Fourier moment $m", xlabel="μꜜ", aspect_ratio = :equal, ylabel="μꜛ")) end p0 = plot(rad2deg.(π * x/2), pdf.(LD.LD,x), legend=false, ylim=(0,3), title="Leaf angle distribution", xlabel="Θ (degrees)") p1 = contourf(ϕ, acos.(μ), R, proj=:polar, ylim=(0,π/2), clims=(0,0.02), alpha=0.8,legend = :none, title="Polar plot R") plot(p0, p1, pZ..., layout = l, margin=5Plots.mm) plot!(size=(700,700)) end gif(anim, "anim_fps10.gif", fps = 10)
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
2310
module CanopyOptics ###### Julia packages to import ############ using Distributions # Distributions for angular distributions of canopy elements using FastGaussQuadrature # Quadrature points for numerical integration using Unitful # Units attached to some variable using UnitfulEquivalences # Spectral conversions using SpecialFunctions:expint # expint in Prospect using DelimitedFiles # File IO (Prospect csv File) using DocStringExtensions # Documentation using LazyArtifacts # Artifacts using LinearAlgebra # Well, guess... using Polynomials # Polynomials for some empirical functions using YAML # YAML input files using QuadGK # Numerical Integration using CUDA using ForwardDiff import SpecialFunctions.expint #"Definition of Stokes vector types:" #using vSmartMOM.Scattering: Stokes_I, Stokes_IQU, Stokes_IQUV # Filename for ProspectPro optical properties const OPTI_2021 = artifact"Prospect" * "/dataSpec_PRO.csv"; # Needs to be more modular later: FT = Float64 ###### Own files to include ################# include("initialization/constants.jl") include("types/canopy_types.jl") include("types/angle_types.jl") include("types/material_types.jl") include("utils/quadrature.jl") include("utils/canopy_angles.jl") include("utils/fresnel.jl") include("core/prospect.jl") include("core/leafAngleRoutines.jl") include("initialization/loadProspect.jl") include("initialization/default_constructors.jl") include("forest_prototyping/types.jl") include("forest_prototyping/parameters_from_yaml.jl") include("forest_prototyping/probabilities.jl") include("forest_prototyping/subroutines.jl") #include("forest_prototyping/output_check.jl") include("utils/dielectric.jl") export prospect export createLeafOpticalStruct, LeafProspectProProperties, LeafOpticalProperties, dirVector, dirVector_μ export AbstractCanopyScatteringType, BiLambertianCanopyScattering, SpecularCanopyScattering export PureIce, LiquidPureWater, LiquidSaltWater export LeafProspectProProperties, LeafOpticalProperties, dielectric # Functions: export compute_Z_matrices, prospect, compute_specular_reflection # MW stuff export wood_forward, wood_backward, afsal, asal, abs_components end # module
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
16634
"Integrated projection of leaf area for a single leaf inclination of θₗ, assumes azimuthally uniform distribution" function A(θ::FT, θₗ::FT) where FT<:Real # Suniti: why not use the expressions in Eq 35-36 from Schultis & Myneni (1987)? a = cos(θ) * cos(θₗ) #@show θ # Eq. 14.24 in Bonan et al. if θₗ ≤ (FT(π/2) - θ) #@show "<" #@show θₗ, a return a else #@show ">" b = sin(θ) * sin(θₗ) c = sqrt(sin(θₗ)^2 - cos(θ)^2) # @show θₗ, FT(2/π)*(c + a * asin(a/b)) return FT(2/π)*(c + a * asin(a/b)) end end "Integrated projection of leaf area for a single leaf inclination of θₗ, assumes azimuthally uniform distribution" function Asm(θ::FT, θₗ::FT) where FT<:Real # Suniti: Eq 35-36 from Schultis & Myneni (1987) a = cos(θ) * cos(θₗ) # Eq. 14.24 in Bonan et al. if θₗ ≤ (FT(π/2) - θ) return a else b = sin(θ) * sin(θₗ) c = sqrt(FT(1)-(a/b)^2) return FT(2/π)*(a * (acos(-a/b)-π/2) + b * c) # (1/π) * (cosθ.cosθₗ.cos⁻¹(cotθ.cotθₗ) + sinθ.sinθₗ.√(1-cot²θ.cot²θₗ)) end end """ $(FUNCTIONNAME)(μ::Array{FT}, LD::AbstractLeafDistribution; nLeg=20) Returns the integrated projection of leaf area in the direction of μ, assumes azimuthally uniform distribution and a LD distribution for leaf polar angle θ. This function is often referred to as the function O(B) (Goudriaan 1977) or G(Ζ) (Ross 1975,1981), see Bonan modeling book, eqs. 14.21-14.26. # Arguments - `μ` an array of cos(θ) (directions [0,1]) - `LD` an [`AbstractLeafDistribution`](@ref) type struct, includes a leaf distribution function - `nLeg` an optional parameter for the number of legendre polynomials to integrate over the leaf distribution (default=20) # Examples ```julia-repl julia> μ,w = CanopyOptics.gauleg(10,0.0,1.0); # Create 10 quadrature points in μ julia> LD = CanopyOptics.spherical_leaves() # Create a default spherical leaf distribution julia> G = CanopyOptics.G(μ, LD) # Compute G(μ) 10-element Vector{Float64}: 0.5002522783000879 0.5002715115149204 0.5003537989277846 0.5004432798701134 0.5005134448870893 0.5003026448466977 0.4999186257540982 0.4994511190721635 0.49907252201082375 0.49936166823681594 ``` """ function G(μ::AbstractArray{FT}, LD::AbstractLeafDistribution; nLeg=40) where FT θₗ,w = gauleg(nLeg,FT(0),FT(π/2)) b = range(FT(0),FT(π/2), length=nLeg) θₗ = (b[1:end-1] + b[2:end])/2 #@show length(θₗ ) w = π / 2 / (nLeg-1) Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling #.* sin.(θₗ) * π/2 #Fᵢ = 2/π * (1.0 .+ cos.(2θₗ)) # renormalize (needed if quadrature doesn't work) #@show sum(w' * Fᵢ) Fᵢ = Fᵢ / sum(w * Fᵢ) θ = acos.(μ) #@show size(A.(θ',θₗ)) #@show size(w * Fᵢ) G = (w * Fᵢ)' * A.(θ',θₗ) return G' end function G2(μ::AbstractArray{FT}, LD::AbstractLeafDistribution; nLeg=40) where FT μl,w = gauleg(nLeg,FT(0),FT(1)) θₗ = acos.(μl) Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling * π/2 Fᵢ = Fᵢ ./ (w'*Fᵢ) θ = acos.(μ) G = (w .* Fᵢ)' * A.(θ',θₗ) return G' end "Brute Force G calculation (for testing" function bfG(μ::Array{FT}, LD::AbstractLeafDistribution; nLeg=20) where FT nQuad = 100 ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); # Reference angles to integrate over in both ϕ and μ μ_l, w = gauleg(180,0.0,1.0); Ω_l = [dirVector_μ(a,b) for a in μ_l, b in ϕ]; θₗ = acos.(μ_l) # Have to divide by sin(θ) again to get ∂θ/∂μ for integration (weights won't work) Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling * π/2#./ abs.(sin.(θₗ)) @show Fᵢ' * w Fᵢ = Fᵢ ./ (Fᵢ' * w) #@show Fᵢ' * w res = similar(μ); for i in eachindex(μ) Ω = dirVector_μ(μ[i],0.0); #res[i] = sum(w .* Fᵢ .* A.(θ[i],θₗ)) # Double integration here: res[i] = ((Fᵢ .* abs.(dot.((Ω,),Ω_l)))' * w)' * w_azi /(2π) end return res end """ $(FUNCTIONNAME)(μ::Array{FT,1},μꜛ::Array{FT,1}, r,t, LD::AbstractLeafDistribution; nLeg = 20) Computes the azimuthally-averaged area scattering transfer function following Shultis and Myneni (https://doi.org/10.1016/0022-4073(88)90079-9), Eq 43: ``Γ(μ' -> μ) = \\int_0^1 dμ_L g_L(μ_L)[t_L Ψ⁺(μ, μ', μ_L) + r_L Ψ⁻(μ, μ', μ_L)]`` assuming an azimuthally uniform leaf angle distribution. # Arguments - `μ::Array{FT,1}` : Quadrature points incoming direction (cos(θ)) - `μꜛ::Array{FT,1}`: Quadrature points outgoing direction (cos(θ)) - `r` : Leaf lambertian reflectance - `t` : Leaf lambertian transmittance - `LD` a [`AbstractLeafDistribution`](@ref) struct that describes the leaf angular distribution function. - `nLeg = 20`: number of quadrature points used for integration over all leaf angles (default is 20). """ function compute_lambertian_Γ(μ::Array{FT,1},μꜛ::Array{FT,1}, r,t, LD::AbstractLeafDistribution; nLeg = 20) where FT Γ = zeros(length(μ), length(μ)) θₗ,w = gauleg(nLeg,FT(0),FT(π/2)) for i in eachindex(θₗ) Ψ⁺, Ψ⁻ = compute_Ψ(μ,μꜛ, cos(θₗ[i])); Γ += pdf.(LD.LD,2θₗ[i]/π) * LD.scaling * w[i] * (t * Ψ⁺ + r * Ψ⁻) end return Γ end """ $(FUNCTIONNAME)(mod::BiLambertianCanopyScattering, μ::Array{FT,1}, LD::AbstractLeafDistribution, m::Int) Computes the single scattering Z matrices (𝐙⁺⁺ for same incoming and outgoing sign of μ, 𝐙⁻⁺ for a change in direction). Internally computes the azimuthally-averaged area scattering transfer function following Shultis and Myneni (https://doi.org/10.1016/0022-4073(88)90079-9), Eq 43:: ``Γ(μ' -> μ) = \\int_0^1 dμ_L g_L(μ_L)[t_L Ψ⁺(μ, μ', μ_L) + r_L Ψ⁻(μ, μ', μ_L)]`` assuming an azimuthally uniform leaf angle distribution. Normalized Γ as 𝐙 = 4Γ/(ϖ⋅G(μ)). Returns 𝐙⁺⁺, 𝐙⁻⁺ # Arguments - `mod` : A bilambertian canopy scattering model [`BiLambertianCanopyScattering`](@ref), uses R,T,nQuad from that model. - `μ::Array{FT,1}`: Quadrature points ∈ [0,1] - `LD` a [`AbstractLeafDistribution`](@ref) struct that describes the leaf angular distribution function. - `m`: Fourier moment (for azimuthally uniform leave distributions such as here, only m=0 returns non-zero matrices) """ function compute_Z_matrices(mod::BiLambertianCanopyScattering, μ::Array{FT,1}, LD::AbstractLeafDistribution, m::Int) where FT (;R,T,nQuad) = mod # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # skip everything beyond m=0 if m>0 return 𝐙⁺⁺, 𝐙⁻⁺ end # Ross kernel G = CanopyOptics.G(μ, LD) # Single Scattering Albedo (should make this a vector too) ϖ = R+T θₗ,w = gauleg(nQuad,FT(0),FT(π/2)); for i in eachindex(θₗ) Ψ⁺, Ψ⁻ = compute_Ψ(μ,μ, cos(θₗ[i])); 𝐙⁺⁺ += pdf.(LD.LD,2θₗ[i]/π) * LD.scaling * w[i] * (T * Ψ⁺ + R * Ψ⁻) Ψ⁺, Ψ⁻ = compute_Ψ(μ,-μ, cos(θₗ[i])); 𝐙⁻⁺ += pdf.(LD.LD,2θₗ[i]/π) * LD.scaling * w[i] * (T * Ψ⁺ + R * Ψ⁻) end return 4𝐙⁺⁺ ./(G'*ϖ), 4𝐙⁻⁺ ./(G'*ϖ) end # Page 20, top of Knyazikhin and Marshak # Example # ϕ = range(0.0, 2π, length=200) # θ = range(0.0, π/2, length=150) # dirs = [dirVector(a,b) for a in θ, b in ϕ]; # R = CanopyOptics.compute_specular_reflection.([dirs[10,1]],dirs, [1.5], [0.3], [LD]) function compute_reflection(mod::SpecularCanopyScattering, Ωⁱⁿ::dirVector{FT}, Ωᵒᵘᵗ::dirVector{FT}, LD) where FT (;nᵣ,κ) = mod Ωstar = getSpecularΩ(Ωⁱⁿ, Ωᵒᵘᵗ) #θstar = min(abs(Ωstar.θ), (π-abs(Ωstar.θ))) # min(abs(Ωstar.θ), abs(π+Ωstar.θ)) θstar = Ωstar.θ; #if Ωⁱⁿ.θ ≈ Ωᵒᵘᵗ.θ && Ωⁱⁿ.ϕ ≈ Ωᵒᵘᵗ.ϕ # θstar = Ωⁱⁿ.θ #end # Still needs to be implemented! # incident angle on leaf surface (half of in and out angle): sa = Ωⁱⁿ ⋅ Ωᵒᵘᵗ sa > 1 ? sa = FT(1) : nothing αstar = acos(abs(sa))/2 #@show Ωstar.ϕ, Ωstar.θ #a = (Ωⁱⁿ ⋅ Ωstar) * (Ωᵒᵘᵗ ⋅ Ωstar) return FT(1/8) * pdf(LD.LD,2θstar/π) * LD.scaling * K(κ, αstar) * Fᵣ(nᵣ,αstar) end function compute_Γ(mod::BiLambertianCanopyScattering, Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}, LD::AbstractLeafDistribution) where FT (;R,T, nQuad) = mod #nQuad = 80 #μ_l, w = gauleg(nQuad,0.0,1.0); θₗ, w = gauleg(nQuad,FT(0),FT(π/2)); μ_l = cos.(θₗ) # Quadrature points in the azimuth (this has to go over 2π): ϕ, w_azi = gauleg(nQuad+1,FT(0),FT(2π)); Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling # Create leaf angles in μ and ϕ Ω_l = [dirVector_μ(a,b) for a in μ_l, b in ϕ]; # Compute the angles (in, leaf angles, out, leaf) integrand = ((Ωⁱⁿ,) .⋅ Ω_l) .* ((Ωᵒᵘᵗ,) .⋅ Ω_l) # Integrate over positive and negatives separately iPos = (integrand+abs.(integrand))./2 iNeg = (integrand-abs.(integrand))./2 # Eq 39 in Shultis and Myneni, double integration here Γ⁻ = -1/2π * (Fᵢ .* w)' * (iNeg * w_azi) Γ⁺ = 1/2π * (Fᵢ .* w)' * (iPos * w_azi) @show # Eq 38 in Shultis and Myneni return R * Γ⁻ + T * Γ⁺ end function compute_reflection(mod::SpecularCanopyScattering,Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}, LD::AbstractLeafDistribution) where FT (;nᵣ,κ) = mod Ωstar, αstar = getSpecularΩ(Ωⁱⁿ, Ωᵒᵘᵗ) # Can change this later as well do have the pdf in μ, not theta! θstar = acos(abs(Ωstar.μ)); # Eq. 2.39 in "Discrete Ordinates Method for Photon Transport in Leaf Canopies", page 59 return FT(1/8) * pdf(LD.LD,2θstar/π) * LD.scaling * K(κ, αstar) * Fᵣ(nᵣ,αstar) end function compute_Z_matrices(mod::SpecularCanopyScattering, μ::Array{FT,1}, LD::AbstractLeafDistribution, m::Int) where FT (;nᵣ, κ, nQuad) = mod # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); # Fourier weights (cosine decomposition) f_weights = cos.(m*ϕ) for i in eachindex(μ) # Incoming beam at ϕ = 0 Ωⁱⁿ = dirVector_μ(μ[i], FT(0)); # Create outgoing vectors in θ and ϕ dirOutꜛ = [dirVector_μ(a,b) for a in μ, b in ϕ]; dirOutꜜ = [dirVector_μ(a,b) for a in -μ, b in ϕ]; # Compute over μ and μ_azi: Zup = compute_reflection.((mod,),(Ωⁱⁿ,),dirOutꜛ, (LD,)); Zdown = compute_reflection.((mod,),(Ωⁱⁿ,),dirOutꜜ, (LD,)); # integrate over the azimuth: 𝐙⁻⁺[i,:] = Zup * (w_azi .* f_weights) 𝐙⁺⁺[i,:] = Zdown * (w_azi .* f_weights) end return 𝐙⁺⁺, 𝐙⁻⁺ end function compute_Z_matrices_aniso(mod::BiLambertianCanopyScattering, μ::AbstractArray{FT,1}, LD::AbstractLeafDistribution, m::Int) where FT (;R,T, nQuad) = mod # Ross kernel G = CanopyOptics.G(Array(μ), LD) @show G # Single Scattering Albedo (should make this a vector too) ϖ = R+T # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # Quadrature points in the azimuth: # Y. Knyazikhin and A. Marshak, eq. A.9a ϕ, w_azi = gauleg(nQuad,FT(0),FT(π)); w_azi *= 2/FT(π) ff = m==0 ? FT(2) : FT(4) #if m>0 # w_azi /= 2 #end # Fourier weights (cosine decomposition) f_weights = cos.(m*ϕ) # Create outgoing vectors in θ and ϕ dirOutꜛ = [dirVector_μ(a,b) for a in -μ, b in ϕ]; dirOutꜜ = [dirVector_μ(a,b) for a in μ, b in ϕ]; for i in eachindex(μ) # Incoming beam at ϕ = 0 Ωⁱⁿ = dirVector_μ(μ[i], FT(0)); # Compute over μ and μ_azi: Zup = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜛ, (LD,)); Zdown = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜜ, (LD,)); #Zup = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜛ); #Zdown = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜜ); # integrate over the azimuth: 𝐙⁻⁺[:,i] = ff * Zup / ϖ * (w_azi .* f_weights) 𝐙⁺⁺[:,i] = ff * Zdown / ϖ * (w_azi .* f_weights) end return 𝐙⁺⁺, 𝐙⁻⁺ end function compute_Γ_isotropic(mod::BiLambertianCanopyScattering, Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}) where FT (;R,T, nQuad) = mod β = acos( Ωᵒᵘᵗ ⋅ Ωⁱⁿ) ω = R + T # Eq 40 in Shultis and Myneni Γ = (ω/3π) * (sin(β) - β * cos(β)) + T/3*cos(β) return Γ end function compute_Z_matrices_aniso(mod::BiLambertianCanopyScattering,μ::AbstractArray{FT,1},LD::AbstractLeafDistribution, Zup, Zdown, m::Int) where FT (;R,T, nQuad) = mod # Ross kernel # Single Scattering Albedo (should make this a vector too) ϖ = R+T # Transmission (same direction) 𝐙⁺⁺ = similar(μ,(length(μ), length(μ))) # Reflection (change direction) 𝐙⁻⁺ = similar(μ,(length(μ), length(μ))) # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(π)); w_azi *= 2/FT(π) w_azi = typeof(μ)(w_azi) ff = m==0 ? FT(2) : FT(4) # Fourier weights (cosine decomposition) f_weights = typeof(μ)(cos.(m*ϕ)) for i in eachindex(μ) # integrate over the azimuth: @views 𝐙⁻⁺[i,:] = ff * Zup[i,:,:] /ϖ * (w_azi .* f_weights) @views 𝐙⁺⁺[i,:] = ff * Zdown[i,:,:] /ϖ * (w_azi .* f_weights) end return 𝐙⁺⁺, 𝐙⁻⁺ end function precompute_Zazi(mod::BiLambertianCanopyScattering, μ::AbstractArray{FT,1}, LD::AbstractLeafDistribution) where FT (;R,T, nQuad) = mod nQuad = nQuad # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(π)); # Fourier weights (cosine decomposition) # Transmission (same direction) Zup = zeros(length(μ),length(μ), nQuad) # Reflection (change direction) Zdown = zeros(length(μ),length(μ), nQuad) # Create outgoing vectors in θ and ϕ dirOutꜛ = [dirVector_μ(a,b) for a in -μ, b in ϕ]; dirOutꜜ = [dirVector_μ(a,b) for a in μ, b in ϕ]; Threads.@threads for i in eachindex(μ) # Incoming beam at ϕ = 0 Ωⁱⁿ = dirVector_μ(μ[i], FT(0)); # Compute over μ and μ_azi: Zup[i,:,:] = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜛ, (LD,)); Zdown[i,:,:] = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜜ, (LD,)); #Zup[:,:,i] = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜛ); #Zdown[:,:,i] = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜜ); end return Zup, Zdown end function precompute_Zazi_(mod::BiLambertianCanopyScattering, μ::AbstractArray{FT,1}, LD::AbstractLeafDistribution) where FT (;R,T, nQuad) = mod # Quadrature points in μ n_μ = length(μ); arr_type = typeof(μ); #μ,w = CanopyOptics.gauleg(n_μ, FT(0), FT(1.0)); dϕ, w_azi = CanopyOptics.gauleg(nQuad, FT(0), FT(π)); dϕᴸ, w_aziᴸ = CanopyOptics.gauleg(nQuad+1, FT(0), FT(2π)); θᴸ,wᴸ = CanopyOptics.gauleg(nQuad, FT(0),FT(π/2)); μᴸ = cos.(θᴸ) Fᵢ = pdf.(LD.LD,2θᴸ/π) * LD.scaling @show sum(wᴸ .* Fᵢ) # Reshape stuff: μⁱⁿ = reshape(arr_type(μ), n_μ, 1, 1, 1, 1 ); μᵒᵘᵗ = reshape(arr_type(deepcopy(μ)), 1, n_μ, 1, 1, 1 ); _dϕ = reshape(arr_type(dϕ), 1, 1, nQuad, 1, 1 ); _μᴸ = reshape(arr_type(μᴸ), 1, 1, 1, nQuad, 1 ); _dϕᴸ = reshape(arr_type(dϕᴸ),1, 1, 1, 1, nQuad+1 ); # Quadrature points wᴸ = wᴸ .* Fᵢ #_w_azi = reshape(arr_type(w_azi), 1, 1, nQuad, 1, 1 ); _wᴸ = reshape(arr_type(wᴸ), 1, 1, 1, nQuad, 1 ); _w_aziᴸ = reshape(arr_type(w_aziᴸ), 1, 1, 1, 1, nQuad+1); integrand = CanopyOptics.leaf_dot_products.(μⁱⁿ, -μᵒᵘᵗ, _dϕ,_μᴸ, _dϕᴸ); iPos = (integrand+abs.(integrand))./2; iNeg = (integrand-abs.(integrand))./2; Γ⁻ = -1/2π * sum(sum(iNeg.*_w_aziᴸ, dims=5).*_wᴸ,dims=4); Γ⁺ = 1/2π * sum(sum(iPos.*_w_aziᴸ, dims=5).*_wᴸ,dims=4); Γ = R .* Γ⁻ .+ T .* Γ⁺; Γup = reshape(Γ, n_μ,n_μ, nQuad); integrand = CanopyOptics.leaf_dot_products.(μⁱⁿ, μᵒᵘᵗ, _dϕ,_μᴸ, _dϕᴸ); iPos = (integrand+abs.(integrand))./2; iNeg = (integrand-abs.(integrand))./2; Γ⁻ = -1/2π * sum(sum(iNeg.*_w_aziᴸ, dims=5).*_wᴸ,dims=4); Γ⁺ = 1/2π * sum(sum(iPos.*_w_aziᴸ, dims=5).*_wᴸ,dims=4); Γ = R .* Γ⁻ .+ T .* Γ⁺; Γdown = reshape(Γ, n_μ,n_μ, nQuad); return Γup,Γdown end "The reduction factor proposed by Nilson and Kuusk, κ ≈ 0.1-0.3, returns exp(-κ * tan(abs(α))" function K(κ::FT, α::FT) where FT exp(-κ * tan(abs(α))); end function leaf_dot_products(μⁱⁿ::FT, μᵒᵘᵗ::FT, dϕᵒᵘᵗ::FT, μᴸ::FT, dϕᴸ::FT) where FT (μⁱⁿ * μᴸ + sqrt(1-μⁱⁿ^2) * sqrt(1-μᴸ^2) * cos(dϕᴸ)) * (μᵒᵘᵗ * μᴸ + sqrt(1-μᵒᵘᵗ^2) * sqrt(1-μᴸ^2) * cos(dϕᴸ - dϕᵒᵘᵗ)) end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
13544
"Integrated projection of leaf area for a single leaf inclination of θₗ, assumes azimuthally uniform distribution" function A(θ::FT, θₗ::FT) where FT<:Real # Suniti: why not use the expressions in Eq 35-36 from Schultis & Myneni (1987)? a = cos(θ) * cos(θₗ) # Eq. 14.24 in Bonan et al. if θₗ ≤ FT(π/2) - θ return a else b = sin(θ) * sin(θₗ) c = sqrt(sin(θₗ)^2 - cos(θ)^2) return FT(2/π)*(c + a * asin(a/b)) end end "Integrated projection of leaf area for a single leaf inclination of θₗ, assumes azimuthally uniform distribution" function Asm(θ::FT, θₗ::FT) where FT<:Real # Suniti: Eq 35-36 from Schultis & Myneni (1987) a = cos(θ) * cos(θₗ) # Eq. 14.24 in Bonan et al. if θₗ ≤ FT(π/2) - θ return a else b = sin(θ) * sin(θₗ) c = sqrt(FT(1)-(a/b)^2) return FT(2/π)*(a * (acos(-a/b)-π/2) + b * c) # (1/π) * (cosθ.cosθₗ.cos⁻¹(cotθ.cotθₗ) + sinθ.sinθₗ.√(1-cot²θ.cot²θₗ)) end end """ $(FUNCTIONNAME)(μ::Array{FT}, LD::AbstractLeafDistribution; nLeg=20) Returns the integrated projection of leaf area in the direction of μ, assumes azimuthally uniform distribution and a LD distribution for leaf polar angle θ. This function is often referred to as the function O(B) (Goudriaan 1977) or G(Ζ) (Ross 1975,1981), see Bonan modeling book, eqs. 14.21-14.26. # Arguments - `μ` an array of cos(θ) (directions [0,1]) - `LD` an [`AbstractLeafDistribution`](@ref) type struct, includes a leaf distribution function - `nLeg` an optional parameter for the number of legendre polynomials to integrate over the leaf distribution (default=20) # Examples ```julia-repl julia> μ,w = CanopyOptics.gauleg(10,0.0,1.0); # Create 10 quadrature points in μ julia> LD = CanopyOptics.spherical_leaves() # Create a default spherical leaf distribution julia> G = CanopyOptics.G(μ, LD) # Compute G(μ) 10-element Vector{Float64}: 0.5002522783000879 0.5002715115149204 0.5003537989277846 0.5004432798701134 0.5005134448870893 0.5003026448466977 0.4999186257540982 0.4994511190721635 0.49907252201082375 0.49936166823681594 ``` """ function G(μ::AbstractArray{FT}, LD::AbstractLeafDistribution; nLeg=20) where FT θₗ,w = gauleg(nLeg,FT(0),FT(π/2)) Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling θ = acos.(μ) G = (w .* Fᵢ)' * A.(θ',θₗ) return G' end "Brute Force G calculation (for testing" function bfG(μ::Array{FT}, LD::AbstractLeafDistribution; nLeg=20) where FT nQuad = 580 ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); # Reference angles to integrate over in both ϕ and μ μ_l, w = gauleg(180,0.0,1.0); Ω_l = [dirVector_μ(a,b) for a in μ_l, b in ϕ]; θₗ = acos.(μ_l) # Have to divide by sin(θ) again to get ∂θ/∂μ for integration (weights won't work) Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling ./ abs.(sin.(θₗ)) #@show Fᵢ' * w #Fᵢ = Fᵢ ./ (Fᵢ' * w) #@show Fᵢ' * w res = similar(μ); for i in eachindex(μ) Ω = dirVector_μ(μ[i],0.0); #res[i] = sum(w .* Fᵢ .* A.(θ[i],θₗ)) # Double integration here: res[i] = ((Fᵢ .* abs.(dot.((Ω,),Ω_l)))' * w)' * w_azi /(2π) end return res end """ $(FUNCTIONNAME)(μ::Array{FT,1},μꜛ::Array{FT,1}, r,t, LD::AbstractLeafDistribution; nLeg = 20) Computes the azimuthally-averaged area scattering transfer function following Shultis and Myneni (https://doi.org/10.1016/0022-4073(88)90079-9), Eq 43: ``Γ(μ' -> μ) = \\int_0^1 dμ_L g_L(μ_L)[t_L Ψ⁺(μ, μ', μ_L) + r_L Ψ⁻(μ, μ', μ_L)]`` assuming an azimuthally uniform leaf angle distribution. # Arguments - `μ::Array{FT,1}` : Quadrature points incoming direction (cos(θ)) - `μꜛ::Array{FT,1}`: Quadrature points outgoing direction (cos(θ)) - `r` : Leaf lambertian reflectance - `t` : Leaf lambertian transmittance - `LD` a [`AbstractLeafDistribution`](@ref) struct that describes the leaf angular distribution function. - `nLeg = 20`: number of quadrature points used for integration over all leaf angles (default is 20). """ function compute_lambertian_Γ(μ::Array{FT,1},μꜛ::Array{FT,1}, r,t, LD::AbstractLeafDistribution; nLeg = 20) where FT Γ = zeros(length(μ), length(μ)) θₗ,w = gauleg(nLeg,FT(0),FT(π/2)) for i in eachindex(θₗ) Ψ⁺, Ψ⁻ = compute_Ψ(μ,μꜛ, cos(θₗ[i])); Γ += pdf.(LD.LD,2θₗ[i]/π) * LD.scaling * w[i] * (t * Ψ⁺ + r * Ψ⁻) end return Γ end """ $(FUNCTIONNAME)(mod::BiLambertianCanopyScattering, μ::Array{FT,1}, LD::AbstractLeafDistribution, m::Int) Computes the single scattering Z matrices (𝐙⁺⁺ for same incoming and outgoing sign of μ, 𝐙⁻⁺ for a change in direction). Internally computes the azimuthally-averaged area scattering transfer function following Shultis and Myneni (https://doi.org/10.1016/0022-4073(88)90079-9), Eq 43:: ``Γ(μ' -> μ) = \\int_0^1 dμ_L g_L(μ_L)[t_L Ψ⁺(μ, μ', μ_L) + r_L Ψ⁻(μ, μ', μ_L)]`` assuming an azimuthally uniform leaf angle distribution. Normalized Γ as 𝐙 = 4Γ/(ϖ⋅G(μ)). Returns 𝐙⁺⁺, 𝐙⁻⁺ # Arguments - `mod` : A bilambertian canopy scattering model [`BiLambertianCanopyScattering`](@ref), uses R,T,nQuad from that model. - `μ::Array{FT,1}`: Quadrature points ∈ [0,1] - `LD` a [`AbstractLeafDistribution`](@ref) struct that describes the leaf angular distribution function. - `m`: Fourier moment (for azimuthally uniform leave distributions such as here, only m=0 returns non-zero matrices) """ function compute_Z_matrices(mod::BiLambertianCanopyScattering, μ::Array{FT,1}, LD::AbstractLeafDistribution, m::Int) where FT (;R,T,nQuad) = mod # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # skip everything beyond m=0 if m>0 return 𝐙⁺⁺, 𝐙⁻⁺ end # Ross kernel G = CanopyOptics.G(μ, LD) # Single Scattering Albedo (should make this a vector too) ϖ = R+T θₗ,w = gauleg(nQuad,FT(0),FT(π/2)); ww = abs.(sin.(θₗ)) for i in eachindex(θₗ) Ψ⁺, Ψ⁻ = compute_Ψ(μ,μ, cos(θₗ[i])); 𝐙⁺⁺ += pdf.(LD.LD,2θₗ[i]/π) * LD.scaling * w[i] * (T * Ψ⁺ + R * Ψ⁻) Ψ⁺, Ψ⁻ = compute_Ψ(μ,-μ, cos(θₗ[i])); 𝐙⁻⁺ += pdf.(LD.LD,2θₗ[i]/π) * LD.scaling * w[i] * (T * Ψ⁺ + R * Ψ⁻) end return 4𝐙⁺⁺ ./(G'*ϖ), 4𝐙⁻⁺ ./(G'*ϖ) end # Page 20, top of Knyazikhin and Marshak # Example # ϕ = range(0.0, 2π, length=200) # θ = range(0.0, π/2, length=150) # dirs = [dirVector(a,b) for a in θ, b in ϕ]; # R = CanopyOptics.compute_specular_reflection.([dirs[10,1]],dirs, [1.5], [0.3], [LD]) function compute_reflection(mod::SpecularCanopyScattering, Ωⁱⁿ::dirVector{FT}, Ωᵒᵘᵗ::dirVector{FT}, LD) where FT (;nᵣ,κ) = mod Ωstar = getSpecularΩ(Ωⁱⁿ, Ωᵒᵘᵗ) #θstar = min(abs(Ωstar.θ), (π-abs(Ωstar.θ))) # min(abs(Ωstar.θ), abs(π+Ωstar.θ)) θstar = Ωstar.θ; #if Ωⁱⁿ.θ ≈ Ωᵒᵘᵗ.θ && Ωⁱⁿ.ϕ ≈ Ωᵒᵘᵗ.ϕ # θstar = Ωⁱⁿ.θ #end # Still needs to be implemented! # incident angle on leaf surface (half of in and out angle): sa = Ωⁱⁿ ⋅ Ωᵒᵘᵗ sa > 1 ? sa = FT(1) : nothing αstar = acos(abs(sa))/2 #@show Ωstar.ϕ, Ωstar.θ #a = (Ωⁱⁿ ⋅ Ωstar) * (Ωᵒᵘᵗ ⋅ Ωstar) return FT(1/8) * pdf(LD.LD,2θstar/π) * LD.scaling * K(κ, αstar) * Fᵣ(nᵣ,αstar) end function compute_Γ(mod::BiLambertianCanopyScattering, Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}, LD::AbstractLeafDistribution) where FT (;R,T, nQuad) = mod #μ_l, w = gauleg(nQuad,0.0,1.0); θₗ, w = gauleg(nQuad,FT(0),FT(π/2)); #μ_l = cos.(θₗ) # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); μ_l = cos.(θₗ ) # Have to divide by sin(θ) again to get ∂θ/∂μ for integration (weights won't work) Fᵢ = pdf.(LD.LD,2θₗ/π) * LD.scaling #.* abs.(sin.(θₗ)) Ω_l = [dirVector_μ(a,b) for a in μ_l, b in ϕ]; # Double integration here over μ and ϕ integrand = ((Ωⁱⁿ,) .⋅ Ω_l) .* ((Ωᵒᵘᵗ,) .⋅ Ω_l) iPos = (integrand+abs.(integrand))./2 iNeg = (integrand-abs.(integrand))./2 # Eq 39 in Shultis and Myneni Γ⁻ = -1/2π * (Fᵢ .* w)' * (iNeg * w_azi) Γ⁺ = 1/2π * (Fᵢ .* w)' * (iPos * w_azi) # Eq 38 in Shultis and Myneni return R * Γ⁻ + T * Γ⁺ end function compute_Γ_isotropic(mod::BiLambertianCanopyScattering, Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}) where FT (;R,T, nQuad) = mod β = acos( Ωᵒᵘᵗ ⋅ Ωⁱⁿ) ω = R + T # Eq 40 in Shultis and Myneni Γ = (ω/3π) * (sin(β) - β * cos(β)) + T/3*cos(β) return Γ end function compute_reflection(mod::SpecularCanopyScattering,Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}, LD::AbstractLeafDistribution) where FT (;nᵣ,κ) = mod Ωstar, αstar = getSpecularΩ(Ωⁱⁿ, Ωᵒᵘᵗ) # Can change this later as well do have the pdf in μ, not theta! θstar = acos(abs(Ωstar.μ)); # Eq. 2.39 in "Discrete Ordinates Method for Photon Transport in Leaf Canopies", page 59 return FT(1/8) * pdf(LD.LD,2θstar/π) * LD.scaling * K(κ, αstar) * Fᵣ(nᵣ,αstar) end function compute_Z_matrices(mod::SpecularCanopyScattering, μ::Array{FT,1}, LD::AbstractLeafDistribution, m::Int) where FT (;nᵣ, κ, nQuad) = mod # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); # Fourier weights (cosine decomposition) f_weights = cos.(m*ϕ) for i in eachindex(μ) # Incoming beam at ϕ = 0 Ωⁱⁿ = dirVector_μ(μ[i], FT(0)); # Create outgoing vectors in θ and ϕ dirOutꜛ = [dirVector_μ(a,b) for a in μ, b in ϕ]; dirOutꜜ = [dirVector_μ(a,b) for a in -μ, b in ϕ]; # Compute over μ and μ_azi: Zup = compute_reflection.((mod,),(Ωⁱⁿ,),dirOutꜛ, (LD,)); Zdown = compute_reflection.((mod,),(Ωⁱⁿ,),dirOutꜜ, (LD,)); # integrate over the azimuth: 𝐙⁻⁺[:,i] = Zup * (w_azi .* f_weights) 𝐙⁺⁺[:,i] = Zdown * (w_azi .* f_weights) end return 𝐙⁺⁺, 𝐙⁻⁺ end function compute_Z_matrices_aniso(mod::BiLambertianCanopyScattering, μ::AbstractArray{FT,1}, LD::AbstractLeafDistribution, m::Int) where FT (;R,T, nQuad) = mod # Ross kernel G = CanopyOptics.G(Array(μ), LD) # Single Scattering Albedo (should make this a vector too) ϖ = R+T # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); w_azi /= FT(2π) # Fourier weights (cosine decomposition) f_weights = cos.(m*ϕ) # Create outgoing vectors in θ and ϕ dirOutꜛ = [dirVector_μ(a,b) for a in μ, b in ϕ]; dirOutꜜ = [dirVector_μ(a,b) for a in -μ, b in ϕ]; for i in eachindex(μ) # Incoming beam at ϕ = 0 Ωⁱⁿ = dirVector_μ(μ[i], FT(0)); # Compute over μ and μ_azi: Zup = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜛ, (LD,)); Zdown = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜜ, (LD,)); #Zup = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜛ); #Zdown = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜜ); # integrate over the azimuth: 𝐙⁻⁺[:,i] = 4Zdown./(G'*ϖ) * (w_azi .* f_weights) 𝐙⁺⁺[:,i] = 4Zup ./(G'*ϖ) * (w_azi .* f_weights) end return 𝐙⁺⁺, 𝐙⁻⁺ end function compute_Z_matrices_aniso(mod::BiLambertianCanopyScattering,μ::AbstractArray{FT,1},LD::AbstractLeafDistribution, Zup, Zdown, m::Int) where FT (;R,T, nQuad) = mod # Ross kernel G = CanopyOptics.G(Array(μ), LD) # Single Scattering Albedo (should make this a vector too) ϖ = R+T nQuad = size(Zup,2) # Transmission (same direction) 𝐙⁺⁺ = zeros(length(μ), length(μ)) # Reflection (change direction) 𝐙⁻⁺ = zeros(length(μ), length(μ)) # Quadrature points in the azimuth (has to be consistent with pre-computation): ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); w_azi /= FT(2π) # Fourier weights (cosine decomposition) f_weights = cos.(m*ϕ) for i in eachindex(μ) # integrate over the azimuth: @views 𝐙⁻⁺[:,i] = 4Zdown[:,:,i]./(G*ϖ) * (w_azi .* f_weights) @views 𝐙⁺⁺[:,i] = 4Zup[:,:,i]./(G*ϖ) * (w_azi .* f_weights) end return 𝐙⁺⁺, 𝐙⁻⁺ end function precompute_Zazi(mod::BiLambertianCanopyScattering, μ::AbstractArray{FT,1}, LD::AbstractLeafDistribution) where FT (;R,T, nQuad) = mod nQuad = 40 # Quadrature points in the azimuth: ϕ, w_azi = gauleg(nQuad,FT(0),FT(2π)); # Fourier weights (cosine decomposition) # Transmission (same direction) Zup = zeros(length(μ), nQuad,length(μ)) # Reflection (change direction) Zdown = zeros(length(μ), nQuad,length(μ)) # Create outgoing vectors in θ and ϕ dirOutꜛ = [dirVector_μ(a,b) for a in μ, b in ϕ]; dirOutꜜ = [dirVector_μ(a,b) for a in -μ, b in ϕ]; #Threads.@threads for i in eachindex(μ) # Incoming beam at ϕ = 0 Ωⁱⁿ = dirVector_μ(μ[i], FT(0)); # Compute over μ and μ_azi: #Zup[:,:,i] = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜛ); #Zdown[:,:,i] = compute_Γ_isotropic.((mod,),(Ωⁱⁿ,),dirOutꜜ); Zup[:,:,i] = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜛ, (LD,)); Zdown[:,:,i] = compute_Γ.((mod,),(Ωⁱⁿ,),dirOutꜜ, (LD,)); end return Zup, Zdown end "The reduction factor proposed by Nilson and Kuusk, κ ≈ 0.1-0.3, returns exp(-κ * tan(abs(α))" function K(κ::FT, α::FT) where FT exp(-κ * tan(abs(α))); end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
5538
""" $(FUNCTIONNAME)(leaf::LeafProspectProProperties{FT}, optis) where {FT<:AbstractFloat} Computes leaf optical properties (reflectance and transittance) based on PROSPECT-PRO # Arguments - `leaf` [`LeafProspectProProperties`](@ref) type struct which provides leaf composition - `optis` [`LeafOpticalProperties`](@ref) type struct, which provides absorption cross sections and spectral grid # Examples ```julia-repl julia> opti = createLeafOpticalStruct((400.0:5:2400)*u"nm"); julia> leaf = LeafProspectProProperties{Float64}(Ccab=30.0); julia> T,R = prospect(leaf,opti); ``` """ function prospect( leaf::LeafProspectProProperties{FT}, optis ) where {FT} # *********************************************************************** # Jacquemoud S., Baret F. (1990), PROSPECT: a model of leaf optical # properties spectra; Remote Sens. Environ.; 34:75-91. # Reference: # Féret, Gitelson, Noble & Jacquemoud [2017]. PROSPECT-D: Towards modeling # leaf optical properties through a complete lifecycle # Remote Sensing of Environment; 193:204–215 # DOI: http://doi.org/10.1016/j.rse.2017.03.004 # The specific absorption coefficient corresponding to brown pigment is() # provided by Frederic Baret [EMMAH, INRA Avignon, [email protected]] # & used with his autorization. # *********************************************************************** (;N, Ccab, Ccar, Cbrown, Canth, Cw, Cm, Cprot, Ccbc) = leaf; (;Kcab, Kant, Kb, Kcar, Km, Kw, nᵣ, Kp, Kcbc) = optis; # This can go into a separate multiple dispatch function as the rest remains constant across versions! Kall=(Ccab*Kcab + Ccar*Kcar + Canth*Kant + Cbrown*Kb + Cw*Kw + Cm*Km + Cprot*Kp +Ccbc * Kcbc) / N; # Adding eps() here to keep it stable and NOT set to 1 manually when Kall=0 (ForwardDiff won't work otherwise) tau = (FT(1) .-Kall).*exp.(-Kall) .+ Kall.^2 .*real.(expint.(Kall.+eps(FT))) # *********************************************************************** # reflectance & transmittance of one layer # *********************************************************************** # Allen W.A., Gausman H.W., Richardson A.J., Thomas J.R. (1969) # Interaction of isotropic ligth with a compact plant leaf; J. Opt. # Soc. Am., 59[10]:1376-1379. # *********************************************************************** # reflectivity & transmissivity at the interface #------------------------------------------------- # From Prospect-D, uses 40 here instead of 59 from CVT) #talf = calctav.(59.,nr) talf = calctav.(FT(40),nᵣ) ralf = FT(1) .-talf t12 = calctav.(FT(90), nᵣ) r12 = FT(1) .-t12 t21 = t12./(nᵣ.^2) r21 = FT(1) .-t21 # top surface side denom = FT(1) .-r21.*r21.*tau.^2 Ta = talf.*tau.*t21./denom Ra = ralf.+r21.*tau.*Ta # bottom surface side t = t12.*tau.*t21./denom r = r12+r21.*tau.*t # *********************************************************************** # reflectance & transmittance of N layers # Stokes equations to compute properties of next N-1 layers [N real] # Normal case() # *********************************************************************** # Stokes G.G. (1862), On the intensity of the light reflected from # | transmitted through a pile of plates; Proc. Roy. Soc. Lond. # 11:545-556. # *********************************************************************** D = sqrt.(((FT(1) .+r.+t).*(FT(1) .+r.-t).*(FT(1) .-r.+t).*(FT(1) .-r.-t)).+5eps(FT)) #println(typeof(D), typeof(r), typeof(t)) rq = r.^2 tq = t.^2 a = (FT(1) .+rq.-tq.+D)./(2r) b = (FT(1) .-rq.+tq.+D)./(2t) bNm1 = b.^(N-1); # bN2 = bNm1.^2 a2 = a.^2 denom = a2.*bN2.-1 Rsub = a.*(bN2.-1)./denom Tsub = bNm1.*(a2.-1)./denom # Case of zero absorption j = findall(r.+t .>= 1) Tsub[j] = t[j]./(t[j]+(1 .-t[j])*(leaf.N-1)) Rsub[j] = 1 .-Tsub[j] # Reflectance & transmittance of the leaf: combine top layer with next N-1 layers denom = FT(1) .-Rsub.*r # lambertian Tranmsission T = Ta.*Tsub./denom # lambertian Reflectance R = Ra.+Ta.*Rsub.*t./denom return T,R end """ calctav(α::FT, nr::FT) where {FT<:AbstractFloat} Computes transmission of isotropic radiation across a dielectric surface (Stern F., 1964; Allen W.A.,Appl. Opt., 3(1):111-113 1973)). From calctav.m in PROSPECT-D # Arguments - `α` angle of incidence [degrees] - `nr` Index of refraction """ function calctav(α::FT, nr::FT2) where {FT,FT2} a = ((nr+1) ^ 2) / 2; a3 = a ^ 3; n2 = nr ^ 2; n4 = nr ^ 4; n6 = nr ^ 6; np = n2 + 1; np2 = np ^ 2; np3 = np ^ 3; nm2 = (n2 - 1) ^2; k = ((n2-1) ^ 2) / -4; k2 = k ^ 2; sa2 = sind(α) ^ 2; _b1 = (α==90 ? 0 : sqrt( (sa2 - np/2)^2 + k )); _b2 = sa2 - np/2; b = _b1 - _b2; b3 = b ^ 3; ts = ( k2 / (6*b3) + k/b - b/2 ) - ( k2 / (6*a3) + k/a - a/2 ); tp1 = -2 * n2 * (b-a) / (np2); tp2 = -2 * n2 * np * log(b/a) / (nm2); tp3 = n2 * (1/b - 1/a) / 2; tp4 = 16 * n4 * (n4+1) * log((2*np*b - nm2) / (2*np*a - nm2)) / (np3*nm2); tp5 = 16 * n6 * (1 / (2*np*b-nm2) - 1 / (2*np*a-nm2)) / (np3); tp = tp1 + tp2 + tp3 + tp4 + tp5; tav = (ts + tp) / (2 * sa2); return tav end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
8910
# calculate scattering coefficient for forest based on distorted born approximation using YAML using SpecialFunctions using QuadGK using Parameters using Test using BenchmarkTools # using LinearAlgebra Import later if needed include("types.jl") include("parameters_from_yaml.jl") include("probabilities.jl") include("subroutines.jl") include("output_check.jl") ## ## Load input parameters ## const INPUT_FILE = "deccheckin.yaml" const input_params = parameters_from_yaml(INPUT_FILE) (;bfrghz, leaf, branch_1, branch_2, trunk, d_c, d_t, ϵ_g, l, sig) = input_params # Conversion to standard metric const c = 3e8 # Speed of light m/s const bfr = bfrghz*1e9 # GHz to Hz const lm = l*1e-2 # cm to m const s = sig*1e-2 # cm to m (surface rms height) const k₀ = 2π*bfr/c # Free space wave number (2π/λ) const n_ϕ = 41 # No. of ϕ const n_θ = 37 # No. of θ const ej = 0.0 + 1.0im # Complex unit vector # Loop over angle of incidence θ_i (not currently looped) const ip = 1 const θ_iᵈ = 40 const θ_iʳ = deg2rad(θ_iᵈ) const ϕ_iᵈ = 0 const ϕ_iʳ = deg2rad(ϕ_iᵈ) const δθ = π/n_θ const δϕ = 2π/n_ϕ const Δϕ = 1/n_ϕ const Δθ = 1/n_θ # Roughness factor for ground scattering in direct-reflected term # r_g defined right above 3.1.9 const r_g = exp(-4*(k₀*s*cos(θ_iʳ))^2) # dim1 = polarization [h, v] # dim2 = layer [crown, trunk] at = zeros(2, 2, 20) # Compute scattering amplitudes from leaves (forward and backward) afhhl, afvvl = afsal(θ_iʳ, leaf, k₀) σ_l = asal(θ_iʳ, leaf, k₀) # Forward scattering of all wood types # Each output is a 2x2 matrix (hh hv ; vh vv) afb1, afb2, aft = wood_forward.([branch_1, branch_2, trunk]) # Backward scattering of all wood types # Each output is a WoodBackscatter type, with 3 fields: d, dr, vh # Each of these fields is an array # (d: [hh, vh, vv], dr: [hh, vv], vh: [vh1, vh3]) σ_b1, σ_b2, σ_t = wood_backward.([branch_1, branch_2, trunk]) ############################ # CALCULATION OF PROPAGATION CONSTANT IN TOP AND BOTTOM LAYERS # 3.1.8??? K_hc = k₀*cos(θ_iʳ)+(2π*(leaf.ρ*afhhl + branch_1.ρ*abs_components(afb1[1,1]) + branch_2.ρ*abs_components(afb2[1,1])))/(k₀*cos(θ_iʳ)) K_vc = k₀*cos(θ_iʳ)+(2π*(leaf.ρ*afvvl + branch_1.ρ*abs_components(afb1[2,2]) + branch_2.ρ*abs_components(afb2[2,2])))/(k₀*cos(θ_iʳ)) K_ht = k₀*cos(θ_iʳ)+(2π*trunk.ρ*aft[1,1])/(k₀*cos(θ_iʳ)) K_vt = k₀*cos(θ_iʳ)+(2π*trunk.ρ*aft[2,2])/(k₀*cos(θ_iʳ)) ath1, atv1, ath2, atv2 = abs.(imag.([K_hc, K_vc, K_ht, K_vt])) K_hc, K_vc, K_ht, K_vt = abs_imag_only.([K_hc, K_vc, K_ht, K_vt]) K_hcⁱ, K_vcⁱ, K_htⁱ, K_vtⁱ = imag.((K_hc, K_vc, K_ht, K_vt)) atv1 = (atv1 <= 1.0E-20 ? 0.0001 : atv1) skdh1= 1/ath1 skdv1= 1/atv1 at[:,:,ip] = [atv1 abs(imag(K_vc+K_vt)) ; ath1 abs(imag(K_hc+K_ht))] ############################ # Calculation of reflection coefficient from ground rgh = (cos(θ_iʳ)-sqrt(ϵ_g-sin(θ_iʳ)^2))/(cos(θ_iʳ)+sqrt(ϵ_g-sin(θ_iʳ)^2)) rgv = (ϵ_g*cos(θ_iʳ)-sqrt(ϵ_g-sin(θ_iʳ)^2))/(ϵ_g*cos(θ_iʳ)+sqrt(ϵ_g-sin(θ_iʳ)^2)) reflhh = rgh*exp(ej*(K_hc+K_hc)*d_c+ej*(K_ht+K_ht)*d_t) reflhc = conj(reflhh) reflvv = rgv*exp(ej*(K_vc+K_vc)*d_c+ej*(K_vt+K_vt)*d_t) reflha = abs(reflhh) reflva = abs(reflvv) dattenh1 = exp(-2*(K_hcⁱ+K_hcⁱ)*d_c) dattenh2 = exp(-2*(K_htⁱ+K_htⁱ)*d_t) dattenv1 = exp(-2*(K_vcⁱ+K_vcⁱ)*d_c) dattenv2 = exp(-2*(K_vtⁱ+K_vtⁱ)*d_t) dattenvh1 = exp(-2*(K_vcⁱ+K_hcⁱ)*d_c) dattenvh2 = exp(-2*(K_vtⁱ+K_htⁱ)*d_t) a1 = (ej)*(K_vc-K_hc) e1 = (ej)*(conj(K_vc)-conj(K_hc)) a2 = (ej)*(K_vt-K_ht) e2 = (ej)*(conj(K_vt)-conj(K_ht)) ############################ # Row is polarization [hh, vh, vv] # Column is layer [branch+leaf (d1), trunk (d2), leaf (d3)] σ_d = zeros(3,3) # Perform 3.1.2 over all polarizations, using computed subexpressions (term_c, term_t) term_c = map((x,y) -> funcm(2*x, 2*y, d_c), [K_hcⁱ, K_vcⁱ, K_vcⁱ], [K_hcⁱ, K_hcⁱ, K_vcⁱ]) term_t = map((x,y) -> funcm(2*x, 2*y, d_t), [K_htⁱ, K_vtⁱ, K_vtⁱ], [K_htⁱ, K_htⁱ, K_vtⁱ]) σ_d[:,1] = (branch_1.ρ*σ_b1.d + branch_2.ρ*σ_b2.d + leaf.ρ*σ_l.d) .* term_c σ_d[:,2] = trunk.ρ*σ_t.d .* term_t .* [dattenh1, dattenvh1, dattenv1] σ_d[:,3] = leaf.ρ*σ_l.d .* term_c ############################ # Row is polarization [hh, vv] # Column is layer [branch+leaf (d1), trunk (d2), leaf (d3)] σ_dr = zeros(2,3) σ_dr[:,1] = 4*d_c*(branch_1.ρ*σ_b1.dr + branch_2.ρ*σ_b2.dr + leaf.ρ*σ_l.dr)*r_g σ_dr[:,2] = 4*d_t*trunk.ρ*σ_t.dr*r_g σ_dr[:,3] = 4*d_c*leaf.ρ*σ_l.dr*r_g σ_dr[1,:] *= reflha^2 σ_dr[2,:] *= reflva^2 ############################ # Row is # Columns is σ_vh = zeros(3,3) sg_d = σ_d[:,1]+σ_d[:,2] sg_r = zeros(2) sg_dr = σ_dr[:,1]+σ_dr[:,2] sg_dri = (σ_dr[:,1]+σ_dr[:,2])/2 sghh = sg_d[1]+sg_r[1]+sg_dr[1] sghhi = sg_d[1]+sg_r[1]+sg_dri[1] sgvv = sg_d[3]+sg_r[2]+sg_dr[2] sgvvi = sg_d[3]+sg_r[2]+sg_dri[2] ############################ # Backscat. cross section, vh pol. factvh1 = exp(-2*(K_hcⁱ-K_vcⁱ)*d_c) factvh2 = exp(-2*(K_vcⁱ-K_hcⁱ)*d_c) factvh3 = exp((-a1-e1)*d_c) # vh1 σ_vh[1,1] = (branch_1.ρ*σ_b1.vh[1]+branch_2.ρ*σ_b2.vh[1]+leaf.ρ*σ_l.vh[1])*(reflha)^2*funcm(2*K_vcⁱ,-2*K_hcⁱ,d_c)*r_g σ_vh[2,1] = (branch_1.ρ*σ_b1.vh[1]+branch_2.ρ*σ_b2.vh[1]+leaf.ρ*σ_l.vh[1])*(reflva)^2*funcp(2*K_vcⁱ,-2*K_hcⁱ,d_c)*r_g σ_vh[3,1] = abs(2*real((branch_1.ρ*σ_b1.vh[2] + branch_2.ρ*σ_b2.vh[2] +leaf.ρ*σ_l.vh[2])*reflvv*reflhc*cfun(a1,e1,d_c)*r_g)) # vh2 σ_vh[1,3] = (leaf.ρ*σ_l.vh[1])*(reflha)^2*funcm(2*K_vcⁱ,-2*K_hcⁱ,d_c)*r_g σ_vh[2,3] = (leaf.ρ*σ_l.vh[1])*(reflva)^2*funcp(2*K_vcⁱ,-2*K_hcⁱ,d_c)*r_g σ_vh[3,3] = abs(2*real((leaf.ρ*σ_l.vh[2])*reflvv*reflhc*cfun(a1,e1,d_c)*r_g)) # vh3 σ_vh[1,2] = factvh1*(trunk.ρ*σ_t.vh[1])*(reflha)^2*funcm(2*K_vtⁱ,-2*K_htⁱ,d_t)*r_g σ_vh[2,2] = factvh2*(trunk.ρ*σ_t.vh[1])*(reflva)^2*funcp(2*K_vtⁱ,-2*K_htⁱ,d_t)*r_g σ_vh[3,2] = abs(2*real(factvh3*(trunk.ρ*σ_t.vh[2])*reflvv*reflhc*cfun(a2,e2,d_t)*r_g)) sgvhdr1=σ_vh[1,1]+σ_vh[2,1]+σ_vh[3,1] sgvh1 = σ_d[2,1]+σ_vh[1,1]+σ_vh[2,1]+σ_vh[3,1] sgvhi1 = σ_d[2,1]+σ_vh[1,1]+σ_vh[2,1] sgvhidr1=σ_vh[1,1]+σ_vh[2,1] sgvhdr3=σ_vh[1,3]+σ_vh[2,3]+σ_vh[3,3] sgvh3 = σ_d[2,3]+σ_vh[1,3]+σ_vh[2,3]+σ_vh[3,3] sgvhi3=σ_d[2,3]+σ_vh[1,3]+σ_vh[2,3] sgvhidr3=σ_vh[1,3]+σ_vh[2,3] sgvhdr2=σ_vh[1,2]+σ_vh[2,2]+σ_vh[3,2] sgvh2 = σ_d[2,2]+σ_vh[1,2]+σ_vh[2,2]+σ_vh[3,2] sgvhi2=σ_d[2,2]+σ_vh[1,2]+σ_vh[2,2] sgvhidr2=σ_vh[1,2]+σ_vh[2,2] sgvh = sgvh1+sgvh2 sgvhi = sgvhi1+sgvhi2 sgvhidr=sgvhidr1+sgvhidr2 ### σ = [sghh sgvh sgvv] σ_i = [sghhi sgvhi sgvvi] σ_o = 10.0*log10.(abs.(σ)) σ_i_o = 10.0*log10.(abs.(σ_i)) ############################ # Calculation of backscat cross sections in db svhi = zeros(20) svhi1 = zeros(20) svhi2 = zeros(20) svhi3 = zeros(20) sgvhr = 0 σ_d_db = 10 * log10.(σ_d) σ_dr_db = 10 * log10.(σ_dr) svhi[ip] = 10.0*log10(sgvhidr) svhi1[ip] = 10.0*log10(sgvhidr1) svhi2[ip] = 10.0*log10(sgvhidr2) svhi3[ip] = 10.0*log10(sgvhidr3) s_dd = 10.0*log10.(sg_d) shhdrd = 10.0*log10(sg_dr[1]) shhdri = 10.0*log10(sg_dri[1]) shhrd = 10.0*log10(sg_r[1]) svhdd = 10.0*log10(abs(sg_d[2])) sgvhdr = sgvhdr1+sgvhdr2+sgvhdr3 svhdrd = 10.0*log10(abs(sgvhdr)) svhdrd1 = 10.0*log10(abs(sgvhdr1)) svhdrd2 = 10.0*log10(abs(sgvhdr2)) svhdrd3 = 10.0*log10(abs(sgvhdr3)) sgvho = 10.0*log10(sg_d[2]+sgvhdr+sgvhr) svhrd = 10.0*log10(abs(sgvhr)) svvdrd = 10.0*log10(sg_dr[2]) svvdri = 10.0*log10(sg_dri[2]) svvrd = 10.0*log10(sg_r[2]) ################################ # Add the effect of rough ground ksig=k₀*s σ_g, gd = grdoh(ksig) σ_t = σ + σ_g σ_t_i = σ_i + σ_g ############################### output = Forest_Scattering_Output(θ_iᵈ, σ_d_db[1,1], σ_d_db[1,2], σ_d_db[1,3], σ_dr_db[1,1], σ_dr_db[1,2], σ_dr_db[1,3], 10.0*log10(σ_t[1]), s_dd[1], shhdrd, σ_d_db[3,1], σ_d_db[3,2], σ_d_db[3,3], σ_dr_db[2,1], σ_dr_db[2,2], σ_dr_db[2,3], 10.0*log10(σ_t[3]), s_dd[3], svvdrd, σ_d_db[2,1], σ_d_db[2,2], σ_d_db[2,3], svhdrd1, svhdrd2, svhdrd3, 10.0*log10(σ_t[2]), svhdd, svhdrd, 10.0*log10(σ_g[1]), 10.0*log10(σ_g[2]), 10.0*log10(σ_g[3]), σ_i_o[1], σ_i_o[2], σ_i_o[3], 10.0*log10(sgvhidr1), 10.0*log10(sgvhidr2), 10.0*log10(sgvhidr3), σ_t[1]/σ_t_i[1], σ_t[2]/σ_t_i[2], σ_t[3]/σ_t_i[3], ath1, atv1, imag(K_hc+K_ht), imag(K_vc+K_vt)) check_output_matches_fortran(output)
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
2205
function check_output_matches_fortran(x::Forest_Scattering_Output) @test x.theti == 40 # hh @test round(x.sighhd1, digits=2) == -16.24 @test round(x.sighhd2, digits=2) == -51.46 @test round(x.sighhd3, digits=2) == -37.27 @test round(x.sighhdr1, digits=3) == -8.708 @test round(x.sighhdr2, digits=3) == 8.987 @test round(x.sighhdr3, digits=2) == -34.94 @test round(x.sighht, digits=3) == 9.073 @test round(x.sighhd, digits=2) == -16.24 @test round(x.sighhdr, digits=3) == 9.060 # vv @test round(x.sigvvd1, digits=2) == -10.08 @test round(x.sigvvd2, digits=2) == -54.54 @test round(x.sigvvd3, digits=2) == -40.02 @test round(x.sigvvdr1, digits=3) == -6.647 @test round(x.sigvvdr2, digits=3) == 6.000 @test round(x.sigvvdr3, digits=2) == -45.73 @test round(x.sigvvt, digits=3) == 6.332 @test round(x.sigvvd, digits=2) == -10.08 @test round(x.sigvvdr, digits=3) == 6.230 # vh @test round(x.sigvhd1, digits=2) == -17.32 # @test round(x.sigvhd2, digits=4) ≈ 0.0 @test round(x.sigvhd3, digits=2) == -52.41 @test round(x.sigvhdr1, digits=2) == -12.37 # @test round(x.sigvhdr2, digits=4) ≈ 0.0 @test round(x.sigvhdr3, digits=2) == -52.01 @test round(x.sigvht, digits=2) == -11.16 @test round(x.sigvhd, digits=2) == -17.32 @test round(x.sigvhdr, digits=2) == -12.37 # total coherent @test round(x.ghhd, digits=2) == -30.77 @test round(x.gvhd, digits=2) == -45.78 @test round(x.gvvd, digits=2) == -27.99 # total incoherent @test round(x.sighhi, digits=3) == 6.075 @test round(x.sigvhi, digits=2) == -12.43 @test round(x.sigvvi, digits=3) == 3.418 @test round(x.sigvhi1, digits=2) == -14.13 # @test round(x.sigvhi2, digits=2) ≈ 0 @test round(x.sigvhi3, digits=2) == -53.43 @test round(x.cofhh, digits=3) == 1.994 @test round(x.cofvh, digits=3) == 1.338 @test round(x.cofvv, digits=3) == 1.955 @test round(x.athc, digits=6) == 0.008110 @test round(x.atvc, digits=5) == 0.01734 @test round(x.atht, digits=6) == 0.008231 @test round(x.atvt, digits=5) == 0.01987 println("All checks match ✅") end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
5459
function parameters_from_yaml(filepath) input_params = YAML.load_file(filepath) # Frequency bfrghz = input_params["frequency"] # Leaf Parameters and Conversions to Metric a_maj_cm = input_params["leaf_parameters"]["major_axis"] b_min_cm = input_params["leaf_parameters"]["minor_axis"] tmm = input_params["leaf_parameters"]["thickness"] ρ_l = input_params["leaf_parameters"]["density"] ϵ_l = eval(Meta.parse(input_params["leaf_parameters"]["dielectric_constant"])) pdf_num_l = input_params["leaf_parameters"]["leaf_inclination_pdf_type"] pdf_param_l = input_params["leaf_parameters"]["pdf_parameter"] a_maj = a_maj_cm * 1e-2 # cm to m b_min = b_min_cm * 1e-2 # cm to m t = tmm * 1e-3 # mm to m leaf = Leaf(ϵ_l, a_maj, b_min, t, ρ_l, pdf_num_l, pdf_param_l) # Primary Branch Parameters r_b1_cm = input_params["primary_branch_parameters"]["diameter"] l_b1 = input_params["primary_branch_parameters"]["length"] ρ_b1 = input_params["primary_branch_parameters"]["density"] ϵ_b1 = eval(Meta.parse(input_params["primary_branch_parameters"]["dielectric_constant"])) pdf_num_b1 = input_params["primary_branch_parameters"]["branch_inclination_pdf_type"] pdf_param_b1 = input_params["primary_branch_parameters"]["pdf_parameter"] r_b1 = 0.5*r_b1_cm*1e-2 # diameter to radius, cm to m branch_1 = Wood(ϵ_b1, r_b1, l_b1, ρ_b1, pdf_num_b1, pdf_param_b1) # Secondary Branch Parameters r_b2_cm = input_params["secondary_branch_parameters"]["diameter"] l_b2 = input_params["secondary_branch_parameters"]["length"] ρ_b2 = input_params["secondary_branch_parameters"]["density"] ϵ_b2 = eval(Meta.parse(input_params["secondary_branch_parameters"]["dielectric_constant"])) pdf_num_b2 = input_params["secondary_branch_parameters"]["branch_inclination_pdf_type"] pdf_param_b2 = input_params["secondary_branch_parameters"]["pdf_parameter"] r_b2 = 0.5*r_b2_cm*1e-2 # diameter to radius, cm to m branch_2 = Wood(ϵ_b2, r_b2, l_b2, ρ_b2, pdf_num_b2, pdf_param_b2) # Trunk Parameters r_t_cm = input_params["trunk_parameters"]["diameter"] l_t = input_params["trunk_parameters"]["length"] ρ_t = input_params["trunk_parameters"]["density"] ϵ_t = eval(Meta.parse(input_params["trunk_parameters"]["dielectric_constant"])) pdf_num_t = input_params["trunk_parameters"]["branch_inclination_pdf_type"] pdf_param_t = input_params["trunk_parameters"]["pdf_parameter"] r_t = 0.5*r_t_cm*1e-2 # diameter to radius, cm to m trunk = Wood(ϵ_t, r_t, l_t, ρ_t, pdf_num_t, pdf_param_t) d_c = input_params["trunk_parameters"]["crown_height"] d_t = input_params["trunk_parameters"]["trunk_height"] ϵ_g = eval(Meta.parse(input_params["trunk_parameters"]["soil_dielectric"] )) l = input_params["trunk_parameters"]["corr_length"] sig = input_params["trunk_parameters"]["rms_height"] return Forest_Scattering_Parameters(bfrghz, leaf, branch_1, branch_2, trunk, d_c, d_t, ϵ_g, l, sig) end function Base.show(io::IO, x::Forest_Scattering_Parameters) println(io, "Frequency: $(x.bfrghz)") println(io, "------------------------------") println(io, "Leaf Parameters") println(io, "------------------------------") println(io, "a_maj: $(x.leaf.a_maj * 1e2) cm") println(io, "b_min: $(x.leaf.b_min * 1e2) cm") println(io, "t: $(x.leaf.t * 1e3) mm") println(io, "ρ: $(x.leaf.ρ) m3") println(io, "ϵ: $(x.leaf.ϵ)") println(io, "pdf_num: $(x.leaf.pdf_num)") println(io, "pdf_param: $(x.leaf.pdf_param)") println(io, "------------------------------") println(io, "Primary Branch Parameters") println(io, "------------------------------") println(io, "r: $(x.branch_1.r * 1e2) cm") println(io, "l: $(x.branch_1.l) m") println(io, "ρ: $(x.branch_1.ρ) m3") println(io, "ϵ: $(x.branch_1.ϵ)") println(io, "pdf_num: $(x.branch_1.pdf_num)") println(io, "pdf_param: $(x.branch_1.pdf_param)") println(io, "------------------------------") println(io, "Secondary Branch Parameters") println(io, "------------------------------") println(io, "r_b2: $(x.branch_2.r * 1e2) cm") println(io, "l_b2: $(x.branch_2.l) m") println(io, "ρ_b2: $(x.branch_2.ρ) m3") println(io, "ϵ_b2: $(x.branch_2.ϵ)") println(io, "pdf_num: $(x.branch_2.pdf_num)") println(io, "pdf_param: $(x.branch_2.pdf_param)") println(io, "------------------------------") println(io, "Trunk Parameters") println(io, "------------------------------") println(io, "r_t: $(x.trunk.r * 1e2) cm") println(io, "l_t: $(x.trunk.l) m") println(io, "ρ_t: $(x.trunk.ρ) m3") println(io, "ϵ_t: $(x.trunk.ϵ)") println(io, "pdf_num: $(x.trunk.pdf_num)") println(io, "pdf_param: $(x.trunk.pdf_param)") println(io, "------------------------------") println(io, "Other") println(io, "------------------------------") println(io, "d_c: $(x.d_c)") println(io, "d_t: $(x.d_t)") println(io, "ϵ_g: $(x.ϵ_g)") println(io, "l: $(x.l)") println(io, "sig: $(x.sig)") end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
2407
# θ: input value # ntype: distribution type # param: distribution parameter function prob(θ, ntype::Integer, param=0.0, nth=37) @assert 0 <= θ <= π "θ must be between 0 and π" θ_d = θ*180.0/pi if ntype == 1 return (0 < θ < π/2 ? 0.5*sin(θ) : 0.0) elseif ntype == 2 return (0 < θ < π/2 ? 8/(3π) * sin(θ)^4 : 0.0) # Unfinished (3) elseif ntype == 3 th0r = param*pi/180. dth = π/nth return (θ <= th0r < θ + dth ? 1.0/dth : 0.0) elseif ntype == 4 dthplr = param * π/180 return (0 < θ < dthplr ? 1.0/dthplr : 0.0) elseif ntype == 5 dthpdr = param * π/180 return ((π/2 - dthpdr) < θ < (π/2 + dthpdr) ? 1.0/(2.0*dthpdr) : 0.0) elseif ntype == 6 return (θ < π/2 ? (16.0/3.0*π)*(sin(2.0*θ))^4 : 0.0) elseif ntype == 7 return (π/4 < θ < π/2 ? abs(2 * sin(4.0 * θ)) : 0.0) elseif ntype == 8 return (16.0/(5.0*pi))*(cos(θ))^6 elseif ntype == 9 return param * exp(-param * θ) elseif ntype == 10 thd = θ*180.0/pi if (0 <=thd <= 10.0) return 0.015 elseif (10.0 < thd <= 20.0) return 0.020 elseif (20.0 < thd <= 30.0) return 0.015 elseif (30.0 < thd <= 40.0) return 0.03 elseif (40.0 < thd <= 50.0) return 0.14 elseif (50.0 < thd <= 60.0) return 0.25 elseif (60.0 < thd <= 70.0) return 0.22 elseif (70.0 < thd <= 80.0) return 0.14 elseif (80.0 < thd <= 90.0) return 0.17 end elseif ntype == 11 return 2 * (1 + cos(2*θ))/pi elseif ntype == 12 return 2 * (1 - cos(2*θ))/pi elseif ntype == 13 return 2 * (1 - cos(4*θ))/pi elseif ntype == 14 return 2 * (1 + cos(4*θ))/pi elseif ntype == 15 return 2/π elseif ntype == 16 return sin(θ) elseif ntype == 17 if (0 < θ_d <= 40.0) return 0.0 elseif (40.0 < θ_d <= 60.0) return 0.053 elseif (60.0 < θ_d <= 80.0) return 0.149 elseif (80.0 < θ_d <= 100.0) return 0.255 elseif (100.0 < θ_d <= 120.0) return 0.416 elseif (120.0 < θ_d <= 140.0) return 0.114 elseif (140.0 < θ_d) return 0.0 end end end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
13801
""" Given a complex number, return the complex number with absolute value of both parts """ abs_components(x::Complex) = complex(abs(real(x)),abs(imag(x))) """ Given a complex number, return the complex number with same real part and absolute value of imaginary part """ abs_imag_only(x::Complex) = complex(real(x),abs(imag(x))) """ Calculate forward scattering amplitudes """ function afsal(Θᵢʳ, leaf::Leaf, k₀) # Calculate integral of p(θ)*sin(θ)^2 from 0 to pi # That is, the average integral over inclinations # prob needs to be replaced with Distributions.jl (which can integrate better anyhow) f(x) = prob(x, leaf.pdf_num, leaf.pdf_param) * sin(x)^2 ai1 = quadgk(f, 0, π)[1] # Volume of leaf vol = π * leaf.a_maj * leaf.b_min * leaf.t / 4 # ν² * vol / 4π β = k₀^2 * vol / (4π) xi = leaf.ϵ - 1 xii = xi/(2 * (1 + xi)) afhhl = β * xi * (1 - xii * ai1) afvvl = β * xi * (1 - xii * (2 * sin(Θᵢʳ)^2 + (cos(Θᵢʳ)^2 - 2 * sin(Θᵢʳ)^2) * ai1)) return (afhhl, afvvl) end """ Calculate scattering coefficients for a thin disk """ function asal(Θᵢʳ, leaf::Leaf, k₀) # Equations 14 and 29, leading term a2 = abs(k₀^2 * (leaf.ϵ - 1) / sqrt(4π))^2 # eb = (leaf.ϵ - 1) / leaf.ϵ b2 = abs(eb)^2 sm = [0.0, 0.0, 0.0] sidr = [0.0, 0.0] sivh = [0.0, 0.0] cnst3 = 2π*leaf.a_maj*leaf.b_min/4 cnti=1.0 cntj=1.0 # Double integral trapezoidal rule? # Loop over θ for i = 1:n_θ+1 θ_curr = (i - 1) * δθ cnti = (i == 1 || i == n_θ+1) ? 0.5 : cnti pdf = prob(θ_curr,leaf.pdf_num,leaf.pdf_param) pdf < 1.0e-03 && break sumx = [0.0, 0.0, 0.0] sjdr = [0.0, 0.0] sjvh = [0.0, 0.0] for j = 1:n_ϕ+1 ϕ_curr=(j-1)*δϕ cntj = (j == 1 || j == n_ϕ+1) ? 0.5 : cntj # calculate swig--beam pattern alphb = (cos(θ_curr)*sin(Θᵢʳ))*sin(ϕ_curr) alphd = alphb - (sin(θ_curr)*cos(Θᵢʳ)) betad = sin(Θᵢʳ)*cos(ϕ_curr) nud = sqrt(alphd^2*(leaf.a_maj/2)^2+betad^2*(leaf.b_min/2)^2)* k₀/π nub = sqrt(alphb^2*(leaf.a_maj/2)^2+betad^2*(leaf.b_min/2)^2)* k₀/π zetad = 2π*nud zetab = 2π*nub swigd = cnst3 * (besselj1(zetad) / zetad) swigb = cnst3 * (besselj1(zetab) / zetab) # calculate integrands sthcp2 = (sin(θ_curr)*cos(ϕ_curr))^2 ss2 = (sin(θ_curr)*cos(Θᵢʳ)*sin(ϕ_curr)-(cos(θ_curr)*sin(Θᵢʳ)))^2 scsph2 = (sin(θ_curr)*cos(Θᵢʳ))^2*sin(ϕ_curr)^2 scs2 = (cos(θ_curr)*sin(Θᵢʳ))^2 - scsph2 scs1 = scsph2+(cos(θ_curr)*sin(Θᵢʳ))^2 sscci = cos(Θᵢʳ)^2-sin(Θᵢʳ)^2 sccs = (cos(θ_curr)*sin(Θᵢʳ))^2-scsph2 cnt = cnti*cntj sumx[1] += (abs(1.0-eb*sthcp2))^2*cnt*swigd^2 sumx[2] += sthcp2*ss2*cnt*swigd^2 sumx[3] += (abs(1.0-eb*ss2))^2*cnt*swigd^2 sjdr[1] += (abs(1.0-eb*sthcp2))^2*cnt*swigb^2 # hh sjdr[2] += (abs(sscci+eb*sccs))^2*cnt*swigb^2 # vv sjvh[1] += sthcp2*scs1*cnt*swigb^2 sjvh[2] += sthcp2*scs2*cnt*swigb^2 cntj=1.0 end sm += sumx * pdf sidr += sjdr * pdf sivh[1]+=sjvh[1]*pdf sivh[2]+=sjvh[2]*pdf cnti=1.0 end sgbd = a2*leaf.t^2 * sm * Δθ * Δϕ sgbd[2] *= b2 sgbdr = a2*leaf.t^2 * sidr*Δθ*Δϕ sgbvh = a2*leaf.t^2 * b2 * abs.(sivh)*Δθ*Δϕ return BackscatterFields(sgbd, sgbdr, sgbvh) end """ Calculation of average forward scattering amplitudes of a finite length cylinder, exact series solution """ function wood_forward(wood::Wood) # Maximum n for scattering loop nmax= min(20, Integer(floor(k₀*wood.r+4*(k₀*wood.r)^(1/3)+2))) # To store total averaged scattering matrix S = zeros(Float64, 2, 2) # Loop over θs for i = 1:n_θ+1 # Current θ θ_curr = (i-1)*δθ cnti = (i == 1 || i == n_θ+1) ? 0.5 : 1.0 # Probability of θ pdf = prob(θ_curr,wood.pdf_num,wood.pdf_param) (pdf < 1.0e-03) && break # To store averaged scattering matrix for current θ S_θ = zeros(Float64, 2, 2) # Loop over ϕs for j = 1:n_ϕ+1 # Current ϕ ϕ_curr = (j-1)*δϕ cntj = (j == 1 || j == n_ϕ+1) ? 0.5 : 1.0 cnt=cnti*cntj # Get scattering at current angle dsi, S_curr = scattering(θ_curr, ϕ_curr, nmax, 1, x -> -x, x->x, x -> π-x, x->x, wood) S_θ += (cnt*S_curr/dsi) * Δθ * Δϕ end # Weight scattering sum by θ pdf S += S_θ * pdf end # Return total S return S end """ Calculation of average backscatter cross-section of a finite length cylinder, exact series solution (KARAM, FUNG, AND ANTAR, 1988) """ function wood_backward(wood::Wood) # Maximum n for scattering loop nmax=min(20, Integer(floor(k₀*wood.r+4.0*(k₀*wood.r)^(1/3)+2.0))) # To store total averaged scattering matrix S_d = zeros(3) # hh, vh, vv S_dr = zeros(2) # hh, vv S_vh = zeros(2) # smvh[1] is smvh1, smvh[2] is **smvh3** # Loop over θs for i = 1:n_θ+1 # Current θ θ_curr = (i-1) * δθ cnti = (i == 1 || i == n_θ+1) ? 0.5 : 1.0 # Probability of θ pdf = prob(θ_curr,wood.pdf_num,wood.pdf_param) (pdf < 1.0e-03) && break # To store averaged scattering matrix for current θ S_d_θ = zeros(3) # hh, vh, vv S_dr_θ = zeros(2) # hh, vv S_vh_θ = zeros(2) # smvh[1] is smvh1, smvh[2] is **smvh3** # Loop over ϕs for j = 1:n_ϕ+1 # Current ϕ ϕ_curr= (j-1) * δϕ cntj = (j == 1 || j == n_ϕ+1) ? 0.5 : 1.0 cnt = cnti*cntj # Get direct scattering at current angle dsi, S = scattering(θ_curr, ϕ_curr, nmax, 1, x -> -x, x->-x, x -> x, x->x+π, wood) S_d_θ += abs.([S[1,1] ; S[1,2] ; S[2,2]] / dsi).^2*cnt # Get direct-reflected scattering at current angle dsi, S = scattering(θ_curr, ϕ_curr, nmax, 1, x -> x, x->-x, x -> π-x, x->x+π, wood) S_dr_θ += abs.([S[1,1] ; S[2,2]] / dsi).^2*cnt S_vh_θ[1] += abs(S[1,2]/(dsi))^2*cnt fvhc=conj(S[1,2]) # Get vh scattering at current angle dsi, S = scattering(θ_curr, ϕ_curr, nmax, -1, x -> -x, x->-x, x -> π-x, x->x+π, wood) S_vh_θ[2] += abs(S[1,2]*fvhc/(dsi*dsi))*cnt end # Weight scattering sum by θ pdf S_d += S_d_θ * pdf S_dr += S_dr_θ * pdf S_vh += S_vh_θ * pdf end # Why are we multiplying by 4π here? S_d = 4π * Δϕ * Δθ * S_d S_dr = 4π * Δϕ * Δθ * S_dr S_vh = 4π * Δϕ * Δθ * S_vh return BackscatterFields(S_d, S_dr, S_vh) end """ Calculate scattering cross-section of a finite length cylinder with specified orientation """ function scattering(θ_curr, ϕ_curr, nmax, sign_i, new_tvs, new_ths, new_thetas, new_phys, wood::Wood) # B.44 from Zyl and Kim book Synthetic Aperture Radar Polarimetry tvi = -sin(θ_curr)*cos(Θᵢʳ)*cos(ϕ_curr-ϕ_iʳ)-sign_i*cos(θ_curr)*sin(Θᵢʳ) # B.45 from Zyl and Kim book Synthetic Aperture Radar Polarimetry thi = sign_i*sin(θ_curr)*sin(ϕ_curr-ϕ_iʳ) ti = sqrt(tvi^2+thi^2) ths = new_ths(thi) tvs = new_tvs(tvi) ts = sqrt(ths^2+tvs^2) cthi = sin(θ_curr)*sin(Θᵢʳ)*cos(ϕ_curr-ϕ_iʳ)-sign_i*cos(θ_curr)*cos(Θᵢʳ) cphi = (sin(Θᵢʳ)*cos(θ_curr)*cos(ϕ_curr-ϕ_iʳ)+sign_i*sin(θ_curr)*cos(Θᵢʳ))/sqrt(1-cthi^2) cthi,cphi = max.(min.([cthi, cphi], 1.0), -1.0) thetai, phyi = acos.([cthi, cphi]) thetas = new_thetas(thetai) phys = new_phys(phyi) S = scattering_amplitude(nmax, wood, thetai, thetas, phyi, phys) dsi=ti*ts # B.35 from Zyl and Kim book Synthetic Aperture Radar Polarimetry Ts = [tvs ths ; -ths tvs] Ti = [tvi -thi ; thi tvi] S_new = Ts * S * Ti return dsi, S_new end """ Calculate bistatic scattering amplitude in the cylinder coordinate Equations 26, 27 in Electromagnetic Wave Scattering from Some Vegetation Samples (KARAM, FUNG, AND ANTAR, 1988) http://www2.geog.ucl.ac.uk/~plewis/kuusk/karam.pdf """ function scattering_amplitude(nmax, wood_c::Wood, θᵢ, Θₛ, ϕᵢ, ϕₛ) μᵢ = cos(θᵢ) μₛ = cos(Θₛ) sin_θₛ = sqrt(1-μₛ^2) # [hh hv ; vh vv] s = zeros(Complex, 2,2) # Equation 26 (Karam, Fung, Antar) argum = k₀*(wood_c.l/2)*( μᵢ+μₛ ) μ_si = (argum == 0.0) ? 1.0 : sin(argum)/argum # Calculate scattering amplitude for n = 0 z₀, A₀, B₀, e_0v, e_0h, ηh_0v, ηh_0h = cylinder(0, wood_c, θᵢ, Θₛ) s0 = [B₀*ηh_0h 0 ; 0 e_0v*(B₀ * μₛ * μᵢ - sin_θₛ * z₀)] # Loop over all needed n values for n = 1:nmax # Cylindrical scattering coefficients at current n zₙ,Aₙ,Bₙ,e_nv,e_nh,ηh_nv,ηh_nh = cylinder(n, wood_c, θᵢ, Θₛ) sphn = 0.0 π_δ = 0.0001 cphn = (π - π_δ < ϕₛ - ϕᵢ < π + π_δ) ? (-1)^n : 1.0 # Inside summation term in each line of Equation 27 s[1,1] += 2*(ηh_nh*Bₙ + ej*e_nh*Aₙ*μᵢ) * cphn s[1,2] += (ηh_nv*Bₙ + ej*e_nv*Aₙ*μᵢ) * sphn s[2,1] += ((e_nh* μᵢ *Bₙ - ej*ηh_nh*Aₙ)* μₛ - sin_θₛ * e_nh*zₙ) * sphn s[2,2] += 2*((e_nv* μᵢ *Bₙ - ej*ηh_nv*Aₙ)* μₛ - sin_θₛ * e_nv*zₙ) * cphn end # Added coefficients to finish Equation 27 h = (wood_c.l/2) F = k₀^2 * h * (wood_c.ϵ-1.0) * μ_si * (s0 + s) F[1,2] *= 2 * ej F[2,1] *= 2 * ej return F end """ Compute the coefficients of the series expansion of cylinder scattering amplitude. Equation 24 in Electromagnetic Wave Scattering from Some Vegetation Samples (KARAM, FUNG, AND ANTAR, 1988) http://www2.geog.ucl.ac.uk/~plewis/kuusk/karam.pdf """ function cylinder(n::Integer, wood_c::Wood, Θᵢ::Real, Θₛ::Real) # Constants a = wood_c.r ϵᵣ = wood_c.ϵ μᵢ = cos(Θᵢ) μₛ = cos(Θₛ) coef1 = sqrt(ϵᵣ-μᵢ^2) sin_Θᵢ = sqrt( 1-μᵢ^2) # Last equations in 24 u = k₀ * a * coef1 vᵢ = k₀ * a * sqrt(1-μᵢ^2) vₛ = k₀ * a * sqrt(1-μₛ^2) # Bessel functions and derivatives at u, v Jₙu=besselj(n,u) Hₙv=besselj(n,vᵢ) - ej*bessely(n,vᵢ) d_Jₙu=dbessj(n,u) d_Hₙv=dbessj(n,vᵢ) - ej*dbessy(n,vᵢ) # Equation 26 (Karam, Fung, Antar) zₙ, znp1, znm1 = zeta(n, a, u, vₛ) # Equation 28 (Karam, Fung, Antar) Aₙ = (znm1-znp1)/(2*coef1) Bₙ = (znm1+znp1)/(2*coef1) # Compute Rₙ with sub-expressions term1 = (d_Hₙv/(vᵢ*Hₙv)-d_Jₙu/(u*Jₙu)) term2 = (d_Hₙv/(vᵢ*Hₙv)-ϵᵣ*d_Jₙu/(u*Jₙu)) term3 = (1/vᵢ^2-1/u^2)*n*μᵢ Rₙ = (π*vᵢ^2*Hₙv/2) * (term1*term2-term3^2) # Calculate remaining terms, using above sub-expressions e_nv = ej*sin_Θᵢ*term1/(Rₙ*Jₙu) e_nh = -sin_Θᵢ*term3/(Rₙ*Jₙu) ηh_nv = -e_nh ηh_nh = ej*sin_Θᵢ*term2/(Rₙ*Jₙu) return (zₙ, Aₙ, Bₙ, e_nv, e_nh, ηh_nv, ηh_nh) end """ Calculate zeta function using bessel functions Equation 26 in Electromagnetic Wave Scattering from Some Vegetation Samples (KARAM, FUNG, AND ANTAR, 1988) http://www2.geog.ucl.ac.uk/~plewis/kuusk/karam.pdf """ function zeta(n::Integer, a, u, vs) # Pre-compute bessel function outputs at n-1, n, n+1, n+2 bjnu=besselj(n,u) bjnv=besselj(n,vs) bjnp1u=besselj(n+1,u) bjnp1v=besselj(n+1,vs) bjnp2v=besselj(n+2,vs) bjnp2u=besselj(n+2,u) bjnm1u=besselj(n-1,u) bjnm1v=besselj(n-1,vs) # Compute z_n values znp1 = (a^2 / (u^2-vs^2)) * (u * bjnp1v * bjnp2u - vs * bjnp1u * bjnp2v) zn = (a^2 / (u^2-vs^2)) * (u * bjnv * bjnp1u - vs * bjnu * bjnp1v) znm1 = (a^2 / (u^2-vs^2)) * (u * bjnm1v * bjnu - vs * bjnm1u * bjnv) return zn, znp1, znm1 end # Bessel function derivatives dbessj(n, x) = -n/x*besselj(n,x)+besselj(n-1,x) dbessy(n, x) = -n/x*bessely(n,x)+bessely(n-1,x) """ 3.1.2 in SAATCHI, MCDONALD """ function funcm(x, y, d) dag = x+y dagd = dag * d z = abs(dagd) # Edge cases z < 1.0e-03 && return d z > 1.6e02 && return 1.0/dag return (1.0 - exp(-(dagd)))/dag end function funcp(x, y, d) dag=x+y dagd=dag*d z=abs(dagd) # Edge cases z < 1e-3 && return d z > 1.6e2 && return 1.0/dag return (exp(dagd)-1.0)/dag end function cfun(a, e, d) dag=a+e dagd=dag*d a3=abs(dagd) # Edge cases a3 < 1.0e-03 && return d a3 > 1.6e02 && return 1.0/dag return (1.0 - exp(-(dagd)))/dag end """ Oh et al, 1992 semi-emprical model for rough surface scattering Equation 3.1.5 in Coherent Effects in Microwave Backscattering Models for Forest Canopies (SAATCHI, MCDONALD) https://www.researchgate.net/publication/3202927_Semi-empirical_model_of_the_ ensemble-averaged_differential_Mueller_matrix_for_microwave_backscattering_from_bare_soil_surfaces """ function grdoh(ksig) r0 = abs((1-sqrt(ϵ_g))/(1+sqrt(ϵ_g)))^2 g=0.7*(1-exp(-0.65*ksig^1.8)) q=0.23*(1-exp(-ksig))*sqrt(r0) sp1=(2*Θᵢʳ/π)^(1/(3*r0)) sp=1-sp1*exp(-ksig) rgh = (cos(Θᵢʳ)-sqrt(ϵ_g-sin(Θᵢʳ)^2))/(cos(Θᵢʳ)+sqrt(ϵ_g-sin(Θᵢʳ)^2)) rgv = (ϵ_g*cos(Θᵢʳ)-sqrt(ϵ_g-sin(Θᵢʳ)^2))/(ϵ_g*cos(Θᵢʳ)+sqrt(ϵ_g-sin(Θᵢʳ)^2)) rh0, rv0 = abs.([rgh rgv]).^2 sighh=g*sp*cos(Θᵢʳ)^3*(rh0+rv0) sigvv=g*cos(Θᵢʳ)^3*(rh0+rv0)/sp sigvh=q*sigvv # 3.1.5 shhg=sighh*exp(-4*imag(K_hc*d_c + K_ht*d_t)) # Factor of 2 pulled out in exp svvg=sigvv*exp(-4*imag(K_vc*d_c + K_vt*d_t)) # Factor of 2 pulled out in exp svhg=sigvh*exp(-2*imag((K_hc+K_vc)*d_c + (K_ht+K_vt)*d_t)) sg = [shhg svhg svvg] gd = 10 * log10.([sighh sigvh sigvv]) return sg, gd end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
1447
""" All leaf-related parameters """ struct Leaf ϵ # Dielectric constant a_maj # Major axis (m) b_min # Minor axis (m) t # Thickness (m) ρ # Density (m3) pdf_num # PDF number pdf_param # PDF parameter end """ All wood-related parameters (branch or trunk) """ struct Wood ϵ # Dielectric constant r # Radius (m) l # Length (m) ρ # Density (m3) pdf_num # PDF number pdf_param # PDF parameter end mutable struct BackscatterFields d::Array dr::Array vh::Array end struct Forest_Scattering_Parameters # Frequency bfrghz # Leaf object leaf::Leaf # Two branch objects branch_1::Wood branch_2::Wood # Trunk object trunk::Wood d_c d_t ϵ_g l sig end mutable struct Forest_Scattering_Output theti sighhd1 sighhd2 sighhd3 sighhdr1 sighhdr2 sighhdr3 sighht sighhd sighhdr sigvvd1 sigvvd2 sigvvd3 sigvvdr1 sigvvdr2 sigvvdr3 sigvvt sigvvd sigvvdr sigvhd1 sigvhd2 sigvhd3 sigvhdr1 sigvhdr2 sigvhdr3 sigvht sigvhd sigvhdr ghhd gvhd gvvd sighhi sigvhi sigvvi sigvhi1 sigvhi2 sigvhi3 cofhh cofvh cofvv athc atvc atht atvt end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
953
FT = Float64 # Conductivity polynomials (can be defined outside): const TempPoly = Polynomial(FT.([2.903602, 8.607e-2, 4.738817e-4, -2.991e-6, 4.3041e-9]),:T) const SalPoly1 = Polynomial(FT.([37.5109, 5.45216, 0.014409]),:S); const SalPoly2 = Polynomial(FT.([1004.75, 182.283, 1.0]),:S); const α₀PolNom = Polynomial(FT.([6.9431, 3.2841, -0.099486]),:S); const α₀PolDenom = Polynomial(FT.([84.85, 69.024, 1.0]),:S); const α₁ = Polynomial(FT.([49.843, -0.2276, 0.00198]),:S); const aU = FT.([0.46606917e-2, -0.26087876e-4, -0.63926782e-5, 0.63000075e1, 0.26242021e-2, -0.42984155e-2, 0.34414691e-4, 0.17667420e-3, -0.20491560e-6, 0.58366888e3, 0.12634992e3, 0.69227972e-4, 0.38957681e-6, 0.30742330e3, 0.12634992e3, 0.37245044e1, 0.92609781e-2, -0.26093754e-1] );
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
2485
""" $(FUNCTIONNAME)(FT=Float64) Creates a `LeafDistribution` following a planophile (mostly horizontal) distribution using a Beta distribution Standard values for θₗ (26.76) and s (18.51) from Bonan https://doi.org/10.1017/9781107339217.003, Table 2.1 """ function planophile_leaves(FT=Float64) θ = FT(26.76) s = FT(18.51) α, β = βparameters(deg2rad(θ), deg2rad(s)); return LeafDistribution(Beta(FT(α), FT(β)), FT(2/π)); end function planophile_leaves2(FT=Float64) return LeafDistribution(Beta(FT(1), FT(2.768)), FT(2/π)); end """ $(FUNCTIONNAME)(FT=Float64) Creates a `LeafDistribution` following a uniform distribution (all angles equally likely) """ function uniform_leaves(FT=Float64) return LeafDistribution(Uniform(FT(0), FT(1)),FT(2/π)); end """ $(FUNCTIONNAME)(FT=Float64) Creates a `LeafDistribution` following a plagiophile (mostly 45degrees) distribution using a Beta distribution Standard values for θₗ (45.0) and s (16.27) from Bonan https://doi.org/10.1017/9781107339217.003, Table 2.1 """ function plagiophile_leaves(FT=Float64) θ = FT(45) s = FT(16.27) α, β = βparameters(deg2rad(θ), deg2rad(s)); return LeafDistribution(Beta(FT(α), FT(β)), FT(2/π)); end """ $(FUNCTIONNAME)(FT=Float64) Creates a `LeafDistribution` following a erectophile (mostly vertical) distribution using a Beta distribution Standard values for θₗ (63.24) and s (18.5) from Bonan https://doi.org/10.1017/9781107339217.003, Table 2.1 """ function erectophile_leaves(FT=Float64) θ = FT(63.24) s = FT(18.5) α, β = βparameters(deg2rad(θ), deg2rad(s)); return LeafDistribution(Beta(FT(α), FT(β)), FT(2/π)); end """ $(FUNCTIONNAME)(FT=Float64) Creates a `LeafDistribution` following a spherical (distributed as facets on a sphere) distribution using a Beta distribution Standard values for θₗ (57.3) and s (21.55) from Bonan https://doi.org/10.1017/9781107339217.003, Table 2.1 """ function spherical_leaves(FT=Float64) θ = FT(57.3) s = FT(21.55) α, β = βparameters(deg2rad(θ), deg2rad(s)); return LeafDistribution(Beta(FT(α), FT(β)), FT(2/π)); end function flat_leaves(FT=Float64) θ = FT(57.3) s = FT(21.55) α, β = βparameters(deg2rad(θ), deg2rad(s)); return LeafDistribution(Beta(FT(α), FT(β)), FT(2/π)); end # Beta function as leaf angular distribution (see RAMI, ν=α, μ=β) function beta_leaves(α::FT,β::FT) where FT return LeafDistribution(Beta(α, β), FT(2/π)); end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
3004
""" $(FUNCTIONNAME)(λ_bnds) Loads in the PROSPECT-PRO database of pigments (and other) absorption cross section in leaves, returns a [`LeafOpticalProperties`](@ref) type struct with spectral units attached. # Arguments - `λ_bnds` an array (with or without a spectral grid unit) that defines the upper and lower limits over which to average the absorption cross sections # Examples ```julia-repl julia> using Unitful # Need to include Unitful package julia> opti = createLeafOpticalStruct((400.0:5:2400)*u"nm"); # in nm julia> opti = createLeafOpticalStruct((0.4:0.1:2.4)*u"μm"); # in μm julia> opti = CanopyOptics.createLeafOpticalStruct((10000.0:100:25000.0)u"1/cm"); # in wavenumber (cm⁻¹) ``` """ function createLeafOpticalStruct(λ_bnds) FT = eltype(ustrip(λ_bnds[1])) # Reference input grid converted to nm: λ_ref = unit2nm(λ_bnds) KS = readdlm(OPTI_2021, '\t',FT) N = length(λ_bnds)-1 λ_out, nᵣ, Kcab, Kcar, Kant, Kb, Kw, Km, Kp, Kcbc = [zeros(FT,N) for i = 1:N]; vars = (λ_out, nᵣ, Kcab, Kcar, Kant, Kb, Kw, Km, Kp, Kcbc) λ = KS[:,1]*u"nm"; @inbounds for i=1:N start = min(λ_ref[i],λ_ref[i+1]) stop = max(λ_ref[i],λ_ref[i+1]) ind_all = findall((λ .≥ start) .& (λ .< stop) ) isempty(ind_all) ? (@warn "Some λ_bnds bins are empty, better coarsen the input grid $(λ_bnds[i]) -> $(λ_bnds[i+1])" ) : nothing for j in eachindex(vars) vars[j][i] = mean(view(KS,ind_all,j)); end end # Get output unit: ou = unit(λ_bnds[1]) (typeof(ou) <: Unitful.FreeUnits{(), NoDims, nothing}) ? out_unit = u"nm" : out_unit = ou return LeafOpticalProperties(uconvSpectral(λ_out*u"nm",out_unit), nᵣ, Kcab, Kcar, Kant, Kb, Kw, Km, Kp, Kcbc) end """ $(FUNCTIONNAME)() As in $(FUNCTIONNAME)(λ_bnds) but reads in the in Prospect-PRO database at original resolution (400-2500nm in 1nm steps) """ function createLeafOpticalStruct() λ_bnds = (399.5:2500.5)u"nm" createLeafOpticalStruct(λ_bnds) end "Convert an input array with Spectral units (or none) to a grid in nm" function unit2nm(λ_bnds) try return uconvSpectral(λ_bnds, u"nm"); catch e # Assume without unit is in "nm" already @warn "Assuming unit of [nm] here for optical struct" return λ_bnds*u"nm" end end "Avoiding annoying issues with uconvert for Spectra() (can't do nm->nm!)" # From unit of `in` to `out_unit` (just attaching out_unit if unit is missing) function uconvSpectral(in,out_unit) unit(in[1]) == out_unit ? in : uconvert.(out_unit, in, Spectral()) end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
900
""" dirVector{FT} Struct for spherical coordinate directions in θ (elevation angle) and ϕ (azimuth angle) # Fields $(DocStringExtensions.FIELDS) """ struct dirVector{FT} θ::FT ϕ::FT end """ dirVector_μ{FT} Struct for spherical coordinate directions in θ (elevation angle) and ϕ (azimuth angle)" # Fields $(DocStringExtensions.FIELDS) """ struct dirVector_μ{FT} μ::FT ϕ::FT end # Define dot product for the directional vector in spherical coordinates: LinearAlgebra.dot(Ω₁::dirVector, Ω₂::dirVector) = cos(Ω₁.θ) * cos(Ω₂.θ) + sin(Ω₁.θ) * sin(Ω₂.θ) * cos(Ω₂.ϕ - Ω₁.ϕ) # Define dot product for the directional vector in spherical coordinates: LinearAlgebra.dot(Ω₁::dirVector_μ, Ω₂::dirVector_μ) = Ω₁.μ * Ω₂.μ + sqrt(1-Ω₁.μ^2) * sqrt(1-Ω₂.μ^2) * cos(Ω₂.ϕ - Ω₁.ϕ) function dot_product(μ₁::FT, μ₂::FT, dϕ::FT) where FT μ₁ * μ₂ + sqrt(1-μ₁^2) * sqrt(1-μ₂^2) * cos(dϕ) end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
3787
"Abstract Type for canopy scattering" abstract type AbstractCanopyScatteringType{FT<:AbstractFloat} end "Model for bi-lambertian canopy leaf scattering" Base.@kwdef struct BiLambertianCanopyScattering{FT<:AbstractFloat} <: AbstractCanopyScatteringType{FT} "Lambertian Reflectance" R::FT = FT(0.3) "Lambertian Transmission" T::FT = FT(0.1) "Number of quadrature points in inclination angle" nQuad::Int = 30 end "Model for specular canopy leaf scattering" Base.@kwdef struct SpecularCanopyScattering{FT<:AbstractFloat} <: AbstractCanopyScatteringType{FT} "Refractive index" nᵣ::FT = FT(1.5) "Roughness parameter" κ::FT = FT(0.5) "Number of quadrature points in azimuth" nQuad::Int = 20 end "Abstract Type for leaf distributions" abstract type AbstractLeafDistribution{FT<:AbstractFloat} end """ struct LeafDistribution{FT<:AbstractFloat} A struct that defines the leaf angular distribution in radians (from 0->π/2; here scaled to [0,1]) # Fields $(DocStringExtensions.FIELDS) """ struct LeafDistribution{FT<:AbstractFloat} <: AbstractLeafDistribution{FT} "Julia Univariate Distribution from Distributions.js" LD::UnivariateDistribution "Scaling factor to normalize distribution (here mostly 2/π as Beta distribution is from [0,1])" scaling::FT end #################################### "Abstract Type for leaf composition" abstract type AbstractLeafProperties end """ struct LeafProperties{FT} A struct which stores important variables of leaf chemistry and structure # Fields $(DocStringExtensions.FIELDS) """ Base.@kwdef struct LeafProspectProProperties{FT} <: AbstractLeafProperties ### Prospect related parameters "Leaf structure parameter [0-3]" N::FT = FT(1.4 ) "Chlorophyll a+b content `[µg cm⁻²]`" Ccab::FT = FT(40.0)#u"µg/cm^2" "Carotenoid content `[µg cm⁻²]`" Ccar::FT = FT(10.0)#u"µg/cm^2" "Anthocynanin content `[nmol cm⁻²]`" Canth::FT = FT(0.5)#u"nmol/cm^2" "Brown pigments content in arbitrary units" Cbrown::FT = FT(0.0) "Equivalent water thickness `[cm]`, typical about 0.002-0.015" Cw::FT = FT(0.012)#u"cm" "Dry matter content (dry leaf mass per unit area) `[g cm⁻²]`, typical about 0.003-0.016" Cm::FT = FT(0.0)#u"g/cm^2" "protein content `[g/cm]`" Cprot::FT = FT(0.001)#u"g/cm^2" "Carbone-based constituents content in `[g/cm⁻²]` (cellulose, lignin, sugars...)" Ccbc::FT = FT(0.009)#u"g/cm^2" end #################################### "Abstract type for Prospect model versions" abstract type AbstractProspectProperties end """ struct PigmentOpticalProperties{FT} A struct which stores important absorption cross sections of pigments, water, etc # Fields $(DocStringExtensions.FIELDS) """ struct LeafOpticalProperties{FT,FT2} <: AbstractProspectProperties "Wavelength `[length]`" λ::FT2 #typeof(([1.0])u"nm") ### Prospect-PRO related parameters "Refractive index of leaf material " nᵣ::Array{FT, 1} "specific absorption coefficient of chlorophyll (a+b) `[cm² μg⁻¹]`" Kcab::Array{FT, 1} "specific absorption coefficient of carotenoids `[cm² μg⁻¹]`" Kcar::Array{FT, 1} "specific absorption coefficient of Anthocyanins `[cm² nmol⁻¹]`" Kant::Array{FT, 1} "specific absorption coefficient of brown pigments (arbitrary units)" Kb::Array{FT, 1} "specific absorption coefficient of water `[cm⁻¹]`" Kw::Array{FT, 1} "specific absorption coefficient of dry matter `[cm² g⁻¹]`" Km::Array{FT, 1} "specific absorption coefficient of proteins `[cm² g⁻¹]`" Kp::Array{FT, 1} "specific absorption coefficient of carbon based constituents `[cm² g⁻¹]`" Kcbc::Array{FT, 1} end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
797
"Abstract Material Type (can be all)" abstract type AbstractMaterial end "Abstract water type" abstract type AbstractWater <: AbstractMaterial end "Abstract soil type" abstract type AbstractSoil <: AbstractMaterial end "Pure liquid water" struct LiquidPureWater <: AbstractWater end "Salty liquid water" Base.@kwdef struct LiquidSaltWater{FT} <: AbstractWater "Salinity in `[PSU]`" S::FT = FT(10) end "Pure Ice" struct PureIce <: AbstractWater end "Soil MW properties" Base.@kwdef struct SoilMW{FT} <: AbstractSoil "Sand Fraction ∈ [0,1]" sand_frac::FT = FT(0.2) "Clay Fraction ∈ [0,1]" clay_frac::FT = FT(0.1) "Volumetric water content ∈ [0,1]" mᵥ::FT = FT(0.35) "Bulk density, `g/cm³` (typical value is 1.7 gcm³)" ρ::FT = FT(1.7) end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
1659
# Copy of RadiativeTransfer.Scattering, had problems including it otherwise """ type AbstractPolarizationType Abstract Polarization type """ abstract type AbstractPolarizationType end """ struct Stokes_IQUV{FT<:AbstractFloat} A struct which defines full Stokes Vector ([I,Q,U,V]) RT code # Fields $(DocStringExtensions.FIELDS) """ Base.@kwdef struct Stokes_IQUV{FT<:AbstractFloat} <: AbstractPolarizationType "Number of Stokes components (int)" n::Int = 4 "Vector of length `n` for ... (see eq in Sanghavi )" D::Array{FT} = [1.0, 1.0, -1.0, -1.0] "Incoming Stokes vector for scalar only" I₀::Array{FT} = [1.0, 0.0, 0.0, 0.0] #assuming completely unpolarized incident stellar radiation end """ struct Stokes_IQU{FT<:AbstractFloat} A struct which defines Stokes Vector ([I,Q,U]) RT code # Fields $(DocStringExtensions.FIELDS) """ Base.@kwdef struct Stokes_IQU{FT<:AbstractFloat} <: AbstractPolarizationType "Number of Stokes components (int)" n::Int = 3 "Vector of length `n` for ... (see eq in Sanghavi )" D::Array{FT} = [1.0, 1.0, -1.0] "Incoming Stokes vector for scalar only" I₀::Array{FT} = [1.0, 0.0, 0.0] #assuming linearly unpolarized incident stellar radiation end """ struct Stokes_I{FT<:AbstractFloat} A struct which define scalar I only RT code # Fields $(DocStringExtensions.FIELDS) """ Base.@kwdef struct Stokes_I{FT<:AbstractFloat} <: AbstractPolarizationType "Number of Stokes components (int)" n::Int = 1 "Vector of length `n` for ... (see eq in Sanghavi )" D::Array{FT} = [1.0] "Incoming Stokes vector for scalar only" I₀::Array{FT} = [1.0] end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
3056
"Get Beta Distribution parameters using standard tabulated values θₗ,s, Eq. 2.9 and 2.10 in Bonan" function βparameters(θₗ,s) α = (1 - (s^2+θₗ^2) / (θₗ*π/2) ) / ( ((s^2+θₗ^2) / θₗ^2) - 1 ) β = ( (π/2)/θₗ -1 ) * α return α,β end "Eq 46 in Shultis and Myneni" function H(μ::FT,μₗ::FT) where FT # cot(θ) * cot(θₗ) r = cot(acos(μ)) * cot(acos(μₗ)); if r > 1 return μ * μₗ elseif r < -1 return FT(0) else # Eq 47 ϕ = acos(-r); return FT(1/π) * (μ*μₗ*ϕ + sqrt(FT(1)-μ^2) * sqrt(1-μₗ^2) * sin(ϕ)) end end "Eq 45 in Shultis and Myneni, fixed grid in μ for both μ and μ' " function compute_Ψ(μ::AbstractArray{FT,1}, μₗ::FT) where FT H⁺ = H.(μ,μₗ) H⁻ = H.(-μ,μₗ) Ψ⁺ = H⁺ * H⁺' + H⁻ * H⁻' Ψ⁻ = H⁺ * H⁻' + H⁻ * H⁺' return Ψ⁺, Ψ⁻ end "Eq 45 in Shultis and Myneni, fixed grid in μ for both μ and μ' " function compute_Ψ(μ::AbstractArray{FT,1},μꜛ::AbstractArray{FT,1}, μₗ::FT) where FT Ψ⁺ = H.(μ,μₗ) * H.(μꜛ,μₗ)' + H.(-μ,μₗ) * H.(-μꜛ,μₗ)' Ψ⁻ = H.(μ,μₗ) * H.(-μꜛ,μₗ)' + H.(-μ,μₗ) * H.(+μꜛ,μₗ)' return Ψ⁺, Ψ⁻ end " Eq 37 in Shultis and Myneni " function scattering_model_lambertian(Ωⁱⁿ::dirVector, Ωᵒᵘᵗ::dirVector, Ωᴸ::dirVector, r, t) α = (Ωⁱⁿ ⋅ Ωᴸ) * (Ωᵒᵘᵗ ⋅ Ωᴸ) if a<0 return r * abs(Ωᵒᵘᵗ ⋅ Ωᴸ) / π else return t * abs(Ωᵒᵘᵗ ⋅ Ωᴸ) / π end end #See Eq 18, Canopy RT book function getSpecularΩ(Ωⁱⁿ::dirVector{FT}, Ωᵒᵘᵗ::dirVector{FT}) where FT sa = Ωⁱⁿ ⋅ Ωᵒᵘᵗ sa > 1 ? sa = FT(1) : nothing α = acos(sa)/2 # Relative azimuth angle: ϕ = (Ωᵒᵘᵗ.ϕ - Ωⁱⁿ.ϕ) # Leaf polar angle: θₗ = acos((cos(Ωⁱⁿ.θ) + cos(Ωᵒᵘᵗ.θ))/2cos(α)); t = (sin(Ωⁱⁿ.θ) + sin(Ωᵒᵘᵗ.θ) * cos(ϕ))/(2cos(α)*sin(θₗ)) if isnan(t) t = FT(1.0) end # Leaf azimuth angle: ϕₗ = acos(max(FT(-1),min(t,FT(1)))) ϕ > π ? ϕₗ = 2π-ϕₗ-Ωⁱⁿ.ϕ : ϕₗ = ϕₗ+Ωⁱⁿ.ϕ #θₗ > π/2 ? θₗ = θₗ - π/2 : nothing out = dirVector(θₗ,ϕₗ) #ϕ > π ? out = dirVector(θₗ,2π-ϕₗ-Ωⁱⁿ.ϕ) : out = dirVector(θₗ,ϕₗ+Ωⁱⁿ.ϕ) #@show (Ωⁱⁿ ⋅ out) , (Ωᵒᵘᵗ ⋅ out) #@show abs(((Ωⁱⁿ ⋅ out) - (Ωᵒᵘᵗ ⋅ out)) / (Ωᵒᵘᵗ ⋅ out)) * 100 #@show θₗ , ϕₗ @assert abs(((Ωⁱⁿ ⋅ out) - (Ωᵒᵘᵗ ⋅ out)) / (Ωᵒᵘᵗ ⋅ out)) * 100 < 1 "Leaf angle wrong, $Ωⁱⁿ, $Ωᵒᵘᵗ, $out" return out end function getSpecularΩ(Ωⁱⁿ::dirVector_μ{FT}, Ωᵒᵘᵗ::dirVector_μ{FT}) where FT sa = Ωⁱⁿ ⋅ Ωᵒᵘᵗ #@show sa sa > 1 ? sa = FT(1) : nothing # Scattering angle α = acos(sa)/FT(2) # Relative azimuth angle: ϕ = (Ωᵒᵘᵗ.ϕ - Ωⁱⁿ.ϕ) # Leaf polar angle: μₗ = ((Ωⁱⁿ.μ + Ωᵒᵘᵗ.μ)/2cos(α)); t = (sqrt(1-Ωⁱⁿ.μ^2) + sqrt(1-Ωᵒᵘᵗ.μ^2) * cos(ϕ))/(2cos(α)*sqrt(1-μₗ^2)) #@show t, sqrt(1-Ωⁱⁿ.μ^2) + sqrt(1-Ωᵒᵘᵗ.μ) if isnan(t) t = FT(1.0) end # Leaf azimuth angle: ϕₗ = acos(max(FT(-1),min(t,FT(1)))) ϕ > π ? ϕₗ = 2π-ϕₗ-Ωⁱⁿ.ϕ : ϕₗ = ϕₗ+Ωⁱⁿ.ϕ out = dirVector_μ(μₗ,ϕₗ) @assert Ωⁱⁿ ⋅ out ≈ Ωᵒᵘᵗ ⋅ out "Leaf angle wrong in specular reflection, $Ωⁱⁿ, $Ωᵒᵘᵗ, $out" return out, α end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
5096
""" $(FUNCTIONNAME)(mod::LiquidSaltWater, T::FT,f::FT) Computes the complex dieletric of liquid salty walter (Ulaby & Long book) # Arguments - `mod` an [`LiquidSaltWater`](@ref) type struct, provide Salinity in PSU - `T` Temperature in `[⁰K]` - `f` Frequency in `[GHz]` - `S` Salinity in `[PSU]` comes from the `mod` [`LiquidSaltWater`](@ref) struct # Examples ```julia-repl julia> w = CanopyOptics.LiquidSaltWater(S=10.0) # Create struct for salty seawater julia> CanopyOptics.dielectric(w,283.0,10.0) 51.79254073931596 + 38.32304044382495im ``` """ function dielectric(mod::LiquidSaltWater, T::FT,f::FT) where FT<:Real (;S) = mod @assert 0 ≤ S ≤ 45 "Salinity should be ∈ [0,45] PSU" @assert 265 ≤ T ≤ 310 "Temperature should be ∈ [265,310] K" # Equations were tuned for ⁰C but want K input! T = T - FT(273) # Compute σ (Eqs 4.21 - 4.21 in Ulaby and Long) σ₃₅ = TempPoly(T) P = S * SalPoly1(S) / SalPoly2(S) Q = FT(1) + (α₀PolNom(S)/α₀PolDenom(S) * (T - FT(15)))/(T + α₁(T)); σ = σ₃₅ * P * Q ϵS = FT(87.85306) * exp(FT(-0.00456992)*T - aU[1]*S - aU[2]*S^2 - aU[3]*S*T); ϵOne = aU[4] * exp(-aU[5]*T - aU[6]*S - aU[7]*S*T); # Relaxation time constants τ1 = (aU[8] + aU[9] *S) * exp(aU[10] / (T+aU[11])); τ2 = (aU[12] + aU[13]*S) * exp(aU[14] / (T+aU[15])); ϵInf = aU[16] + aU[17]*T + aU[18]*S; # Complex Permittivity Calculation ϵ = ((ϵS-ϵOne) / (FT(1) - 1im * 2π * f * τ1)) + ((ϵOne-ϵInf) / (1-1im * 2π * f * τ2)) + (ϵInf) + 1im*((FT(17.9751)*σ) /f); end """ $(FUNCTIONNAME)(mod::LiquidPureWater, T::FT,f::FT) Computes the complex dieletric of liquid pure walter (Ulaby & Long book) # Arguments - `mod` an [`LiquidSaltWater`](@ref) type struct - `T` Temperature in `[⁰K]` - `f` Frequency in `[GHz]` # Examples ```julia-repl julia> w = CanopyOptics.LiquidPureWater() # Create struct for salty seawater julia> CanopyOptics.dielectric(w,283.0,10.0) 53.45306674215052 + 38.068642430090044im ``` """ function dielectric(mod::LiquidPureWater, T::FT,f::FT) where FT<:Real @assert 265 ≤ T ≤ 310 "Temperature should be ∈ [265,310] K" # Equations were tuned for ⁰C but want K input! T = T - FT(273) ϵS = FT(87.85306) * exp(FT(-0.00456992)*T); ϵOne = aU[4] * exp(-aU[5]*T); τ1 = aU[8] * exp(aU[10] / (T+aU[11])); τ2 = aU[12] * exp(aU[14] / (T+aU[15])); ϵInf = aU[16] + aU[17]*T; # Complex Permittivity Calculation ϵ = ((ϵS-ϵOne) / (FT(1) - 1im * 2π * f * τ1)) + ((ϵOne-ϵInf)./(1-1im * 2π * f * τ2)) + (ϵInf); end """ $(FUNCTIONNAME)(mod::PureIce, T::FT,f::FT) Computes the complex dieletric of liquid pure walter (Ulaby & Long book) # Arguments - `mod` an [`PureIce`](@ref) type struct - `T` Temperature in `[⁰K]` - `f` Frequency in `[GHz]` # Examples ```julia-repl julia> w = CanopyOptics.PureIce() # Create struct for salty seawater julia> CanopyOptics.dielectric(w,283.0,10.0) 53.45306674215052 + 38.068642430090044im ``` """ function dielectric(mod::PureIce, T::FT, f::FT) where FT @assert 233 ≤ T ≤ 273.15 "Temperature should be ∈ [233,273.15] K" # Some constants first θ = (FT(300)/T) - FT(1); B1 = FT(0.0207); B2 = FT(1.16e-11); b = FT(335); # Eqs 4.22-4.25 α = (FT(0.00504) + FT(0.0062) * θ) * exp(-FT(22.1) * θ); βₘ = (B1/T) * exp(b/T) / (exp(b/T)-FT(1))^2 + B2 * f^2; δβ = exp(-FT(9.963) + FT(0.0372) * (T-FT(273.16))); β = βₘ + δβ; ϵ = FT(3.1884) + FT(9.1e-4) *(T-FT(273)) + (α/f + β*f)im; end """ $(FUNCTIONNAME)(mod::SoilMW, T::FT,f::FT) Computes the complex dieletric of soil (Ulaby & Long book) # Arguments - `mod` an [`SoilMW`](@ref) type struct (includes sand_frac, clay_frac, water_frac, ρ) - `T` Temperature in `[⁰K]` - `f` Frequency in `[GHz]` # Examples ```julia-repl julia> w = SoilMW(sand_frac=0.2,clay_frac=0.2, water_frac = 0.3, ρ=1.7 ) # Create struct for salty seawater julia> dielectric(w,283.0,10.0) 53.45306674215052 + 38.068642430090044im ``` """ function dielectric(mod::SoilMW{FT}, T::FT,f::FT) where FT (;sand_frac, clay_frac, mᵥ, ρ) = mod # T = Tk - FT(273) f_hz = f * FT(1e9); # transform from GHz to Hz α = FT(0.65); # eq: 4.68a β₁ = FT(1.27) - FT(0.519) * sand_frac - FT(0.152) * clay_frac; # eq: 4.68b β₂ = FT(2.06) - FT(0.928) * sand_frac - FT(0.255) * clay_frac; # eq: 4.68c ϵ₀ = FT(8.854e-12); if f > 1.3 σ = FT(-1.645) + FT(1.939) * ρ - FT(2.256) * sand_frac + FT(1.594) * clay_frac; # eq: 4.68d elseif 0.3 ≤ f ≤ 1.3 σ = FT(0.0467) + FT(0.22) * ρ - FT(0.411) * sand_frac + FT(0.661) * clay_frac; # eq: 4.70 else σ = FT(0) end # Dielectric Constant of Pure Water ϵw = dielectric(LiquidPureWater(),T,f) # Add conductivity term to ϵ'' (eq. 4.67b) ϵw += im*((FT(2.65)-ρ) / FT(2.65 * mᵥ) * σ / (2π * ϵ₀ * f_hz)) # calculating dielectric constant of soil using eq. 4.66a and 4.66b epsr = (FT(1) + FT(0.66) * ρ + mᵥ^β₁ * real(ϵw).^α - mᵥ)^(1/α); epsi = mᵥ^β₂ .* imag(ϵw); epsr + epsi*im end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
512
"Fresnel reflection, needs pol_type soon too!" function Fᵣ(n::FT,θᵢ::FT) where FT #@show rad2deg(θᵢ) # Refractive index of air nᵢ = FT(1) # Angle of transmitted light in medium: θₜ = asin(nᵢ * sin(θᵢ)/n) #(sin(α - θₛ)^2 / sin(α + θₛ)^2 + tan(α - θₛ)^2 / tan(α + θₛ)^2)/2 r_perpendicular = (nᵢ * cos(θᵢ) - n * cos(θₜ)) / (nᵢ * cos(θᵢ) + n * cos(θₜ)) r_parallel = (nᵢ * cos(θₜ) - n * cos(θᵢ)) / (nᵢ * cos(θₜ) + n * cos(θᵢ)) return (r_perpendicular^2 + r_parallel^2)/2 end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
233
function gauleg(n::Int, xmin::FT, xmax::FT; norm=false) where FT ξ, w = gausslegendre(n) ξ = (xmax - xmin) / FT(2) * ξ .+ (xmin + xmax) / FT(2) norm ? w /= sum(w) : w *= (xmax - xmin) / FT(2) return FT.(ξ), FT.(w) end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
81
using CanopyOptics using ForwardDiff using Test include("test_CanopyOptics.jl")
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
code
1211
@testset "CanopyOptics" begin @info "Testing spherical leaf G factor calculation ..."; @testset "G function" begin for FT in [Float32, Float64] μ,w = CanopyOptics.gauleg(10,FT(0.0),FT(1.0)); LD = CanopyOptics.spherical_leaves(FT) G = CanopyOptics.G(μ, LD) @test eltype(G) == FT; # Should be about 0.5 for spherical leaves: @test all(abs.(G .- 0.5) .< 0.001) end end @testset "PROSPECT refl and gradient" begin function test_prospect(θ::AbstractVector{T}) where {T} opti = createLeafOpticalStruct((400.0:1.0:2500.0)) leaf = LeafProspectProProperties{T}(Ccab=θ[1], Ccar=θ[2], Canth=θ[3]) _, R = prospect(leaf, opti) return R end refl = test_prospect([40.0, 8.0, 4.0]) @test all(refl .>= 0) @test all(refl .<= 1) jac = ForwardDiff.jacobian(test_prospect, [40.0, 8.0, 4.0]) @test all(isfinite.(jac)) # Increasing pigments decreases reflectance in visible @test all(jac[1:100,:] .<= 0) # ...but has no effect in the SWIR @test all(jac[(end-100):end,:] .== 0) end end
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
docs
754
# CanopyOptics.jl <p align="center"> <a href="https://RemoteSensingTools.github.io/CanopyOptics.jl/dev/"> <img src="https://img.shields.io/badge/docs-latest-blue.svg" alt="Docs"> </a> <a href="https://github.com/RemoteSensingTools/CanopyOptics.jl/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/RemoteSensingTools/CanopyOptics.jl" alt="License"> </a> <a href="https://github.com/RemoteSensingTools/vSmartMOM.jl/commits/master"> <img src="https://img.shields.io/github/commit-activity/y/RemoteSensingTools/CanopyOptics.jl" alt="Github Commit Frequency"> </a> </p> Tools for the computation of canopy optical parameters, see docs for details (works in concert with vSmartMOM.jl)
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
docs
647
# CanopyOptics.jl *A package to compute canopy scattering properties* ## Package Features - Use leaf angle distributions to compute bi-lambertian area scattering matrices - Compute specular reflection - Compute leaf reflectance and transmittance based on Prospect-PRO ## Installation The latest release of CanopyOptics can be installed from the Julia REPL prompt with ```julia julia> ]add https://github.com/RemoteSensingTools/CanopyOptics.jl ``` ## Code docs: ### Types ```@autodocs Modules = [CanopyOptics] Private = false Order = [:type] ``` ### Functions ```@autodocs Modules = [CanopyOptics] Private = false Order = [:function] ```
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.1.3
336f84c4ca016852f0dd7c6bed1b2c7c58e3a1c8
docs
2161
```@meta EditURL = "<unknown>/docs/src/pages/tutorials/bilambertian.jl" ``` ````@example bilambertian push!(LOAD_PATH,"../../../../src/"); nothing #hide ```` # Bilambertian Canopy Scattering Using packages: ````@example bilambertian using Plots, Distributions using CanopyOptics theme(:ggplot2) ```` Compute quadrature points: ````@example bilambertian μ,w = CanopyOptics.gauleg(20,0.0,1.0) ```` Use standard planophile leaf distribution: ````@example bilambertian LD = CanopyOptics.planophile_leaves2() ```` Use a Bilambertian model and specify Reflectance R and Transmission T ````@example bilambertian BiLambMod = CanopyOptics.BiLambertianCanopyScattering(R=0.4,T=0.2) ```` Compute Scattering Matrices 𝐙⁺⁺, 𝐙⁻⁺ for 0th Fourier moment: ````@example bilambertian 𝐙⁺⁺, 𝐙⁻⁺ = CanopyOptics.compute_Z_matrices(BiLambMod, μ, LD, 0) ```` Plots matrices (shows single scattering contributions for incoming and outgoing directions) ````@example bilambertian l = @layout [a b] p1 = contourf(μ, μ, 𝐙⁻⁺, title="Z⁻⁺ (Reflection)", xlabel="μꜜ", ylabel="μꜛ") p2 = contourf(μ, μ, 𝐙⁺⁺, title="Z⁺⁺ (Transmission)", xlabel="μꜛ", ylabel="μꜛ") plot(p1, p2, layout = l, margin=5Plots.mm) plot!(size=(900,350)) ```` ### Animation over different Beta leaf distributions ````@example bilambertian steps = 0.1:0.1:5 α = [collect(steps); 5*ones(length(steps))] β = [ 5*ones(length(steps)); reverse(collect(steps));] x = 0:0.01:1 anim = @animate for i ∈ eachindex(α) LD = CanopyOptics.LeafDistribution(Beta(α[i],β[i]), 2/π) Z⁺⁺, Z⁻⁺ = CanopyOptics.compute_Z_matrices(BiLambMod, μ, LD, 0) l = @layout [a b c] p0 = plot(rad2deg.(π * x/2), pdf.(LD.LD,x), legend=false, ylim=(0,3), title="Leaf angle distribution", xlabel="Θ (degrees)") p1 = contourf(μ, μ, Z⁻⁺, title="Z⁻⁺ (Reflection)", xlabel="μꜜ", ylabel="μꜛ",clims=(0.5,2)) p2 = contourf(μ, μ, Z⁺⁺, title="Z⁺⁺ (Transmission)", xlabel="μꜛ", ylabel="μꜛ",clims=(0.5,2)) plot(p0, p1, p2, layout = l, margin=5Plots.mm) plot!(size=(1100,300)) end gif(anim, "anim_fps10.gif", fps = 10) ```` --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
CanopyOptics
https://github.com/RemoteSensingTools/CanopyOptics.jl.git
[ "MIT" ]
0.2.7
f988004407ccf6c398a87914eafdd8bc9109e533
code
11483
module SliceMap export mapcols, MapCols, maprows, slicemap, tmapcols, ThreadMapCols using JuliennedArrays using Tracker using Tracker: TrackedReal, TrackedMatrix, track, @grad, data using ZygoteRules using ZygoteRules: pullback, @adjoint #========== Reverse, Eachslice ==========# """ mapcols(f, m) ≈ mapreduce(f, hcat, eachcol(m)) ≈ mapslices(f, m, dims=1) This is a more efficient version of the functions on the right. For `f(x::Vector)::Matrix` it reshapes like `mapslices(vec∘f, m, dims=1)`. For `f(x::Vector)::Number` it skips the reduction, just `reshape(map(f, eachcol(m)),1,:)`. It provides a gradient for Tracker and Zygote, saving the backward function for each slice. Any arguments after the matrix are passed to `f` as scalars, i.e. `mapcols(f, m, args...) = reduce(hcat, f(col, args...) for col in eeachcol(m))`. They do not get sliced/iterated (unlike `map`), nor are their gradients tracked. Note that if `f` itself contains parameters, their gradients are also not tracked. """ mapcols(f, M, args...) = _mapcols(map, f, M, args...) tmapcols(f, M, args...) = _mapcols(threadmap, f, M, args...) function _mapcols(map::Function, f, M::AbstractMatrix, args...) res = map(col -> _vec(f(col, args...)), eachcol(M)) eltype(res) <: AbstractVector ? reduce(hcat, res) : reshape(res,1,:) end _vec(x) = x _vec(A::AbstractArray) = vec(A) # to allow f vector -> matrix, by reshaping _mapcols(map::Function, f, M::TrackedMatrix, args...) = track(_mapcols, map, f, M, args...) @grad _mapcols(map::Function, f, M::AbstractMatrix, args...) = ∇mapcols(map, map(col -> Tracker.forward(x -> _vec(f(x, args...)), col), eachcol(data(M))), args...) @adjoint _mapcols(map::Function, f, M::AbstractMatrix, args...) = ∇mapcols(map, map(col -> ZygoteRules.pullback(x -> _vec(f(x, args...)), col), eachcol(M)), args) function ∇mapcols(bigmap, forwards, args...) res = map(data∘first, forwards) function back(Δ) Δcols = eltype(res) <: AbstractVector ? eachcol(data(Δ)) : vec(data(Δ)) cols = bigmap((fwd, Δcol) -> data(last(fwd)(Δcol)[1]), forwards, Δcols) (nothing, nothing, reduce(hcat, cols), map(_->nothing, args)...) end eltype(res) <: AbstractVector ? reduce(hcat, res) : reshape(res,1,:), back end """ maprows(f, M) ≈ mapslices(f, M, dims=2) Like `mapcols()` but for rows. """ function maprows(f::Function, M::AbstractMatrix, args...) res = map(col -> transpose(_vec(f(col, args...))), eachrow(M)) eltype(res) <: AbstractArray ? reduce(vcat, res) : reshape(res,:,1) end maprows(f::Function, M::TrackedMatrix, args...) = track(maprows, f, M, args...) @grad maprows(f::Function, M::AbstractMatrix, args...) = ∇maprows(map(row -> Tracker.forward(x -> _vec(f(x, args...)), row), eachrow(data(M))), args) @adjoint maprows(f::Function, M::AbstractMatrix, args...) = ∇maprows(map(row -> ZygoteRules.pullback(x -> _vec(f(x, args...)), row), eachrow(M)), args) function ∇maprows(forwards, args) res = map(transpose∘data∘first, forwards) function back(Δ) Δrows = eltype(res) <: AbstractArray ? eachrow(data(Δ)) : vec(data(Δ)) rows = map((fwd, Δrow) -> transpose(data(last(fwd)(Δrow)[1])), forwards, Δrows) (nothing, reduce(vcat, rows), map(_->nothing, args)...) end eltype(res) <: AbstractArray ? reduce(vcat, res) : reshape(res,:,1), back end """ slicemap(f, A; dims) ≈ mapslices(f, A; dims) Like `mapcols()`, but for any slice. The function `f` must preserve shape, e.g. if `dims=(2,4)` then `f` must map matrices to matrices. The gradient is for Zygote only. Parameters within the function `f` (if there are any) should be correctly tracked, which is not the case for `mapcols()`. Keyword `rev=true` will apply `f` to `Iterators.reverse(Slices(A,...))`, thus iterating in the opposite order. """ function slicemap(f, A::AbstractArray{T,N}, args...; dims, rev::Bool=false) where {T,N} code = ntuple(d -> d in dims ? True() : False(), N) B = JuliennedArrays.Slices(A, code...) C = if rev==false [ f(slice, args...) for slice in B ] else R = [ f(slice, args...) for slice in iter_reverse(B) ] iter_reverse(R) end JuliennedArrays.Align(C, code...) end iter_reverse(x) = collect(Iterators.reverse(x)) @adjoint iter_reverse(x) = iter_reverse(x), dy -> (iter_reverse(dy),) #========== Forward, Static ==========# using StaticArrays, ForwardDiff struct MapCols{d} end """ MapCols{d}(f, m::Matrix, args...) Similar to `mapcols(f, m, args...)`, but slices `m` into `SVector{d}` columns. Their length `d = size(M,1)` should ideally be provided for type-stability, but is not required. The gradient for Tracker and Zygote uses `ForwardDiff` on each slice. """ MapCols(f::Function, M::AbstractMatrix, args...) = MapCols{size(M,1)}(f, M, args...) MapCols{d}(f::Function, M::AbstractMatrix, args...) where {d} = _MapCols(map, f, M, Val(d), args...) function _MapCols(map::Function, f::Function, M::Matrix{T}, ::Val{d}, args...) where {T,d} d == size(M,1) || error("expected M with $d rows") A = reinterpret(SArray{Tuple{d}, T, 1, d}, vec(M)) B = map(col -> surevec(f(col, args...)), A) reduce(hcat, B) end surevec(A::AbstractArray) = vec(A) surevec(x::Number) = SVector(x) # simple way to deal with f vector -> scalar _MapCols(map::Function, f::Function, M::TrackedMatrix, dval, args...) = track(_MapCols, map, f, M, dval, args...) @grad _MapCols(map::Function, f::Function, M::TrackedMatrix, dval, args...) = ∇MapCols(map, f, M, dval, args...) @adjoint _MapCols(map::Function, f::Function, M::Matrix, dval, args...) = ∇MapCols(map, f, M, dval, args...) function ∇MapCols(bigmap::Function, f::Function, M::AbstractMatrix{T}, dval::Val{d}, args...) where {T,d} d == size(M,1) || error("expected M with $d rows") k = size(M,2) A = reinterpret(SArray{Tuple{d}, T, 1, d}, vec(data(M))) dualcol = SVector(ntuple(j->ForwardDiff.Dual(0, ntuple(i->i==j ? 1 : 0, dval)...), dval)) C = bigmap(col -> surevec(f(col + dualcol, args...)), A) Z = reduce(hcat, map(col -> ForwardDiff.value.(col), C)) function back(ΔZ) S = promote_type(T, eltype(data(ΔZ))) ∇M = zeros(S, size(M)) @inbounds for c=1:k part = ForwardDiff.partials.(C[c]) for r=1:d for i=1:size(ΔZ,1) ∇M[r,c] += data(ΔZ)[i,c] * part[i].values[r] end end end (nothing, nothing, ∇M, nothing, map(_->nothing, args)...) end Z, back end #========== Gradients for Zygote ==========# #= JuliennedArrays =# @adjoint JuliennedArrays.Slices(whole, along...) = JuliennedArrays.Slices(whole, along...), Δ -> (Align(Δ, along...), map(_->nothing, along)...) @adjoint JuliennedArrays.Align(whole, along...) = Align(whole, along...), Δ -> (JuliennedArrays.Slices(Δ, along...), map(_->nothing, along)...) #= Base =# @adjoint Base.reduce(::typeof(hcat), V::AbstractVector{<:AbstractVector}) = reduce(hcat, V), dV -> (nothing, collect(eachcol(dV)),) #========== Experimenting with gradients for for eachslice / reduce ==========# export gluecol, collecteachcol export mapcols2, mapcols4, mapcols5, mapcols6, mapcols7 gluecol(V::AbstractVector{<:AbstractVector}) = reduce(hcat, V) #= gluecol(V::AbstractVector{<:TrackedVector}) = track(gluecol, V) @grad function gluecol(V::AbstractVector) gluecol(data.(V)), ΔM -> (collect(eachcol(data(ΔM))),) # doesn't work end =# @adjoint gluecol(V::AbstractVector) = gluecol(V), ΔM -> (collect(eachcol(ΔM)),) # does work! function mapcols2(f, A) cols = [A[:,c] for c=1:size(A,2)] res = f.(cols) gluecol(res) end # Apply that straight to reduce(hcat,...) function mapcols4(f, A) cols = [view(A,:,c) for c=1:size(A,2)] res = map(f, cols) reduce(hcat, res) end # Surprisingly dy for eachcol seems to know the answer? # typeof(dy) = NamedTuple{(:f, :iter),Tuple{NamedTuple{(:A,),Tuple{Array{Float64,2}}},Array{Nothing,1}}} # dy = (f = (A = [47.9325 51.3781 # Which means this works... but uses as much memory as gradient of array of views: #=@adjoint function eachcol(x::AbstractMatrix) eachcol(x), dy -> (dy.f.A,) #= begin @show typeof(dy) dy dx = zero(x) .+ 0.0 # zeros(eltype(dy), size(x)) foreach(copyto!, eachcol(dx), dy) (dx,) end =# end=# # @adjoint eachcol(x) = eachcol(x), dy -> (dy.f.A,) function mapcols5(f, A) cols = collect(eachcol(A)) res = map(f, cols) reduce(hcat, res) end collecteachcol(x) = collect(eachcol(x)) @adjoint function collecteachcol(x) collecteachcol(x), dy -> begin dx = _zero(x) # _zero is not in ZygoteRules, TODO foreach(copyto!, collecteachcol(dx), dy) (dx,) end end function mapcols6(f, A) cols = collecteachcol(A) res = map(f, cols) reduce(hcat, res) end # function mapcols7(f, A) # cols = eachcol(A) # without collect. Zygote.gradient -> StackOverflowError # res = map(f, cols) # reduce(hcat, res) # end # Following a suggestion? Doesn't help. # @adjoint Base.collect(x) = collect(x), Δ -> (Δ,) #========== Threaded Map ==========# # What KissThreading does is much more complicated, perhaps worth investigating: # https://github.com/mohamed82008/KissThreading.jl/blob/master/src/KissThreading.jl # BTW I do the first one because some diffeq maps infer to ::Any, # else you could use Core.Compiler.return_type(f, Tuple{eltype(x)}) """ threadmap(f, A) threadmap(f, A, B) Simple version of `map` using a `Threads.@threads` loop, or `Threads.@spawn` on Julia >= 1.3. Only for vectors & really at most two of them, of nonzero length, with all outputs having the same type. """ function threadmap(f::Function, vw::AbstractVector...) length(first(vw))==0 && error("can't map over empty vector, sorry") length(vw)==2 && (isequal(length.(vw)...) || error("lengths must be equal")) out1 = f(first.(vw)...) if length(first(vw)) > 1 _threadmap(out1, f, vw...) else [out1] end end # NB function barrier. Plus two versions: @static if VERSION < v"1.3" function _threadmap(out1, f, vw...) out = Vector{typeof(out1)}(undef, length(first(vw))) out[1] = out1 Threads.@threads for i in 2:length(first(vw)) @inbounds out[i] = f(getindex.(vw, i)...) end out end else function _threadmap(out1, f, vw...) ell = length(first(vw)) out = Vector{typeof(out1)}(undef, ell) out[1] = out1 Base.@sync for is in Iterators.partition(2:ell, cld(ell-1, Threads.nthreads())) Threads.@spawn for i in is @inbounds out[i] = f(getindex.(vw, i)...) end end out end end # Collect generators to allow indexing threadmap(f::Function, v) = threadmap(f, collect(v)) threadmap(f::Function, v, w) = threadmap(f, collect(v), collect(w)) threadmap(f::Function, v, w::AbstractVector) = threadmap(f, collect(v), w) threadmap(f::Function, v::AbstractVector, w) = threadmap(f, v, collect(w)) struct ThreadMapCols{d} end """ ThreadMapCols{d}(f, m::Matrix, args...) Like `MapCols` but with multi-threading! """ ThreadMapCols(f::Function, M::AbstractMatrix, args...) = ThreadMapCols{size(M,1)}(f, M, args...) ThreadMapCols{d}(f::Function, M::AbstractMatrix, args...) where {d} = _MapCols(threadmap, f, M, Val(d), args...) end # module
SliceMap
https://github.com/mcabbott/SliceMap.jl.git
[ "MIT" ]
0.2.7
f988004407ccf6c398a87914eafdd8bc9109e533
code
6965
using SliceMap using Test using ForwardDiff, Tracker, Zygote, JuliennedArrays Zygote.refresh() @testset "columns" begin mat = rand(1:9, 3,10) fun(x) = 2 .+ x.^2 res = mapslices(fun, mat, dims=1) @test res ≈ mapcols(fun, mat) @test res ≈ MapCols{3}(fun, mat) @test res ≈ MapCols(fun, mat) @test res ≈ tmapcols(fun, mat) @test res ≈ ThreadMapCols{3}(fun, mat) @test res ≈ ThreadMapCols(fun, mat) grad = ForwardDiff.gradient(m -> sum(sin, mapslices(fun, m, dims=1)), mat) @test grad ≈ Tracker.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, MapCols(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, tmapcols(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, ThreadMapCols{3}(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, ThreadMapCols(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, tmapcols(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, ThreadMapCols{3}(fun, m)), mat)[1] jcols(f,m) = Align(map(f, JuliennedArrays.Slices(m, True(), False())), True(), False()) @test res ≈ jcols(fun, mat) @test grad ≈ Zygote.gradient(m -> sum(sin, jcols(fun, m)), mat)[1] # Case of length 1, was an error for _threadmap @test res[:,1:1] ≈ mapcols(fun, mat[:, 1:1]) @test res[:,1:1] ≈ tmapcols(fun, mat[:, 1:1]) @test res[:,1:1] ≈ ThreadMapCols(fun, mat[:, 1:1]) end @testset "columns -> scalar" begin mat = rand(1:9, 3,10) fun(x) = sum(x) # different function! res = mapslices(fun, mat, dims=1) @test res ≈ mapcols(fun, mat) @test res ≈ MapCols{3}(fun, mat) grad = ForwardDiff.gradient(m -> sum(sin, mapslices(fun, m, dims=1)), mat) @test grad ≈ Tracker.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] end @testset "columns -> matrix" begin mat = rand(1:9, 3,10) fun(x) = x .* x' # different function! vector -> matrix res = mapslices(vec∘fun, mat, dims=1) @test res ≈ mapcols(fun, mat) @test res ≈ MapCols{3}(fun, mat) grad = ForwardDiff.gradient(m -> sum(sin, mapslices(vec∘fun, m, dims=1)), mat) @test grad ≈ Tracker.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] end @testset "columns w args" begin mat = randn(Float32, 3,10) fun(x, s) = 1 .+ x .* s res = mapslices(x -> vec(fun(x,5)), mat, dims=1) @test res ≈ mapcols(fun, mat, 5) @test res ≈ MapCols{3}(fun, mat, 5) grad = ForwardDiff.gradient(m -> sum(sin, mapslices(x -> vec(fun(x,5)), m, dims=1)), mat) @test grad ≈ Tracker.gradient(m -> sum(sin, mapcols(fun, m, 5)), mat)[1] @test grad ≈ Tracker.gradient(m -> sum(sin, MapCols{3}(fun, m, 5)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, mapcols(fun, m, 5)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, MapCols{3}(fun, m, 5)), mat)[1] end @testset "rows" begin mat = randn(4,5) fun(x) = 2 .+ x.^2 ./ sum(x) res = mapslices(fun, mat, dims=2) @test res ≈ maprows(fun, mat) grad = ForwardDiff.gradient(m -> sum(sin, mapslices(fun, m, dims=2)), mat) @test grad ≈ Tracker.gradient(m -> sum(sin, maprows(fun, m)), mat)[1] @test grad ≈ Zygote.gradient(m -> sum(sin, maprows(fun, m)), mat)[1] jrows(f,m) = Align(map(f, JuliennedArrays.Slices(m, False(), True())), False(), True()) @test res ≈ jrows(fun, mat) @test grad ≈ Zygote.gradient(m -> sum(sin, jrows(fun, m)), mat)[1] end @testset "slices of a 4-tensor" begin ten = randn(3,4,5,2) fun(x::AbstractVector) = sqrt(3) .+ x.^3 ./ (sum(x)^2) res = mapslices(fun, ten, dims=3) @test res ≈ slicemap(fun, ten, dims=3) grad = ForwardDiff.gradient(x -> sum(sin, slicemap(fun, x, dims=3)), ten) @test grad ≈ Zygote.gradient(x -> sum(sin, slicemap(fun, x, dims=3)), ten)[1] jthree(f,m) = Align(map(f, JuliennedArrays.Slices(m, False(), False(), True(), False()) ), False(), False(), True(), False()) @test res ≈ jthree(fun, ten) @test grad ≈ Zygote.gradient(m -> sum(sin, jthree(fun, m)), ten)[1] j3(f,m) = Align(map(f, JuliennedArrays.Slices(m, 3)), 3) @test res ≈ j3(fun, ten) @test grad ≈ Zygote.gradient(m -> sum(sin, j3(fun, m)), ten)[1] end @testset "gradient of the function" begin struct F W end (f::F)(x) = f.W * x # toy version of e.g. Flux.Dense w = rand(3,2) x = rand(2,5) gradx = ForwardDiff.gradient(x -> sum(mapslices(F(w), x, dims=1)), x) gradw = ForwardDiff.gradient(w -> sum(mapslices(F(w), x, dims=1)), w) wp = Tracker.param(w) xp = Tracker.param(x) Tracker.back!(sum(mapcols(F(wp), xp))) @test Tracker.grad(xp) ≈ gradx @test Tracker.grad(wp) == 0 .* gradw # bug or a feature? # fp = F(wp) # wp.grad .= 0; xp.grad .= 0; # Tracker.back!(sum(mapcols(fp, xp))) # @test Tracker.grad(xp) ≈ gradx # @test_broken Tracker.grad(wp) ≈ gradw # zero f = F(w) grad_mapcols = Zygote.gradient(() -> sum(mapcols(f, x)), Zygote.Params([w,x])) @test grad_mapcols[x] ≈ gradx @test grad_mapcols[w] == nothing # bug or a feature? grad_slicemap = Zygote.gradient(() -> sum(slicemap(f, x, dims=1)), Zygote.Params([w,x])) @test grad_slicemap[x] ≈ gradx @test grad_slicemap[w] ≈ gradw @test gradw ≈ Zygote.gradient(w -> sum(slicemap(F(w), x, dims=1)), w)[1] # Using F(w) with Params() gives wrong answers: # https://github.com/FluxML/Zygote.jl/issues/522#issuecomment-605935652 end @testset "slicemap rev=true" begin rec(store) = x -> (push!(store, first(x)); x) A = [1,1,1] .* (1:5)' store = [] slicemap(rec(store), A; dims=1) @test store == 1:5 store = [] slicemap(rec(store), A; dims=1, rev=true) @test store == 5:-1:1 # gradient check as above ten = randn(3,4,5,2) fun(x::AbstractVector) = sqrt(3) .+ x.^3 ./ (sum(x)^2) res = mapslices(fun, ten, dims=3) @test res ≈ slicemap(fun, ten; dims=3, rev=true) @test res ≈ slicemap(fun, ten; dims=3, rev=false) grad = ForwardDiff.gradient(x -> sum(sin, mapslices(fun, x, dims=3)), ten) @test grad ≈ Zygote.gradient(x -> sum(sin, slicemap(fun, x, dims=3, rev=false)), ten)[1] @test grad ≈ Zygote.gradient(x -> sum(sin, slicemap(fun, x, dims=3, rev=true)), ten)[1] end
SliceMap
https://github.com/mcabbott/SliceMap.jl.git
[ "MIT" ]
0.2.7
f988004407ccf6c398a87914eafdd8bc9109e533
docs
1469
# SliceMap.jl [![Build Status](https://github.com/mcabbott/SliceMap.jl/workflows/CI/badge.svg)](https://github.com/mcabbott/SliceMap.jl/actions?query=workflow%3ACI) This package provides some `mapslices`-like functions, with gradients defined for [Tracker](https://github.com/FluxML/Tracker.jl) and [Zygote](https://github.com/FluxML/Zygote.jl): ```julia mapcols(f, M) ≈ mapreduce(f, hcat, eachcol(M)) MapCols{d}(f, M) # where d=size(M,1), for SVector slices ThreadMapCols{d}(f, M) # using Threads.@threads maprows(f, M) ≈ mapslices(f, M, dims=2) slicemap(f, A; dims) ≈ mapslices(f, A, dims=dims) # only Zygote ``` The capitalised functions differ both in using [StaticArrays](https://github.com/JuliaArrays/StaticArrays.jl) slices, and using [ForwardDiff](https://github.com/JuliaDiff/ForwardDiff.jl) for the gradient of each slice, instead of the same reverse-mode Tracker/Zygote. For small slices, this will often be much faster, with or without gradients. The package also defines Zygote gradients for the Slice/Align functions in [JuliennedArrays](https://github.com/bramtayl/JuliennedArrays.jl), which is a good way to roll-your-own `mapslices`-like thing (and is exactly how `slicemap(f, A; dims)` works). Similar gradients are also available in [TensorCast](https://github.com/mcabbott/TensorCast.jl), and in [LazyStack](https://github.com/mcabbott/LazyStack.jl). There are more details & examples at [docs/intro.md](docs/intro.md).
SliceMap
https://github.com/mcabbott/SliceMap.jl.git
[ "MIT" ]
0.2.7
f988004407ccf6c398a87914eafdd8bc9109e533
docs
5769
# SliceMap.jl Some examples & benchmarks. Times shown were on Julia 1.2 I think, and some have improved quite a bit since. ## Simple example ```julia mat = rand(1:9, 3,10) fun(x) = 2 .+ x.^2 mapslices(fun, mat, dims=1) using SliceMap mapcols(fun, mat) # eachcol(m) MapCols{3}(fun, mat) # reinterpret(SArray,...) using ForwardDiff, Tracker, Zygote ForwardDiff.gradient(m -> sum(sin, mapslices(fun, m, dims=1)), mat) Tracker.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] # Tracker.forward per slice Tracker.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] # ForwardDiff on slices Zygote.gradient(m -> sum(sin, mapcols(fun, m)), mat)[1] # Zygote.forward per slice Zygote.gradient(m -> sum(sin, MapCols{3}(fun, m)), mat)[1] ``` These are a bit faster than `mapslices` too. Although storing all the backward functions, which is what `mapcols` does, has some overhead: ```julia using BenchmarkTools mat1k = rand(3,1000); @btime mapreduce(fun, hcat, eachcol($mat1k)) # 1.522 ms, 11.80 MiB @btime mapslices(fun, $mat1k, dims=1) # 1.017 ms, 329.92 KiB @btime mapcols(fun, $mat1k) # 399.016 μs, 219.02 KiB @btime MapCols{3}(fun, $mat1k) # 15.564 μs, 47.16 KiB @btime MapCols(fun, $mat1k) # 16.774 μs (without slice size) @btime ForwardDiff.gradient(m -> sum(mapslices(fun, m, dims=1)), $mat1k); # 329.305 ms @btime Tracker.gradient(m -> sum(mapcols(fun, m)), $mat1k); # 70.203 ms @btime Tracker.gradient(m -> sum(MapCols{3}(fun, m)), $mat1k); # 51.129 μs, 282.92 KiB @btime Zygote.gradient(m -> sum(mapcols(fun, m)), $mat1k); # 20.454 ms, 3.52 MiB @btime Zygote.gradient(m -> sum(MapCols{3}(fun, m)), $mat1k); # 28.229 μs, 164.63 KiB ``` On recent versions of Julia, `mapcols` has become much faster, 5-10 times. FWIW, times on Julia 1.8-dev & and M1 mac, June 2021: ``` @btime mapreduce(fun, hcat, eachcol($mat1k)) # 616.250 μs (2317 allocations: 11.69 MiB) @btime mapslices(fun, $mat1k, dims=1) # 230.250 μs (7499 allocations: 298.23 KiB) @btime mapcols(fun, $mat1k) # 26.750 μs (1003 allocations: 140.83 KiB) @btime MapCols{3}(fun, $mat1k) # 6.067 μs (9 allocations: 47.20 KiB) @btime MapCols(fun, $mat1k) # 6.217 μs (9 allocations: 47.20 KiB) @btime ForwardDiff.gradient(m -> sum(mapslices(fun, m, dims=1)), $mat1k); # 70.815 ms (1877210 allocations: 210.64 MiB) @btime Tracker.gradient(m -> sum(mapcols(fun, m)), $mat1k); # 29.840 ms (598046 allocations: 26.20 MiB) @btime Tracker.gradient(m -> sum(MapCols{3}(fun, m)), $mat1k); # 25.833 μs (60 allocations: 283.23 KiB) julia> @btime Zygote.gradient(m -> sum(mapcols(fun, m)), $mat1k); # 93.750 μs (4047 allocations: 392.14 KiB) julia> @btime Zygote.gradient(m -> sum(MapCols{3}(fun, m)), $mat1k); # 14.834 μs (18 allocations: 164.73 KiB) ``` ## Other packages This package also provides Zygote gradients for the Slice/Align functions in [JuliennedArrays](https://github.com/bramtayl/JuliennedArrays.jl), which can be used to write many mapslices-like operations: ```julia using JuliennedArrays jumap(f,m) = Align(map(f, Slices(m, True(), False())), True(), False()) jumap1(f,m) = Align(map(f, Slices(m, 1)), 1) jumap(fun, mat) # same as mapcols jumap1(fun, mat) Zygote.gradient(m -> sum(sin, jumap(fun, m)), mat)[1] @btime jumap(fun, $mat1k); # 44.823 μs @btime jumap1(fun, $mat1k); # 11.805 μs, really? @btime Zygote.gradient(m -> sum(jumap(fun, m)), $mat1k); # 26.110 ms @btime Zygote.gradient(m -> sum(jumap1(fun, m)), $mat1k) # 412.904 μs, really? ``` Similar gradients also moved to [TensorCast](https://github.com/mcabbott/TensorCast.jl): ```julia using TensorCast @cast [i,j] := fun(mat[:,j])[i] # same as mapcols tcm(mat) = @cast out[i,j] := fun(mat[:,j])[i] Zygote.gradient(m -> sum(sin, tcm(m)), mat)[1] @btime tcm($mat1k) # 427.907 μs @btime Zygote.gradient(m -> sum(tcm(m)), $mat1k); # 18.358 ms ``` The original purpose of `MapCols`, with ForwardDiff on slices, was that this works well when the function being mapped integrates some differential equation. ```julia using DifferentialEquations, ParameterizedFunctions ode = @ode_def begin du = ( - k2 * u )/(k1 + u) # an equation with 2 parameters end k1 k2 function g(k::AbstractVector{T}, times) where T u0 = T[ 1.0 ] # NB convert initial values to eltype(k) prob = ODEProblem(ode, u0, (0.0, 0.0+maximum(times)), k) Array(solve(prob, saveat=times))::Matrix{T} end kay = rand(2,50); MapCols{2}(g, kay, 1:5) # 5 time steps, for each col of parameters Tracker.gradient(k -> sum(sin, MapCols{2}(g, k, 1:5)), kay)[1] ``` This is quite efficient, and seems to go well with multi-threading: ```julia @btime MapCols{2}(g, $kay, 1:5) # 1.394 ms @btime ThreadMapCols{2}(g, $kay, 1:5) # 697.333 μs @btime Tracker.gradient(k -> sum(MapCols{2}(g, k, 1:5)), $kay)[1] # 2.561 ms @btime Tracker.gradient(k -> sum(ThreadMapCols{2}(g, k, 1:5)), $kay)[1] # 1.344 ms Threads.nthreads() == 4 # on my 2/4-core laptop ``` ## Elsewhere Issues about mapslices: * https://github.com/FluxML/Zygote.jl/issues/92 * https://github.com/FluxML/Flux.jl/issues/741 * https://github.com/JuliaLang/julia/issues/29146 Differential equations: * https://arxiv.org/abs/1812.01892 "DSAAD" * http://docs.juliadiffeq.org/latest/analysis/sensitivity.html Other packages which define gradients of possible interest: * https://github.com/GiggleLiu/LinalgBackwards.jl * https://github.com/mcabbott/ArrayAllez.jl
SliceMap
https://github.com/mcabbott/SliceMap.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
910
using DockerSandbox using Documenter DocMeta.setdocmeta!(DockerSandbox, :DocTestSetup, :(using DockerSandbox); recursive=true) makedocs(; modules=[DockerSandbox], authors="Keno Fischer, Dilum Aluthge, and contributors", repo="https://github.com/JuliaContainerization/DockerSandbox.jl/blob/{commit}{path}#{line}", sitename="DockerSandbox.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://JuliaContainerization.github.io/DockerSandbox.jl", assets=String[], ), pages=[ "Home" => "index.md", "Prerequisites" => "prerequisites.md", "Examples" => "examples.md", "Public API" => "public.md", "Internals (Private)" => "internals.md", ], strict=true, ) deploydocs(; repo="github.com/JuliaContainerization/DockerSandbox.jl", )
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
236
module DockerSandbox import Base: run, success import Random export DockerConfig export run export success export with_container include("types.jl") include("base.jl") include("container.jl") include("convenience.jl") end # module
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
802
for f in (:run, :success) @eval begin """ $($f)(container::DockerContainer, config::DockerConfig, user_cmd::Cmd; kwargs...) """ function $f(container::DockerContainer, config::DockerConfig, cmd::Cmd; kwargs...) container_cmd = construct_container_command( container, config, cmd, ) docker_cmd = pipeline( container_cmd; config.stdin, config.stdout, config.stderr, ) if config.verbose @info("Running sandboxed command", cmd.exec) end return $f(docker_cmd; kwargs...) end end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
6007
""" docker_image_label(container::DockerContainer) """ function docker_image_label(container::DockerContainer) return string("org.julialang.docker.jl=", container.label) end function _assert_no_nonword_characters(str::String) isascii(str) || throw(ArgumentError("String is not an ASCII string")) occursin(r"^[A-Za-z0-9_]*?$", str) || throw(ArgumentError("String contains one or more nonword characters")) return nothing end function _replace_nonword_character(char::Char) if occursin(r"^\w$", string(char)) return char else return '_' end end function _replace_all_nonword_characters(str::String) isascii(str) || throw(ArgumentError("String is not an ASCII string")) old_chars = collect(str) new_chars = _replace_nonword_character.(old_chars) new_str = join(new_chars) _assert_no_nonword_characters(new_str) return new_str end """ docker_image_name(image::String) """ function docker_image_name(image::String) docker_image = string( "julialang_dockerjl:", _replace_all_nonword_characters(image), "_", string(Base._crc32c(image), base=16), ) return docker_image end """ cleanup(container::DockerContainer) """ function cleanup(container::DockerContainer) label = docker_image_label(container) success(`docker system prune --force --filter=label=$(label)`) return nothing end function _generate_dockerfile(config::DockerConfig) if config.platform === :linux return """ FROM --platform=linux $(config.base_image) RUN usermod --lock root RUN groupadd --system myuser RUN useradd --create-home --shell /bin/bash --system --gid myuser myuser USER myuser """ else msg = "Invalid value for config.platform: $(config.platform)" throw(ArgumentError(msg)) end end """ build_docker_image(config::DockerConfig) """ function build_docker_image(config::DockerConfig) docker_image = docker_image_name(config.base_image) mktempdir() do tmp_dir cd(tmp_dir) do rm("Dockerfile"; force = true, recursive = true) dockerfile = _generate_dockerfile(config) open("Dockerfile", "w") do io println(io, strip(dockerfile)) end if config.docker_build_stdout === nothing if config.verbose docker_build_stdout = Base.stdout else docker_build_stdout = Base.devnull end else docker_build_stdout = config.docker_build_stdout end if config.docker_build_stderr === nothing if config.verbose docker_build_stderr = Base.stderr else docker_build_stderr = Base.devnull end else docker_build_stderr = config.docker_build_stderr end (docker_build_stdout isa IO) || throw(ArgumentError("docker_build_stdout must be an IO")) (docker_build_stderr isa IO) || throw(ArgumentError("docker_build_stderr must be an IO")) run( pipeline( `docker build -t $(docker_image) .`; stdin = Base.devnull, stdout = docker_build_stdout, stderr = docker_build_stderr, ) ) end end return docker_image end """ construct_container_command(container::DockerContainer, config::DockerConfig, cmd::Cmd) """ function construct_container_command(container::DockerContainer, config::DockerConfig, cmd::Cmd) build_docker_image(config) container_cmd_string = String["docker", "run"] append!(container_cmd_string, ["--security-opt=no-new-privileges"]) # disable container processes from gaining new privileges append!(container_cmd_string, ["--cap-drop=all"]) # drop all capabilities if config.add_capabilities !== nothing for cap in config.add_capabilities append!(container_cmd_string, ["--cap-add=$(cap)"]) end end append!(container_cmd_string, ["--interactive"]) # keep STDIN open even if not attached append!(container_cmd_string, ["--label", docker_image_label(container)]) # set metadata append!(container_cmd_string, ["--rm=true"]) # automatically remove the container when it exits # If we're doing a fully-interactive session, tell it to allocate a psuedo-TTY is_interactive = all( isa.( (config.stdin, config.stdout, config.stderr), Base.TTY, ) ) is_interactive && append!(container_cmd_string, ["-t"]) # Start in the right directory append!(container_cmd_string, ["--workdir=/home/myuser"]) # Add in read-only mappings if config.read_only_maps !== nothing for (dst, src) in pairs(config.read_only_maps) if dst == "/" throw(ArgumentError("Cannot provide a mapping for /")) else append!(container_cmd_string, ["-v", "$(src):$(dst):ro"]) end end end # Add in read-write mappings if config.read_write_maps !== nothing for (dst, src) in pairs(config.read_write_maps) if dst == "/" throw(ArgumentError("Cannot provide a mapping for /")) else append!(container_cmd_string, ["-v", "$(src):$(dst)"]) end end end # Apply environment mappings from `config` if config.env !== nothing for (k, v) in pairs(config.env) append!(container_cmd_string, ["-e", "$(k)=$(v)"]) end end append!(container_cmd_string, [docker_image_name(config.base_image)]) append!(container_cmd_string, cmd.exec) container_cmd = Cmd(container_cmd_string) return container_cmd end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
376
""" with_container(f::Function, ::Type{<:DockerContainer} = DockerContainer; kwargs...) """ function with_container(f::F, ::Type{T} = DockerContainer; kwargs...) where {F <: Function, T <: DockerContainer} container = T(; kwargs...) try return f(container) finally cleanup(container) end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
1337
""" DockerContainer() """ Base.@kwdef struct DockerContainer label::String = Random.randstring(10) end """ DockerConfig(; kwargs...) ## Required Keyword Arguments: - `base_image::String` ## Optional Keyword Arguments: - `verbose::Bool = false` - `env::Union{Dict{String, String}, Nothing} = nothing` - `platform::Symbol = :linux` - `read_only_maps::Union{Dict{String, String}, Nothing} = nothing` - `read_write_maps::Union{Dict{String, String}, Nothing} = nothing` - `stdin::IO = Base.devnull` - `stdout::IO = Base.stdout` - `stderr::IO = Base.stderr` - `docker_build_stdout::Union{IO, Nothing} = nothing` - `docker_build_stderr::Union{IO, Nothing} = nothing` - `add_capabilities::Union{Vector{String}, Nothing} = nothing` """ Base.@kwdef struct DockerConfig # Required base_image::String # Optional verbose::Bool = false env::Union{Dict{String, String}, Nothing} = nothing platform::Symbol = :linux read_only_maps::Union{Dict{String, String}, Nothing} = nothing read_write_maps::Union{Dict{String, String}, Nothing} = nothing stdin::IO = Base.devnull stdout::IO = Base.stdout stderr::IO = Base.stderr docker_build_stdout::Union{IO, Nothing} = nothing docker_build_stderr::Union{IO, Nothing} = nothing add_capabilities::Union{Vector{String}, Nothing} = nothing end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
324
@testset "add capabilities" begin config = DockerConfig(; base_image = "julia:latest", add_capabilities = ["CAP_CHOWN"], ) with_container() do container code = """ println("This was a success.") """ @test success(container, config, `julia -e $(code)`) end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
89
@testset "Test that Docker is installed" begin @test success(`docker --version`) end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
652
@testset "environment variables" begin config = DockerConfig(; base_image = "julia:latest", env = Dict{String, String}("MY_ENVIRONMENT_VARIABLE" => "hello_world") ) with_container() do container code = """ println("This was a success.") if !haskey(ENV, "MY_ENVIRONMENT_VARIABLE") throw(ErrorException("environment variable does not exist")) end if ENV["MY_ENVIRONMENT_VARIABLE"] != "hello_world" throw(ErrorException("environment variable has the wrong value")) end """ @test success(container, config, `julia -e $(code)`) end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
862
@testset "Errors" begin @testset begin config = DockerConfig(; base_image = "foo", platform = :foo) mktempdir() do build_directory @test_throws ArgumentError DockerSandbox._generate_dockerfile(config) end end @testset begin configs = [ DockerConfig(; base_image = "julia:latest", read_only_maps = Dict("/" => "/foo"), ), DockerConfig(; base_image = "julia:latest", read_write_maps = Dict("/" => "/foo"), ), ] for config in configs with_container() do container code = """ println("123") """ @test_throws ArgumentError run(container, config, `julia -e $(code)`) end end end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
757
@testset "Ensure that there are no non-stdlib dependencies" begin package_directories = String[ dirname(dirname(pathof(DockerSandbox))), dirname(@__DIR__), dirname(dirname(@__FILE__)), ] for package_directory in package_directories package_project_filename = joinpath(package_directory, "Project.toml") predictmd_project = TOML.parsefile(package_project_filename) predictmd_direct_deps = predictmd_project["deps"] for (name, uuid) in pairs(predictmd_direct_deps) is_stdlib = Pkg.Types.is_stdlib(Base.UUID(uuid)) if !is_stdlib @error("There is a non-stdlib dependency", name, uuid) end @test is_stdlib end end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
1117
@testset "read-only maps" begin mktempdir() do tmpdir_ro open(joinpath(tmpdir_ro, "myroinputfile"), "w") do io println(io, "Hello RO world!") end x1 = read(joinpath(tmpdir_ro, "myroinputfile"), String) @test x1 == "Hello RO world!\n" config = DockerConfig(; base_image = "julia:latest", read_only_maps = Dict( "/home/myuser/workdir_ro" => tmpdir_ro, ), ) Utils.make_world_readable_recursively(tmpdir_ro) with_container() do container code = """ y1 = read("/home/myuser/workdir_ro/myroinputfile", String) if y1 != "Hello RO world!\n" throw(ErrorException("File contents did not match")) end mktempdir() do tmpdir open(joinpath(tmpdir, "sometemporaryfile"), "w") do io println(io, "I wrote this file into a temporary directory.") end end """ @test success(container, config, `julia -e $(code)`) end end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
2909
@testset "read-write maps" begin mktempdir() do tmpdir_ro mktempdir() do tmpdir_rw open(joinpath(tmpdir_ro, "myroinputfile"), "w") do io println(io, "Hello RO world!") end open(joinpath(tmpdir_rw, "myrwinputfile"), "w") do io println(io, "Hello RW world!") end x1 = read(joinpath(tmpdir_ro, "myroinputfile"), String) x2 = read(joinpath(tmpdir_rw, "myrwinputfile"), String) @test x1 == "Hello RO world!\n" @test x2 == "Hello RW world!\n" @test !ispath(joinpath(tmpdir_rw, "myrwoutputfile")) @test !isfile(joinpath(tmpdir_rw, "myrwoutputfile")) config = DockerConfig(; base_image = "julia:latest", read_only_maps = Dict( "/home/myuser/workdir_ro" => tmpdir_ro, ), read_write_maps = Dict( "/home/myuser/workdir_rw" => tmpdir_rw, ), ) Utils.make_world_readable_recursively(tmpdir_ro) Utils.make_world_writeable_recursively(tmpdir_rw) with_container() do container code = """ y1 = read("/home/myuser/workdir_ro/myroinputfile", String) y2 = read("/home/myuser/workdir_rw/myrwinputfile", String) if y1 != "Hello RO world!\n" throw(ErrorException("File contents did not match")) end if y2 != "Hello RW world!\n" throw(ErrorException("File contents did not match")) end if ispath("/home/myuser/workdir_rw/myrwoutputfile") throw(ErrorException("The file exists, but it should not exist")) end if isfile("/home/myuser/workdir_rw/myrwoutputfile") throw(ErrorException("The file exists, but it should not exist")) end open("/home/myuser/workdir_rw/myrwoutputfile", "w") do io println(io, "I created and wrote this file inside the container.") end chmod("/home/myuser/workdir_rw/myrwoutputfile", 0o666) mktempdir() do tmpdir open(joinpath(tmpdir, "sometemporaryfile"), "w") do io println(io, "I wrote this file into a temporary directory.") end end """ @test success(container, config, `julia -e $(code)`) end @test ispath(joinpath(tmpdir_rw, "myrwoutputfile")) @test isfile(joinpath(tmpdir_rw, "myrwoutputfile")) z1 = read(joinpath(tmpdir_rw, "myrwoutputfile"), String) @test z1 == "I created and wrote this file inside the container.\n" end end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
320
using DockerSandbox using Test import Pkg import TOML include("utils.jl") include("no_nonstdlib_deps.jl") include("docker_is_installed.jl") include("add_capabilities.jl") include("environment_variables.jl") include("errors.jl") include("read_only_maps.jl") include("read_write_maps.jl") include("with_container.jl")
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
1214
module Utils """ apply_chmod_recursively(root_dir::String; dir_mode::Integer, file_mode::Integer) """ function apply_chmod_recursively(root_dir::String; dir_mode::Integer, file_mode::Integer) chmod(root_dir, dir_mode) for (root, dirs, files) in walkdir(root_dir) for dir in dirs full_dir_path = joinpath(root, dir) isdir(full_dir_path) || throw(ArgumentError("unexpected error")) chmod(full_dir_path, dir_mode) end for file in files full_file_path = joinpath(root, file) isfile(full_file_path) || throw(ArgumentError("unexpected error")) chmod(full_file_path, file_mode) end end return nothing end """ make_world_readable_recursively(root_dir::String) """ function make_world_readable_recursively(root_dir::String) return apply_chmod_recursively(root_dir; dir_mode=0o555, file_mode=0o444) end """ make_world_writeable_recursively(root_dir::String) """ function make_world_writeable_recursively(root_dir::String) return apply_chmod_recursively(root_dir; dir_mode=0o777, file_mode=0o666) end end # module
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
code
1367
@testset "with_container()" begin configs = [ DockerConfig(; base_image = "julia:latest", verbose = true), DockerConfig(; base_image = "julia:latest", verbose = false), DockerConfig(; base_image = "julia:latest", verbose = true, docker_build_stdout = Base.devnull, docker_build_stderr = Base.devnull, ), ] for config in configs with_container() do container code = """ println("This was a success.") """ @test success(container, config, `julia -e $(code)`) end with_container() do container code = """ throw(ErrorException("This was a failure.")) """ @test !success(container, config, `julia -e $(code)`) end with_container() do container code = """ println("This was a success.") """ p = run(container, config, `julia -e $(code)`; wait = false) wait(p) @test success(p) end with_container() do container code = """ throw(ErrorException("This was a failure.")) """ p = run(container, config, `julia -e $(code)`; wait = false) wait(p) @test !success(p) end end end
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
docs
1104
# DockerSandbox.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaContainerization.github.io/DockerSandbox.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaContainerization.github.io/DockerSandbox.jl/dev) [![Coverage](https://codecov.io/gh/JuliaContainerization/DockerSandbox.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaContainerization/DockerSandbox.jl) | Julia | CI | | ------- | -- | | v1 | [![CI](https://github.com/JuliaContainerization/DockerSandbox.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/JuliaContainerization/DockerSandbox.jl/actions/workflows/ci.yml) | | nightly | [![CI (Julia nightly)](https://github.com/JuliaContainerization/DockerSandbox.jl/actions/workflows/ci_julia_nightly.yml/badge.svg)](https://github.com/JuliaContainerization/DockerSandbox.jl/actions/workflows/ci_julia_nightly.yml) | DockerSandbox.jl is a package for running Julia `Cmd` objects inside of Docker containers. Please see the [documentation](https://JuliaContainerization.github.io/DockerSandbox.jl/stable).
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
docs
613
```@meta CurrentModule = DockerSandbox ``` # Examples ## Simple Example ```@example using DockerSandbox config = DockerConfig(; base_image = "julia:latest"); with_container() do container code = """ println("Hello world!") """ run(container, config, `julia -e $(code)`) end ``` ## Interactive Example ```julia julia> using DockerSandbox julia> config = DockerConfig(; base_image = "julia:latest", Base.stdin, Base.stdout, Base.stderr, ); julia> with_container() do container run(container, config, `/bin/bash`) end ```
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
docs
462
```@meta CurrentModule = DockerSandbox ``` # [DockerSandbox.jl](https://github.com/JuliaContainerization/DockerSandbox.jl) DockerSandbox.jl is a package for running Julia `Cmd` objects inside of Docker containers. The source code for this package is available in the [GitHub repository](https://github.com/JuliaContainerization/DockerSandbox.jl). ## Related Packages You may also be interested in: 1. [Sandbox.jl](https://github.com/staticfloat/Sandbox.jl)
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
docs
140
```@meta CurrentModule = DockerSandbox ``` # Internals (Private) ```@autodocs Modules = [DockerSandbox] Public = false Private = true ```
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
docs
110
```@meta CurrentModule = DockerSandbox ``` # Prerequisites You must have Docker installed on your computer.
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
1.0.0
0fa0cbf109b2b9c55a0e998e313092fb355f0231
docs
131
```@meta CurrentModule = DockerSandbox ``` # Public API ```@autodocs Modules = [DockerSandbox] Public = true Private = false ```
DockerSandbox
https://github.com/JuliaContainerization/DockerSandbox.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
610
using ComplexDiff using Documenter DocMeta.setdocmeta!(ComplexDiff, :DocTestSetup, :(using ComplexDiff); recursive=true) makedocs(; modules=[ComplexDiff], authors="Qingyu Qu", repo="https://github.com/ErikQQY/ComplexDiff.jl/blob/{commit}{path}#{line}", sitename="ComplexDiff.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://ErikQQY.github.io/ComplexDiff.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/ErikQQY/ComplexDiff.jl", devbranch="main", )
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
277
module ComplexDiff include("unicomplex.jl") include("bicomplex.jl") include("tricomplex.jl") include("quadcomplex.jl") include("pentacomplex.jl") export bicomplex, tricomplex, quadcomplex, pentacomplex export biderivative, triderivative, quadderivative, pentaderivative end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
3575
import Base: sin, cos, tan, cot, sec, csc, atan import Base: sinh, cosh, tanh, coth, sech, csch import Base: abs, exp, log, zero import Base: +, -, *, /, ^ ## By constructing bicomplex, we can represent multi-complex numbers using recursion struct bicomplex i1 i2 end """ Using matrix to represent bicomplex. """ function mat(bi::bicomplex) i1, i2 = bi.i1, bi.i2 return [i1 -i2; i2 i1] end function mat2bicomplex(matrix) out1, out2 = matrix[1, 1], matrix[2, 1] return bicomplex(out1, out2) end ## Basic operators: +, -, *, /, ^ function +(bi1::bicomplex, bi2::bicomplex) result = mat(bi1)+mat(bi2) return mat2bicomplex(result) end function +(bi::bicomplex, n) result = n .+mat(bi) return mat2bicomplex(result) end function +(n, bi::bicomplex) result = n .+mat(bi) return mat2bicomplex(result) end function -(bi1::bicomplex, bi2::bicomplex) result = mat(bi1)-mat(bi2) return mat2bicomplex(result) end function -(bi::bicomplex, n) result = mat(bi).-n return mat2bicomplex(result) end function -(bi::bicomplex) result = -mat(bi) return mat2bicomplex(result) end function *(bi1::bicomplex, bi2::bicomplex) result = mat(bi1)*mat(bi2) return mat2bicomplex(result) end function *(n, bi::bicomplex) result = n*mat(bi) return mat2bicomplex(result) end function *(bi::bicomplex, n) result = n*mat(bi) return mat2bicomplex(result) end function /(bi1::bicomplex, bi2::bicomplex) result=mat(bi1)/mat(bi2) return mat2bicomplex(result) end function /(n, bi::bicomplex) result= n*inv(mat(bi)) return mat2bicomplex(result) end function /(bi::bicomplex, n) result=mat(bi)/n return mat2bicomplex(result) end function ^(bi::bicomplex, power) result = mat(bi)^power return mat2bicomplex(result) end function zero(bi::bicomplex) i1, i2 = bi.i1, bi.i2 return bicomplex(zero(i1), zero(i2)) end ## Basic functions: abs, exp, log function abs(bi::bicomplex) i1, i2 = bi.i1, bi.i2 return sqrt(i1^2+i2^2) end function exp(bi::bicomplex) i1, i2 = bi.i1, bi.i2 out1 = exp(i1)*cos(i2) out2 = exp(i1)*sin(i2) return bicomplex(out1, out2) end ## Basic math functions: sin, cos, tan, cot, sec, csc function sin(bi::bicomplex) i1, i2 = bi.i1, bi.i2 out1 = cosh(i2)*sin(i1) out2 = sinh(i2)*cos(i1) return bicomplex(out1, out2) end function cos(bi::bicomplex) i1, i2 = bi.i1, bi.i2 out1 = cosh(i2)*cos(i1) out2 = -sinh(i2)*sin(i1) return bicomplex(out1, out2) end function tan(bi::bicomplex) return sin(bi)/cos(bi) end function cot(bi::bicomplex) return cos(bi)/sin(bi) end function sec(bi::bicomplex) return 1/cos(bi) end function csc(bi::bicomplex) return 1/sin(bi) end ## Basic hyperbolic functions: sinh, cosh, tanh, coth, sech, csch function sinh(bi::bicomplex) i1, i2 = bi.i1, bi.i2 out1 = cosh(i1)*cos(i2) out2 = sinh(i1)*sin(i2) return bicomplex(out1, out2) end function cosh(bi::bicomplex) i1, i2 = bi.i1, bi.i2 out1 = sinh(i1)*cos(i2) out2 = cosh(i1)*sin(i2) return bicomplex(out1, out2) end function tanh(bi::bicomplex) return sinh(bi)/cosh(bi) end function coth(bi::bicomplex) return cosh(bi)/sinh(bi) end function sech(bi::bicomplex) return 1/cosh(bi) end function csch(bi::bicomplex) return 1/sinh(bi) end function image2(bi::bicomplex) i1, i2 = bi.i1, bi.i2 return imag(i2) end function biderivative(f, point, h) result = image2(f(bicomplex(point+im*h, h)))/h^2 return result end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
3465
import Base: sin, cos, tan, cot, sec, csc, atan import Base: sinh, cosh, tanh, coth, sech, csch import Base: abs, exp, log import Base: +, -, *, /, ^ struct pentacomplex i1 i2 end function mat(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 return [i1 -i2; i2 i1] end function mat2pentacomplex(matrix) out1, out2 = matrix[1, 1], matrix[2, 1] return pentacomplex(out1, out2) end ## Basic operators: +, -, *, /, ^ function +(penta1::pentacomplex, penta2::pentacomplex) result=mat(penta1)+mat(penta2) return mat2pentacomplex(result) end function +(n, penta::pentacomplex) result=n .+mat(penta) return mat2pentacomplex(result) end function +(penta::pentacomplex, n) result=n .+mat(penta) return mat2pentacomplex(result) end function -(penta1::pentacomplex, penta2::pentacomplex) result=mat(penta1)-mat(penta2) return mat2pentacomplex(result) end function -(n, penta::pentacomplex) result = n .-mat(penta) return mat2pentacomplex(result) end function -(penta::pentacomplex) result=-mat(penta) return mat2pentacomplex(result) end function *(penta1::pentacomplex, penta2::pentacomplex) result=mat(penta1)*mat(penta2) return mat2pentacomplex(result) end function *(n, penta::pentacomplex) result = n*mat(penta) return mat2pentacomplex(result) end function /(penta1::pentacomplex, penta2::pentacomplex) result=mat(penta1)/mat(penta2) return mat2pentacomplex(result) end function ^(penta::pentacomplex, power) result=mat(penta)^power return mat2pentacomplex(result) end ## Basic functions: abs, exp, log function abs(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 return sqrt(i1^2+i2^2) end function exp(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 out1 = exp(i1)*cos(i2) out2 = exp(i1)*sin(i2) return pentacomplex(out1, out2) end ## Basic math functions: sin, cos, tan, cot, sec, csc function sin(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 out1 = cosh(i2)*sin(i1) out2 = sinh(i2)*cos(i1) return pentacomplex(out1, out2) end function cos(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 out1 = cosh(i2)*cos(i1) out2 = -sinh(i2)*sin(i1) return pentacomplex(out1, out2) end function tan(penta::pentacomplex) return sin(penta)/cos(penta) end function cot(penta::pentacomplex) return cos(penta)/sin(penta) end function sec(penta::pentacomplex) return 1/cos(penta) end function csc(penta::pentacomplex) return 1/sin(penta) end ## Basic hyperbolic functions: sinh, cosh, tanh, coth, sech, csch function sinh(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 out1 = cosh(i1)*cos(i2) out2 = sinh(i1)*sin(i2) return pentacomplex(out1, out2) end function cosh(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 out1 = sinh(i1)*cos(i2) out2 = cosh(i1)*sin(i2) return pentacomplex(out1, out2) end function tanh(penta::pentacomplex) return sinh(penta)/cosh(penta) end function coth(penta::pentacomplex) return cosh(penta)/sinh(penta) end function sech(penta::pentacomplex) return 1/cosh(penta) end function csch(penta::pentacomplex) return 1/sinh(penta) end function image5(penta::pentacomplex) i1, i2 = penta.i1, penta.i2 return image4(i2) end function pentaderivative(f, point, h) result = image5(f(pentacomplex(quadcomplex(tricomplex(bicomplex(point+im*h, h), h), h), h)))/h^5 return result end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
3732
import Base: sin, cos, tan, cot, sec, csc, atan import Base: sinh, cosh, tanh, coth, sech, csch import Base: abs, exp, log, zero, one import Base: +, -, *, /, ^ struct quadcomplex i1 i2 end function mat(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 return [i1 -i2; i2 i1] end function mat2quadcomplex(matrix) out1, out2 = matrix[1, 1], matrix[2, 1] return quadcomplex(out1, out2) end ## Basic operators: +, -, *, /, ^ function +(quad1::quadcomplex, quad2::quadcomplex) result=mat(quad1)+mat(quad2) return mat2quadcomplex(result) end function +(n, quad::quadcomplex) result=n .+mat(quad) return mat2quadcomplex(result) end function +(quad::quadcomplex, n) result=n .+mat(quad) return mat2quadcomplex(result) end function -(quad1::quadcomplex, quad2::quadcomplex) result=mat(quad1)-mat(quad2) return mat2quadcomplex(result) end function -(n, quad::quadcomplex) result=n .-mat(quad) return mat2quadcomplex(result) end function -(quad::quadcomplex) result=-mat(quad) return mat2quadcomplex(result) end function *(quad1::quadcomplex, quad2::quadcomplex) result=mat(quad1)*mat(quad2) return mat2quadcomplex(result) end function *(n, quad::quadcomplex) result = n*mat(quad) return mat2quadcomplex(result) end function *(quad::quadcomplex, n) result = n*mat(quad) return mat2quadcomplex(result) end function /(quad1::quadcomplex, quad2::quadcomplex) result=mat(quad1)/mat(quad2) return mat2quadcomplex(result) end function /(n, quad::quadcomplex) result=n*inv(quad) return result end function ^(quad::quadcomplex, power) result=mat(quad)^power return mat2quadcomplex(result) end function zero(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 return quadcomplex(zero(i1), zero(i2)) end function one(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 return quadcomplex(one(i1), one(i2)) end ## Basic functions: abs, exp, log function abs(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 return sqrt(i1^2+i2^2) end function exp(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 out1 = exp(i1)*cos(i2) out2 = exp(i1)*sin(i2) return quadcomplex(out1, out2) end ## Basic math functions: sin, cos, tan, cot, sec, csc function sin(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 out1 = cosh(i2)*sin(i1) out2 = sinh(i2)*cos(i1) return quadcomplex(out1, out2) end function cos(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 out1 = cosh(i2)*cos(i1) out2 = -sinh(i2)*sin(i1) return quadcomplex(out1, out2) end function tan(quad::quadcomplex) return sin(quad)/cos(quad) end function cot(quad::quadcomplex) return cos(quad)/sin(quad) end function sec(quad::quadcomplex) return 1/cos(quad) end function csc(quad::quadcomplex) return 1/sin(quad) end ## Basic hyperbolic functions: sinh, cosh, tanh, coth, sech, csch function sinh(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 out1 = cosh(i1)*cos(i2) out2 = sinh(i1)*sin(i2) return quadcomplex(out1, out2) end function cosh(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 out1 = sinh(i1)*cos(i2) out2 = cosh(i1)*sin(i2) return quadcomplex(out1, out2) end function tanh(quad::quadcomplex) return sinh(quad)/cosh(quad) end function coth(quad::quadcomplex) return cosh(quad)/sinh(quad) end function sech(quad::quadcomplex) return 1/cosh(quad) end function csch(quad::quadcomplex) return 1/sinh(quad) end function image4(quad::quadcomplex) i1, i2 = quad.i1, quad.i2 return image3(i2) end function quadderivative(f, point, h) result = image4(f(quadcomplex(tricomplex(bicomplex(point+im*h, h), h), h)))/h^4 return result end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
3502
import Base: sin, cos, tan, cot, sec, csc, atan import Base: sinh, cosh, tanh, coth, sech, csch import Base: abs, exp, log, zero import Base: +, -, *, /, ^ struct tricomplex i1#::bicomplex i2 end function mat(tri::tricomplex) i1, i2 = tri.i1, tri.i2 return [i1 -i2; i2 i1] end function mat2tricomplex(matrix) out1, out2 = matrix[1, 1], matrix[2, 1] return tricomplex(out1, out2) end ## Basic operators: +, -, *, /, ^ function +(tri1::tricomplex, tri2::tricomplex) result = mat(tri1)+mat(tri2) return mat2tricomplex(result) end function +(n, tri::tricomplex) result = n .+mat(tri) return mat2tricomplex(result) end function +(tri::tricomplex, n) result = n .+mat(tri) return mat2tricomplex(result) end function -(tri1::tricomplex, tri2::tricomplex) result=mat(tri1)-mat(tri2) return mat2tricomplex(result) end -(tri::tricomplex)=mat2tricomplex(-mat(tri)) function *(tri1::tricomplex, tri2::tricomplex) result=mat(tri1)*mat(tri2) return mat2tricomplex(result) end function *(n, tri::tricomplex) result = n*mat(tri) return mat2tricomplex(result) end function *(tri::tricomplex, n) result = n*mat(tri) return mat2tricomplex(result) end function /(tri1::tricomplex, tri2::tricomplex) result=mat(tri1)-mat(tri2) return mat2tricomplex(result) end function /(n, tri::tricomplex) result=n*inv(mat(tri)) return mat2tricomplex(result) end function /(tri::tricomplex, n) result=mat(tri)/n return mat2tricomplex(result) end function ^(tri::tricomplex, power) result=mat(tri)^power return mat2tricomplex(result) end function zero(tri::tricomplex) i1, i2 = tri.i1, tri.i2 return tricomplex(zero(i1), zero(i2)) end function abs(tri::tricomplex) i1, i2 = tri.i1, tri.i2 return sqrt(i1^2+i2^2) end function sin(tri::tricomplex) i1, i2 = tri.i1, tri.i2 out1 = cosh(i2)*sin(i1) out2 = sinh(i2)*cos(i1) return tricomplex(out1, out2) end function cos(tri::tricomplex) i1, i2 = tri.i1, tri.i2 out1 = cosh(i2)*cos(i1) out2 = -sinh(i2)*sin(i1) return tricomplex(out1, out2) end function tan(tri::tricomplex) return sin(tri)/cos(tri) end function cot(tri::tricomplex) return cos(tri)/sin(tri) end function sec(tri::tricomplex) return 1/cos(tri) end function csc(tri::tricomplex) return 1/sin(tri) end ## Basic functions: abs, exp, log function abs(tri::tricomplex) i1, i2 = tri.i1, tri.i2 return sqrt(i1^2+i2^2) end function exp(tri::tricomplex) i1, i2 = tri.i1, tri.i2 out1 = exp(i1)*cos(i2) out2 = exp(i1)*sin(i2) return tricomplex(out1, out2) end ## Basic hyperbolic functions: sinh, cosh, tanh, coth, sech, csch function sinh(tri::tricomplex) i1, i2 = tri.i1, tri.i2 out1 = cosh(i1)*cos(i2) out2 = sinh(i1)*sin(i2) return tricomplex(out1, out2) end function cosh(tri::tricomplex) i1, i2 = tri.i1, tri.i2 out1 = sinh(i1)*cos(i2) out2 = cosh(i1)*sin(i2) return tricomplex(out1, out2) end function tanh(tri::tricomplex) return sinh(tri)/cosh(tri) end function coth(tri::tricomplex) return cosh(tri)/sinh(tri) end function sech(tri::tricomplex) return 1/cosh(tri) end function csch(tri::tricomplex) return 1/sinh(tri) end function image3(tri::tricomplex) i1, i2 = tri.i1, tri.i2 return image2(i2) end function triderivative(f, point, h) result = image3(f(tricomplex(bicomplex(point+im*h, h), h)))/h^3 return result end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
69
function derivative(f, point, h) return imag(f(point+im*h))/h end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
241
using ComplexDiff using Test @testset "Test Second Order Derivative" begin @test isapprox(biderivative(x->x^2, 1, 0.00001), 2; atol=1e-5) @test isapprox(biderivative(x->1/sin(x), 1, 0.000001), 1/2*(3+cos(2))*csc(1)^3; atol=1e-5) end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
151
using ComplexDiff using Test @testset "Test Second Order Derivative" begin @test isapprox(quadderivative(sin, 1, 0.000001), sin(1); atol=1e-5) end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
165
using ComplexDiff using Test @testset "ComplexDiff.jl" begin include("bicomplextest.jl") include("tricomplextest.jl") include("quadcomplextest.jl") end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
code
288
using ComplexDiff using Test @testset "Test Third Order Derivative" begin @test isapprox(triderivative(sin, 1, 0.00001), -cos(1); atol=1e-5) @test isapprox(triderivative(x->x^3, 1, 0.00001), 6; atol=1e-5) @test isapprox(triderivative(x->x^4, 1, 0.0000001), 24; atol=1e-5) end
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
docs
670
# ComplexDiff [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://ErikQQY.github.io/ComplexDiff.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://ErikQQY.github.io/ComplexDiff.jl/dev) [![Build Status](https://github.com/ErikQQY/ComplexDiff.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/ErikQQY/ComplexDiff.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/ErikQQY/ComplexDiff.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/ErikQQY/ComplexDiff.jl) ComplexDiff.jl fully utilize the complex step differentiation to compute accurate and high order derivative.
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
0.1.0
f50bb0aaaa1ac0d2473fc37922718a01ed1ff4b1
docs
190
```@meta CurrentModule = ComplexDiff ``` # ComplexDiff Documentation for [ComplexDiff](https://github.com/ErikQQY/ComplexDiff.jl). ```@index ``` ```@autodocs Modules = [ComplexDiff] ```
ComplexDiff
https://github.com/ErikQQY/ComplexDiff.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
919
using ImageMethodReverb, Random, WAV, LinearAlgebra Fs = 16e3 # sampling frequency T60 = 0.9 # reverberation time xs = [1, 2, 2] #src pos (in meters) xr = [2, 1.5, 1] #mic pos L = Lx, Ly, Lz = 4.,4.,4. # room dimensions in meters Nt = round(Int,Fs) #time samples 1 sec h_se, = rim(xs,xr,L,0.93.*ones(6),Nt,Fs; Rd=0) # with sweeping echo h, = rim(xs,xr,L,0.93.*ones(6),Nt,Fs) # without sweeping echo wavplay(0.8 .* h_se ./ norm(h,Inf),Fs) wavplay(0.8 .* h ./ norm(h,Inf),Fs) using Plots, FFTW f = rfftfreq(Nt,Fs) t = range(0; length = Nt, step = 1/Fs ) p1 = plot(t, h_se, xlabel="Time (t)", ylabel="Sound Pressure (Pa)") plot!(p1, t, h) p2 = plot(f, 10 .* log10.(abs.(rfft(h_se))), xlabel="Frequency (Hz)", ylabel="Sound Pressure (dB)", xlim=[50;500], ) plot!(p2, f, 10 .* log10.(abs.(rfft(h)))) plot(p1,p2)
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
124
__precompile__() module ImageMethodReverb using Random, LinearAlgebra include("rim_solver.jl") include("utils.jl") end
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
5063
export rim """ `h, seed = rim(xs, xr, L, T60, Nt, Fs)` Computes a synthetic acoustic room impulse response (RIR). #### Arguments: * `xs` : source position (m) * `xr` : microphone position (m) * `L` : room dimensions (m) * `beta`/`T60` : 6 element containing reflection coefficients of walls/reverberation time * `Nt` : length of the RIR (samples) * `Fs` : sampling frequency (Hz) #### Keyword Arguments: * `c = 343` : speed of sound (m/s) * `Rd = 1e-1` : random displacement (m) * `N = (0,0,0)`: 3 element representing order of reflection when `N == (0,0,0)` full order is computed. * `Tw = 20` : taps of fractional delay filter (samples) * `Fc = 0.9` : cut-off frequency of fractional delay filter (samples) * `T=Float64` : data type #### Outputs: * `h`: vector or matrix where each column is an impulse response or the sound pressure if `s` was specified corresponding to the microphone positions `xr` * `seed`: randomization seed to preserve spatial properties when other RIR at different position are needed """ function rim(xs, xr, L, beta, Nt::Int, Fs; c = 343, Rd = 8e-2, seed = 1234, N = (0,0,0), Tw = 20, Fc = 0.9, T = Float64, ) if length(xs) != 3 throw(ErrorException("length(xs) must be equal to 3")) end if length(xr) != 3 throw(ErrorException("length(xr) must be equal to 3")) end if length(L) != 3 throw(ErrorException("length(L) must be equal to 3")) end if length(N) != 3 throw(ErrorException("length(L) must be equal to 3")) end if any( xs .> L ) || any( xs .< 0 ) throw(ErrorException("xs outside of room")) end if any( xr .> L ) || any( xr .< 0 ) throw(ErrorException("xr outside of room")) end if any(N .< 0 ) throw(ErrorException("N should be positive")) end if any( (typeof(n) <: Int) == false for n in N ) throw(ErrorException("N should be integers only")) end if length(beta) == 1 # T60 beta = revTime2beta(L, beta, c) end if length(beta) != 6 throw(ErrorException("beta must be either of length 1 or 6")) end Fsc = T(Fs/c) L = Array{T}([L.*(Fsc*2)...]) # remove units xr = Array{T}([xr.*Fsc...]) xs = Array{T}([xs.*Fsc...]) beta = Array{T}([beta...]) N = [N...] Rd = T(Rd *Fsc) h = zeros(T,Nt) # initialize output pos_is = zeros(T,3) if( all(N .== 0) ) N = floor.(Int, Nt./L).+1 # compute full order end Random.seed!(seed) run_rim!(h, xs, xr, pos_is, L, beta, N, T(Rd), Fc, Tw, Nt) h .*= Fsc return h, seed end # with fractional delay function run_rim!(h::V, xs::V, xr::V, pos_is::V, L::V, beta::V, N::VI, Rd::T, Fc::T, Tw::I, Nt::I, ) where {T <: AbstractFloat, V <: AbstractArray{T}, I <: Integer, VI <: AbstractArray{I}, } beta_pow = zeros(I,6) for u = 0:1, v = 0:1, w = 0:1 for l = -N[1]:N[1], m = -N[2]:N[2], n = -N[3]:N[3] if (l ==0 && m == 0 && n == 0 && u == 0 && v == 0 && w == 0) # we have direct path, so # no displacement is added RD = 0.0 else RD = Rd end # compute distance pos_is[1] = xs[1]-2*u*xs[1]+l*L[1]+RD*randn() pos_is[2] = xs[2]-2*v*xs[2]+m*L[2]+RD*randn() pos_is[3] = xs[3]-2*w*xs[3]+n*L[3]+RD*randn() # position of image source d = norm( pos_is .-xr )+1 + Rd id = round(Int64,d) if (id > Nt || id < 1) #if index not exceed length h continue end A = get_amplitude!(beta, beta_pow, l,m,n, u,v,w, d) if Tw == 0 h[id] += A else add_sinc_delay!(h, d, A, Tw, Fc, Nt) end end end return h end # fractional delay function add_sinc_delay!(h::Array{T}, d::T, A::T, Tw::I, Fc::T, Nt::I) where {T <: AbstractFloat, I <: Integer} # create time window indx = max(ceil(I,d.-Tw/2),1):min(floor(I,d.+Tw/2),Nt) # compute filtered impulse A2 = A/2 @inbounds @simd for i in indx h[i] += A2 *( 1.0 + cos(2*π*(i-d)/Tw) )*sinc(Fc*(i-d)) end return h end function get_amplitude!(beta::Array{T}, beta_pow::Array{I}, l::I,m::I,n::I, u::I,v::I,w::I, d::T) where {I <: Integer, T <: AbstractFloat} beta_pow[1] = abs(l-u) beta_pow[2] = abs(l) beta_pow[3] = abs(m-v) beta_pow[4] = abs(m) beta_pow[5] = abs(n-w) beta_pow[6] = abs(n) A = one(T) for i in eachindex(beta) A *= beta[i]^beta_pow[i] end A /= (4*π*(d-1)) return A end
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
1050
export revTime """ `revTime(h::AbstractVector, Fs::Number)` Returns the T60 of the impulse response `h` with sampling frequency `Fs`. """ function revTime(h::AbstractVector,Fs::Number) cs = cumsum(reverse(h.^2, dims = 1), dims = 1) edc = 10*log10.(reverse(cs./cs[end], dims = 1)) #energy decay curve rt = zeros(Float64,size(h,2)) for i = 1:size(h,2) ind = findfirst(edc[:,i] .<= -60. ) if ind == 0 rt[i] = size(h,1)/Fs else rt[i] = ind/Fs end end return rt, edc end """ `revTime2beta( (Lx,Ly,Lz), T60, c = 343)` Given the reverberation time in T60 in a cuboid room with volume `Lx` x `Ly` x `Lz` returns a 6-long vector containing the reflection coefficients (β) of each wall surface. """ function revTime2beta(L, T60, c) if(T60 < 0) error("T60 should be positive") end Lx, Ly, Lz = L S = 2*( Lx*Ly+Lx*Lz+Ly*Lz ) # Total surface area V = prod([Lx;Ly;Lz]) α = 1-exp(-(24*V*log(10))/(c*T60*S)) # Absorption coefficient β =-sqrt(abs(1-α)).*ones(6) # Reflection coefficient return β end
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
286
using ImageMethodReverb using Test using LinearAlgebra using DelimitedFiles, Random @testset "ImageMethodReverb" begin @testset "Image source method" begin include("test_ism.jl") end @testset "equivalence with MATLAB" begin include("test_julia_vs_matlab.jl") end end
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
2111
#testing seed is preserved Fs = 4e4 # Sampling frequency c = 343 # create new acoustic env with default values Nt = round(Int64,0.1*Fs) # Number of time samples, 0.25 secs L = (4., 4., 4.) # Room dimensions Lx,Ly,Lz = L xs = (2., 1.5, 1.) # Source position xr = (1., 2., 2.) # Receiver position T60 = 0.1 # Reverberation Time beta = ImageMethodReverb.revTime2beta(L, T60, c) Tw = 20 # samples of Low pass filter Fc = 0.9 # cut-off frequency println("testing β for a given T60 gives correct T60") h, seed = rim(xs,xr,L,beta,Nt,Fs; N = (4,4,4)) rt, edc = revTime(h, Fs) @test norm(rt.-T60)/norm(T60)< 0.25 #testing rev time println("testing seed is preserved") h2, = rim(xs,xr,L,beta,Nt,Fs; N = (4,4,4), seed = seed) @test norm(h-h2) < 1e-8 println("testing calls") # with T60 h2, = rim(xs,xr,L,T60,Nt,Fs; N = (4,4,4), seed = seed) @test norm(h-h2) < 1e-8 ## original image source method println("test with no fractional delay") xs = (2., 1.5, 1.) # Source position xr = (1., 2., 2.) # Receiver position h2, = rim(xs,xr,L,beta,Nt,Fs; Tw = 0, Fc = 0., N = (4,4,4), seed = seed) println("test line of sight") xs = (1., 1., 1.) for i = 1:10 d = (0.2 .*randn(3)...,) # dandom dispacement h_rand, = rim(xs, xs .+ d, L, 0.001, Nt,Fs; Rd = 1e-1, N = (0,0,0)) @test argmax(h_rand)*1/Fs - norm(xr .- xs)/343 < 1e-4 end # testing errors L, xr, xs = (1,1,1), (0.5,0.5,0.5),(0.7,0.7,0.7) @test_throws ErrorException rim((0.1,), xr, L, beta, Nt,Fs) @test_throws ErrorException rim((1.1,0,0), xr, L, beta, Nt,Fs) @test_throws ErrorException rim(xs,(0.1,), L, beta, Nt,Fs) @test_throws ErrorException rim(xs,(1.1,0,0), L, beta, Nt,Fs) @test_throws ErrorException rim(xs,xr,(0,0), beta, Nt,Fs) @test_throws ErrorException rim(xs,xr,L, beta, Nt,Fs; N=(-1,1,1)) @test_throws ErrorException rim(xs,xr,L, beta, Nt,Fs; N=(1,1)) @test_throws ErrorException rim(xs,xr,L, beta, Nt,Fs; N=(1,1)) @test_throws ErrorException rim(xs,xr,L, beta, Nt,Fs; N=(1.5,1,1)) @test_throws ErrorException rim(xs,xr,L, (1,1), Nt,Fs)
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
code
709
# testing output of this implementation with the one # of Enzo de Sena: http://www.desena.org/sweep/ Fs = 4e4 # Sampling frequency c = 343 # create new acoustic env with default values Nt = round(Int64,4E4/4) # Number of time samples xs = (2.,1.5,1.) # Source position xr = (1.,2.,2.) # Receiver position L = (4.,4.,4.) # Room dimensions beta = 0.93.*(ones(6)...,) # Reflection coefficient Rd = 0.00 # random displacement Tw = 40 # samples of Low pass filter Fc = 0.9 # cut-off frequency # generate IR with randomization h, = rim(xs,xr,L,beta,Nt,Fs; Tw = Tw, Fc = Fc, Rd = Rd) hm = readdlm("h.txt") @test norm(hm-h)<1e-8
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
1.1.0
88866a0ccca8df6cd2414ce0dc0660b56b975ccb
docs
1654
# Image Method Reverb [![DOI](https://zenodo.org/badge/31613348.svg)](https://zenodo.org/badge/latestdoi/31613348) [![Build status](https://github.com/nantonel/ImageMethodReverb.jl/workflows/CI/badge.svg)](https://github.com/nantonel/ImageMethodReverb.jl/actions?query=workflow%3ACI) [![codecov.io](http://codecov.io/github/nantonel/ImageMethodReverb.jl/coverage.svg?branch=master)](http://codecov.io/github/nantonel/ImageMethodReverb.jl?branch=master) Acoustic Room Impulse Response (RIR) generator using the (Randomized) Image Method for rectangular rooms. Convolving a RIR with an audio file adds reverberation. ## Installation To install the package, hit `]` from the Julia command line to enter the package manager, then ```julia pkg> add ImageMethodReverb ``` See the demo folder for some examples. Type `?rim` for more details. By default the randomized image method from [1] is used. The original image method proposed in [2] can be reproduced as well by turning off the randomization and fractional delays. ## Other languages implementations A MATLAB implementation of the Randomized Image Method can be found [here](https://github.com/enzodesena/rim). ## References * [1] [E. De Sena, N. Antonello, M. Moonen, and T. van Waterschoot, "On the Modeling of Rectangular Geometries in Room Acoustic Simulations", IEEE Transactions of Audio, Speech Language Processing, vol. 21, no. 4, 2015.](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=7045580) * [2] Allen, Jont B., and David A. Berkley. "Image method for efficiently simulating small‐room acoustics." The Journal of the Acoustical Society of America vol. 65 no. 4, 1979.
ImageMethodReverb
https://github.com/nantonel/ImageMethodReverb.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
code
94
# Copyright © 2021 Alexander L. Hayes using Documenter makedocs(sitename="ExportPublic.jl")
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
code
2058
# Copyright © 2021 Alexander L. Hayes # Copyright © 2019 John Tinnerhom #= MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =# module ExportPublic macro exportPublic() inI = [] out = [] res = [] for name in Base.names(__module__, all = true) push!(out, :(export $(name))) end for name in Base.names(__module__, all = false, imported = true) push!(inI, :(export $(name))) end for name in Base.names(Main.Base, all = false, imported = true) push!(inI, :(export $(name))) end for name in Base.names(Main.Core, all = false, imported = true) push!(inI, :(export $(name))) end for e in out if e in inI || e == :(export include) || '#' in string(e) || "_" == SubString(string(e), 8, 8) continue end push!(res, :($(e))) end # Do not export things that we already have ret = Expr(:block, res...) return ret end @exportPublic() end
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
code
237
module Bar using ExportPublic function foo() 1 end function bar() 2 end function barBar() 3 end function fooFoo() _secret_implementation_detail() end function _secret_implementation_detail() 4 end @exportPublic() end
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
code
331
module DemoModule using ExportPublic function add(a, b) # `add` is exported automatically return _private_helper(a) + _private_helper(b) end function _private_helper(a) # `_private_helper` should not be exported, so it's marked with a `_` return a end @exportPublic() end
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
code
426
module SimpleMath using ExportPublic _secret_pi = 22/7 my_pi = _secret_pi function add_two(a::Int, b::Int) _implementation_detail(a) + _implementation_detail(b) end function _implementation_detail(a::Int) a end function add_squared(a::Int, b::Int) _square_it(a) + _square_it(b) end function _square_it(a::Int) a ^ 2 end @exportPublic() end
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git
[ "MIT" ]
0.1.0
32ac213c415abaee7c6a36dd65bacf2c65b8836d
code
958
module ExportPublicTest using Test include("Bar.jl") using .Bar include("SimpleMath.jl") using .SimpleMath include("DemoModule.jl") using .DemoModule @testset "Bar.jl" begin @test foo() == 1 @test bar() == 2 @test barBar() == 3 @test fooFoo() == 4 @test_throws UndefVarError _secret_implementation_detail() end @testset "SimpleMath.jl" begin @test add_two(5, 5) == 10 @test add_two(10, 10) == 20 @test_throws UndefVarError _implementation_detail() @test add_squared(1, 1) == 2 @test add_squared(2, 2) == 8 @test add_squared(4, 4) == 32 @test_throws UndefVarError _square_it() @test my_pi == 22/7 @test_throws UndefVarError _secret_pi end @testset "DemoModule.jl" begin @test add(5, 5) == 10 @test add(6, 6) == 12 @test_throws UndefVarError _private_helper() end end
ExportPublic
https://github.com/hayesall/ExportPublic.jl.git