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.9.1 | 9e2f36d3c96a820c678f2f1f1782582fcf685bae | code | 15195 | # This file is a part of Julia. License is MIT: https://julialang.org/license
using Test, Random
using DelimitedFiles
isequaldlm(m1, m2, t) = isequal(m1, m2) && (eltype(m1) == eltype(m2) == t)
@testset "readdlm" begin
@test isequaldlm(readdlm(IOBuffer("1\t2\n3\t4\n5\t6\n")), [1. 2; 3 4; 5 6], Float64)
@test isequaldlm(readdlm(IOBuffer("1\t2\n3\t4\n5\t6\n"), Int), [1 2; 3 4; 5 6], Int)
@test isequaldlm(readdlm(IOBuffer("1,22222222222222222222222222222222222222,0x3,10e6\n2000.1,true,false,-10.34"), ',', Any),
reshape(Any[1,2000.1,Float64(22222222222222222222222222222222222222),true,0x3,false,10e6,-10.34], 2, 4), Any)
@test isequaldlm(readdlm(IOBuffer("-9223355253176920979,9223355253176920979"), ',', Int64), Int64[-9223355253176920979 9223355253176920979], Int64)
@test size(readdlm(IOBuffer("1,2,3,4"), ',')) == (1,4)
@test size(readdlm(IOBuffer("1,2,3,"), ',')) == (1,4)
@test size(readdlm(IOBuffer("1,2,3,4\n"), ',')) == (1,4)
@test size(readdlm(IOBuffer("1,2,3,\n"), ',')) == (1,4)
@test size(readdlm(IOBuffer("1,2,3,4\n1,2,3,4"), ',')) == (2,4)
@test size(readdlm(IOBuffer("1,2,3,4\n1,2,3,"), ',')) == (2,4)
@test size(readdlm(IOBuffer("1,2,3,4\n1,2,3"), ',')) == (2,4)
@test size(readdlm(IOBuffer("1,2,3,4\r\n"), ',')) == (1,4)
@test size(readdlm(IOBuffer("1,2,3,4\r\n1,2,3\r\n"), ',')) == (2,4)
@test size(readdlm(IOBuffer("1,2,3,4\r\n1,2,3,4\r\n"), ',')) == (2,4)
@test size(readdlm(IOBuffer("1,2,3,\"4\"\r\n1,2,3,4\r\n"), ',')) == (2,4)
@test size(readdlm(IOBuffer("1 2 3 4\n1 2 3"))) == (2,4)
@test size(readdlm(IOBuffer("1\t2 3 4\n1 2 3"))) == (2,4)
@test size(readdlm(IOBuffer("1\t 2 3 4\n1 2 3"))) == (2,4)
@test size(readdlm(IOBuffer("1\t 2 3 4\n1 2 3\n"))) == (2,4)
@test size(readdlm(IOBuffer("1,,2,3,4\n1,2,3\n"), ',')) == (2,5)
let result1 = reshape(Any["", "", "", "", "", "", 1.0, 1.0, "", "", "", "", "", 1.0, 2.0, "", 3.0, "", "", "", "", "", 4.0, "", "", ""], 2, 13),
result2 = reshape(Any[1.0, 1.0, 2.0, 1.0, 3.0, "", 4.0, ""], 2, 4)
@test isequaldlm(readdlm(IOBuffer(",,,1,,,,2,3,,,4,\n,,,1,,,1\n"), ','), result1, Any)
@test isequaldlm(readdlm(IOBuffer(" 1 2 3 4 \n 1 1\n")), result2, Any)
@test isequaldlm(readdlm(IOBuffer(" 1 2 3 4 \n 1 1\n"), ' '), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1 2\n3 4 \n")), [[1.0, 3.0] [2.0, 4.0]], Float64)
end
let result1 = reshape(Any["", "", "", "", "", "", "भारत", 1.0, "", "", "", "", "", 1.0, 2.0, "", 3.0, "", "", "", "", "", 4.0, "", "", ""], 2, 13)
@test isequaldlm(readdlm(IOBuffer(",,,भारत,,,,2,3,,,4,\n,,,1,,,1\n"), ',') , result1, Any)
end
let result1 = reshape(Any[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, ""], 2, 4)
@test isequaldlm(readdlm(IOBuffer("1\t 2 3 4\n1 2 3")), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1\t 2 3 4\n1 2 3 ")), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1\t 2 3 4\n1 2 3\n")), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1,2,3,4\n1,2,3\n"), ','), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1,2,3,4\n1,2,3"), ','), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1,2,3,4\r\n1,2,3\r\n"), ','), result1, Any)
@test isequaldlm(readdlm(IOBuffer("1,2,3,\"4\"\r\n1,2,3\r\n"), ','), result1, Any)
end
let result1 = reshape(Any["abc", "hello", "def,ghi", " \"quote\" ", "new\nline", "world"], 2, 3),
result2 = reshape(Any["abc", "line\"", "\"hello\"", "\"def", "", "\" \"\"quote\"\" \"", "ghi\"", "", "world", "\"new", "", ""], 3, 4)
@test isequaldlm(readdlm(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ','), result1, Any)
@test isequaldlm(readdlm(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ',', quotes=false), result2, Any)
end
let result1 = reshape(Any["t", "c", "", "c"], 2, 2),
result2 = reshape(Any["t", "\"c", "t", "c"], 2, 2)
@test isequaldlm(readdlm(IOBuffer("t \n\"c\" c")), result1, Any)
@test isequaldlm(readdlm(IOBuffer("t t \n\"\"\"c\" c")), result2, Any)
end
@test isequaldlm(readdlm(IOBuffer("\n1,2,3\n4,5,6\n\n\n"), ',', skipblanks=false),
reshape(Any["",1.0,4.0,"","","",2.0,5.0,"","","",3.0,6.0,"",""], 5, 3), Any)
@test isequaldlm(readdlm(IOBuffer("\n1,2,3\n4,5,6\n\n\n"), ',', skipblanks=true), reshape([1.0,4.0,2.0,5.0,3.0,6.0], 2, 3), Float64)
@test isequaldlm(readdlm(IOBuffer("1,2\n\n4,5"), ',', skipblanks=false), reshape(Any[1.0,"",4.0,2.0,"",5.0], 3, 2), Any)
@test isequaldlm(readdlm(IOBuffer("1,2\n\n4,5"), ',', skipblanks=true), reshape([1.0,4.0,2.0,5.0], 2, 2), Float64)
let x = bitrand(5, 10), io = IOBuffer()
writedlm(io, x)
seek(io, 0)
@test readdlm(io, Bool) == x
end
let x = [1,2,3], y = [4,5,6], io = IOBuffer()
writedlm(io, zip(x,y), ", ")
seek(io, 0)
@test readdlm(io, ',') == [x y]
end
let x = [0.1 0.3 0.5], io = IOBuffer()
writedlm(io, x, ", ")
seek(io, 0)
@test read(io, String) == "0.1, 0.3, 0.5\n"
end
let x = [0.1 0.3 0.5], io = IOBuffer()
writedlm(io, x, ", ")
seek(io, 0)
@test readdlm(io, ',') == [0.1 0.3 0.5]
end
let x = ["abc", "def\"ghi", "jk\nl"], y = [1, ",", "\"quoted\""], io = IOBuffer()
writedlm(io, zip(x,y), ',')
seek(io, 0)
@test readdlm(io, ',') == [x y]
end
let x = ["a" "b"; "d" ""], io = IOBuffer()
writedlm(io, x)
seek(io, 0)
@test readdlm(io) == x
end
let x = ["\"hello\"", "world\""], io = IOBuffer()
writedlm(io, x, quotes=false)
@test String(take!(io)) == "\"hello\"\nworld\"\n"
writedlm(io, x)
@test String(take!(io)) == "\"\"\"hello\"\"\"\n\"world\"\"\"\n"
end
end
@testset "comments" begin
@test isequaldlm(readdlm(IOBuffer("#this is comment\n1,2,3\n#one more comment\n4,5,6"), ',', comments=true), [1. 2. 3.;4. 5. 6.], Float64)
@test isequaldlm(readdlm(IOBuffer("#this is \n#comment\n1,2,3\n#one more \n#comment\n4,5,6"), ',', comments=true), [1. 2. 3.;4. 5. 6.], Float64)
@test isequaldlm(readdlm(IOBuffer("1,2,#3\n4,5,6"), ',', comments=true), [1. 2. "";4. 5. 6.], Any)
@test isequaldlm(readdlm(IOBuffer("1#,2,3\n4,5,6"), ',', comments=true), [1. "" "";4. 5. 6.], Any)
@test isequaldlm(readdlm(IOBuffer("1,2,\"#3\"\n4,5,6"), ',', comments=true), [1. 2. "#3";4. 5. 6.], Any)
@test isequaldlm(readdlm(IOBuffer("1,2,3\n #with leading whitespace\n4,5,6"), ',', comments=true), [1. 2. 3.;" " "" "";4. 5. 6.], Any)
end
@testset "without comments" begin
@test isequaldlm(readdlm(IOBuffer("1,2,#3\n4,5,6"), ','), [1. 2. "#3";4. 5. 6.], Any)
@test isequaldlm(readdlm(IOBuffer("1#,2,3\n4,5,6"), ','), ["1#" 2. 3.;4. 5. 6.], Any)
@test isequaldlm(readdlm(IOBuffer("1,2,\"#3\"\n4,5,6"), ','), [1. 2. "#3";4. 5. 6.], Any)
end
@testset "skipstart" begin
x = ["a" "b" "c"; "d" "e" "f"; "g" "h" "i"; "A" "B" "C"; 1 2 3; 4 5 6; 7 8 9]
io = IOBuffer()
writedlm(io, x, quotes=false)
seek(io, 0)
(data, hdr) = readdlm(io, header=true, skipstart=3)
@test data == [1 2 3; 4 5 6; 7 8 9]
@test hdr == ["A" "B" "C"]
x = ["a" "b" "\nc"; "d" "\ne" "f"; "g" "h" "i\n"; "A" "B" "C"; 1 2 3; 4 5 6; 7 8 9]
io = IOBuffer()
writedlm(io, x, quotes=true)
seek(io, 0)
(data, hdr) = readdlm(io, header=true, skipstart=6)
@test data == [1 2 3; 4 5 6; 7 8 9]
@test hdr == ["A" "B" "C"]
io = IOBuffer()
writedlm(io, x, quotes=false)
seek(io, 0)
(data, hdr) = readdlm(io, header=true, skipstart=6)
@test data == [1 2 3; 4 5 6; 7 8 9]
@test hdr == ["A" "B" "C"]
end
@testset "i18n" begin
# source: http://www.i18nguy.com/unicode/unicode-example-utf8.zip
let i18n_data = ["Origin (English)", "Name (English)", "Origin (Native)", "Name (Native)",
"Australia", "Nicole Kidman", "Australia", "Nicole Kidman",
"Austria", "Johann Strauss", "Österreich", "Johann Strauß",
"Belgium (Flemish)", "Rene Magritte", "België", "René Magritte",
"Belgium (French)", "Rene Magritte", "Belgique", "René Magritte",
"Belgium (German)", "Rene Magritte", "Belgien", "René Magritte",
"Bhutan", "Gonpo Dorji", "འབྲུག་ཡུལ།", "མགོན་པོ་རྡོ་རྗེ།",
"Canada", "Celine Dion", "Canada", "Céline Dion",
"Canada - Nunavut (Inuktitut)", "Susan Aglukark", "ᓄᓇᕗᒻᒥᐅᑦ", "ᓱᓴᓐ ᐊᒡᓗᒃᑲᖅ",
"Democratic People's Rep. of Korea", "LEE Sol-Hee", "조선 민주주의 인민 공화국", "이설희",
"Denmark", "Soren Hauch-Fausboll", "Danmark", "Søren Hauch-Fausbøll",
"Denmark", "Soren Kierkegaard", "Danmark", "Søren Kierkegård",
"Egypt", "Abdel Halim Hafez", "ﻣﺼﺮ", "ﻋﺑﺪﺍﻠﺣﻟﻳﻢ ﺤﺎﻓﻅ",
"Egypt", "Om Kolthoum", "ﻣﺼﺮ", "ﺃﻡ ﻛﻟﺛﻭﻡ",
"Eritrea", "Berhane Zeray", "ብርሃነ ዘርኣይ", "ኤርትራ",
"Ethiopia", "Haile Gebreselassie", "ኃይሌ ገብረሥላሴ", "ኢትዮጵያ",
"France", "Gerard Depardieu", "France", "Gérard Depardieu",
"France", "Jean Reno", "France", "Jean Réno",
"France", "Camille Saint-Saens", "France", "Camille Saint-Saëns",
"France", "Mylene Demongeot", "France", "Mylène Demongeot",
"France", "Francois Truffaut", "France", "François Truffaut",
"France (Braille)", "Louis Braille", "⠋⠗⠁⠝⠉⠑", "⠇⠕⠥⠊⠎⠀<BR>⠃⠗⠁⠊⠇⠇⠑",
"Georgia", "Eduard Shevardnadze", "საქართველო", "ედუარდ შევარდნაძე",
"Germany", "Rudi Voeller", "Deutschland", "Rudi Völler",
"Germany", "Walter Schultheiss", "Deutschland", "Walter Schultheiß",
"Greece", "Giorgos Dalaras", "Ελλάς", "Γιώργος Νταλάρας",
"Iceland", "Bjork Gudmundsdottir", "Ísland", "Björk Guðmundsdóttir",
"India (Hindi)", "Madhuri Dixit", "भारत", "माधुरी दिछित",
"Ireland", "Sinead O'Connor", "Éire", "Sinéad O'Connor",
"Israel", "Yehoram Gaon", "ישראל", "יהורם גאון",
"Italy", "Fabrizio DeAndre", "Italia", "Fabrizio De André",
"Japan", "KUBOTA Toshinobu", "日本", "久保田 利伸",
"Japan", "HAYASHIBARA Megumi", "日本", "林原 めぐみ",
"Japan", "Mori Ogai", "日本", "森鷗外",
"Japan", "Tex Texin", "日本", "テクス テクサン",
"Norway", "Tor Age Bringsvaerd", "Noreg", "Tor Åge Bringsværd",
"Pakistan (Urdu)", "Nusrat Fatah Ali Khan", "پاکستان", "نصرت فتح علی خان",
"People's Rep. of China", "ZHANG Ziyi", "中国", "章子怡",
"People's Rep. of China", "WONG Faye", "中国", "王菲",
"Poland", "Lech Walesa", "Polska", "Lech Wałęsa",
"Puerto Rico", "Olga Tanon", "Puerto Rico", "Olga Tañón",
"Rep. of China", "Hsu Chi", "臺灣", "舒淇",
"Rep. of China", "Ang Lee", "臺灣", "李安",
"Rep. of Korea", "AHN Sung-Gi", "대한민국", "안성기",
"Rep. of Korea", "SHIM Eun-Ha", "대한민국", "심은하",
"Russia", "Mikhail Gorbachev", "Россия", "Михаил Горбачёв",
"Russia", "Boris Grebenshchikov", "Россия", "Борис Гребенщиков",
"Slovenia", "\"Frane \"\"Jezek\"\" Milcinski", "Slovenija", "Frane Milčinski - Ježek",
"Syracuse (Sicily)", "Archimedes", "Συρακούσα", "Ἀρχιμήδης",
"Thailand", "Thongchai McIntai", "ประเทศไทย", "ธงไชย แม็คอินไตย์",
"U.S.A.", "Brad Pitt", "U.S.A.", "Brad Pitt",
"Yugoslavia (Cyrillic)", "Djordje Balasevic", "Југославија", "Ђорђе Балашевић",
"Yugoslavia (Latin)", "Djordje Balasevic", "Jugoslavija", "Đorđe Balašević"]
i18n_arr = permutedims(reshape(i18n_data, 4, Int(floor(length(i18n_data)/4))), [2, 1])
i18n_buff = PipeBuffer()
writedlm(i18n_buff, i18n_arr, ',')
@test i18n_arr == readdlm(i18n_buff, ',')
hdr = i18n_arr[1:1, :]
data = i18n_arr[2:end, :]
writedlm(i18n_buff, i18n_arr, ',')
@test (data, hdr) == readdlm(i18n_buff, ',', header=true)
writedlm(i18n_buff, i18n_arr, '\t')
@test (data, hdr) == readdlm(i18n_buff, '\t', header=true)
end
end
@testset "issue #13028" begin
for data in ["A B C", "A B C\n"]
data,hdr = readdlm(IOBuffer(data), header=true)
@test hdr == AbstractString["A" "B" "C"]
@test data == Matrix{Float64}(undef, 0, 3)
end
end
# fix #13179 parsing unicode lines with default delmiters
@test isequaldlm(readdlm(IOBuffer("# Should ignore this π\n1\tα\n2\tβ\n"), comments=true), Any[1 "α"; 2 "β"], Any)
# BigInt parser
let data = "1 2 3"
readdlm(IOBuffer(data), ' ', BigInt) == BigInt[1 2 3]
end
@testset "show with MIME types" begin
@test sprint(show, "text/csv", [1 2; 3 4]) == "1,2\n3,4\n"
@test sprint(show, "text/tab-separated-values", [1 2; 3 4]) == "1\t2\n3\t4\n"
for writefunc in ((io,x) -> show(io, "text/csv", x),
(io,x) -> invoke(writedlm, Tuple{IO,Any,Any}, io, x, ","))
# iterable collections of iterable rows:
let x = [(1,2), (3,4)], io = IOBuffer()
writefunc(io, x)
seek(io, 0)
@test readdlm(io, ',') == [1 2; 3 4]
end
# vectors of strings:
let x = ["foo", "bar"], io = IOBuffer()
writefunc(io, x)
seek(io, 0)
@test vec(readdlm(io, ',')) == x
end
end
for writefunc in ((io,x) -> show(io, "text/tab-separated-values", x),
(io,x) -> invoke(writedlm, Tuple{IO,Any,Any}, io, x, "\t"))
# iterable collections of iterable rows:
let x = [(1,2), (3,4)], io = IOBuffer()
writefunc(io, x)
seek(io, 0)
@test readdlm(io, '\t') == [1 2; 3 4]
end
# vectors of strings:
let x = ["foo", "bar"], io = IOBuffer()
writefunc(io, x)
seek(io, 0)
@test vec(readdlm(io, '\t')) == x
end
end
end
# Test that we can read a write protected file
let fn = tempname()
open(fn, "w") do f
write(f, "Julia")
end
chmod(fn, 0o444)
readdlm(fn)[] == "Julia"
rm(fn)
end
# test writedlm with a filename instead of io input
let fn = tempname(), x = ["a" "b"; "d" ""]
writedlm(fn, x, ',')
@test readdlm(fn, ',') == x
rm(fn)
end
# issue #21180
let data = "\"721\",\"1438\",\"1439\",\"…\",\"1\""
@test readdlm(IOBuffer(data), ',') == Any[721 1438 1439 "…" 1]
end
# issue #21207
let data = "\"1\",\"灣\"\"灣灣灣灣\",\"3\""
@test readdlm(IOBuffer(data), ',') == Any[1 "灣\"灣灣灣灣" 3]
end
# reading from a byte array (#16731)
let data = Vector{UInt8}("1,2,3\n4,5,6"), origdata = copy(data)
@test readdlm(data, ',') == [1 2 3; 4 5 6]
@test data == origdata
end
# issue #11484: useful error message for invalid readdlm filepath arguments
@test_throws ArgumentError readdlm(tempdir())
# showing as text/csv
let d = TextDisplay(PipeBuffer())
show(d.io, "text/csv", [3 1 4])
@test read(d.io, String) == "3,1,4\n"
end
@testset "complex" begin
@test readdlm(IOBuffer("3+4im, 4+5im"), ',', Complex{Int}) == [3+4im 4+5im]
end
| DelimitedFiles | https://github.com/JuliaData/DelimitedFiles.jl.git |
|
[
"MIT"
] | 1.9.1 | 9e2f36d3c96a820c678f2f1f1782582fcf685bae | docs | 1066 | # DelimitedFiles
| **Documentation** | **Build Status** |
|:-----------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------:|
| [![][docs-img]][docs-url] | [![][ci-img]][ci-url] [![][codecov-img]][codecov-url] |
[docs-img]: https://img.shields.io/badge/docs-blue.svg
[docs-url]: http://delimitedfiles.juliadata.org/dev/
[docs-v1-img]: https://img.shields.io/badge/docs-v1-blue.svg
[docs-v1-url]: https://julialang.github.io/delimitedfiles/v1/
[ci-img]: https://github.com/JuliaLang/delimitedfiles.jl/workflows/CI/badge.svg?branch=main
[ci-url]: https://github.com/JuliaLang/delimitedfiles.jl/actions?query=workflow%3A%22CI%22
[codecov-img]: https://codecov.io/gh/JuliaLang/delimitedfiles.jl/branch/main/graph/badge.svg
[codecov-url]: https://codecov.io/gh/JuliaLang/delimitedfiles.jl
This package ships as part of the Julia stdlib.
| DelimitedFiles | https://github.com/JuliaData/DelimitedFiles.jl.git |
|
[
"MIT"
] | 1.9.1 | 9e2f36d3c96a820c678f2f1f1782582fcf685bae | docs | 356 | # Delimited Files
```@docs
DelimitedFiles.readdlm(::Any, ::AbstractChar, ::Type, ::AbstractChar)
DelimitedFiles.readdlm(::Any, ::AbstractChar, ::AbstractChar)
DelimitedFiles.readdlm(::Any, ::AbstractChar, ::Type)
DelimitedFiles.readdlm(::Any, ::AbstractChar)
DelimitedFiles.readdlm(::Any, ::Type)
DelimitedFiles.readdlm(::Any)
DelimitedFiles.writedlm
```
| DelimitedFiles | https://github.com/JuliaData/DelimitedFiles.jl.git |
|
[
"MIT"
] | 0.1.0 | 0769fa4e397e5181509fd3f68174574d0a903df4 | code | 390 | using Documenter, AtBackslash
makedocs(;
modules=[AtBackslash],
format=Documenter.HTML(),
pages=[
"Home" => "index.md",
],
repo="https://github.com/tkf/AtBackslash.jl/blob/{commit}{path}#L{line}",
sitename="AtBackslash.jl",
authors="Takafumi Arakaki <[email protected]>",
assets=String[],
)
deploydocs(;
repo="github.com/tkf/AtBackslash.jl",
)
| AtBackslash | https://github.com/tkf/AtBackslash.jl.git |
|
[
"MIT"
] | 0.1.0 | 0769fa4e397e5181509fd3f68174574d0a903df4 | code | 3183 | module AtBackslash
# Use README as the docstring of the module:
@doc let path = joinpath(dirname(@__DIR__), "README.md")
include_dependency(path)
replace(read(path, String), r"^```julia"m => "```jldoctest README")
end AtBackslash
export @\
using Base.Meta: isexpr
function is_interpolation(ex)
isexpr(ex, :$) || return false
if length(ex.args) != 1 || isexpr(ex.args[1], :tuple)
error("Only single-argument \$ is supported. Got: ", ex)
end
return true
end
"""
@\\(NCT1, NTC2, ..., NTCn) :: NamedTuple
@\\(; NCT1, NTC2, ..., NTCn) :: NamedTuple
@\\(expr)
"""
macro \(args...)
@gensym input
replace_symbols(x) = x
replace_symbols(x::QuoteNode) =
if x.value isa Symbol
:($input.$(x.value))
else
x
end
replace_symbols(x::Symbol) =
if x === :_
input
else
esc(x)
end
replace_symbols(ex::Expr) =
if isexpr(ex, :...) && ex.args == [:_]
:($input...)
elseif isexpr(ex, :parameters)
args = map(ex.args) do x
if x isa Symbol
Expr(:(=), esc(x), replace_symbols(x))
elseif x isa QuoteNode && x.value isa Symbol
Expr(:(=), esc(x.value), replace_symbols(x))
else
replace_symbols(x)
end
end
Expr(ex.head, args...)
elseif is_interpolation(ex)
# Should I still replace `_`?
esc(ex.args[1])
elseif isexpr(ex, :.)
Expr(:., replace_symbols(ex.args[1]), ex.args[2:end]...)
elseif isexpr(ex, :macrocall)
esc(ex)
elseif isexpr(ex, :quote)
ex
else
Expr(ex.head, replace_symbols.(ex.args)...)
end
if args == (:_,)
# Should I?
error("`@\\_` not supported. Use `identity`.")
end
#! format: off
if (
length(args) == 1 &&
((args[1] isa QuoteNode && args[1].value isa Symbol) || args[1] isa Symbol)
)
ex, = args
error(
"Ambiguous expression: `@\\($ex)`\n",
"Use `@\\(_.$ex)` if you mean `x -> x.$ex`.\n",
"Use `@\\(; $ex)` if you mean `x -> ($ex = x.$ex,)`.",
)
end
#! format: on
# Handle: @\(_..., a=x+1, b) :: NamedTuple
all(args) do x
(x isa Symbol ||
(x isa QuoteNode && x.value isa Symbol) ||
(is_interpolation(x) && x.args[1] isa Symbol) ||
(isexpr(x, :(=)) && x.args[1] isa Symbol) ||
(isexpr(x, :...) && x.args == [:_]))
end && begin
return :($input -> $(replace_symbols(Expr(:tuple, Expr(:parameters, args...)))))
end
# Handle: @\(; KEY => VAL) :: NamedTuple
if length(args) == 1 && isexpr(args[1], :parameters)
return :($input -> $(replace_symbols(Expr(:tuple, args[1]))))
end
# Handle: @\[a, b] :: Array
# Handle: @\(x > y) :: Bool
if length(args) == 1
return :($input -> $(replace_symbols(args[1])))
end
error("Unsupported expression:\n", "@\\", Expr(:tuple, args...))
end
end # module
| AtBackslash | https://github.com/tkf/AtBackslash.jl.git |
|
[
"MIT"
] | 0.1.0 | 0769fa4e397e5181509fd3f68174574d0a903df4 | code | 5412 | module TestAtBackslash
using AtBackslash: @\, AtBackslash
using Documenter: doctest
using Test: @test, @testset
@testset "All bound" begin
@test (x = 1, y = 2) |> @\(_..., a = :x + :y, y = 10) === (x = 1, y = 10, a = 3)
@test (x = 1, y = 2) |> @\(:y, :x) === (y = 2, x = 1)
@test (x = 1, y = 2) |> @\(:x < :y) === true
@test (x = 1, y = 2) |> @\(:x < :y < 3) === true
@test (x = 1, y = 2) |> @\(:x + 10) == 11
@test (x = 1, y = 2) |> @\(; :x) === (x = 1,)
@test (x = 1, y = 2) |> @\[:x, :y] == [1, 2]
@test (x = 1, y = 2) |> @\[:x :y] == [1 2]
@test (x = 1, y = 2) |> @\[:x :y; :y :x] == [1 2; 2 1]
@test (x = 1, y = 2) |> @\[_] == [(x = 1, y = 2)]
@test (x = 1, y = 2) |> @\[_ _] == [(x = 1, y = 2) (x = 1, y = 2)]
@test (x = 1, y = 2) |> @\[(; :x, :y)] == [(x = 1, y = 2)]
@test (x = 1, y = 2) |> @\[(; x = :x, y = :y)] == [(x = 1, y = 2)]
@test (x = 1, y = 2, name = :x) |> @\(_[:name]) == 1
@test (x = 1, y = 2, name = :x) |> @\(; :name => _[:name] + 10) === (x = 11,)
@test (x = 1, y = 2, name = :x) |> @\((; :name => _[:name] + 10)) === (x = 11,)
@test (x = 1, y = 2, name = :x) |> @\(; :name => _[:name] + 10, :y) === (x = 11, y = 2)
@test (x = 1, y = 2, name = :x) |> @\((; :name => _[:name] + 10, :y)) === (
x = 11,
y = 2,
)
@test (x = 1, y = 2, name = :x) |> @\(; :name => _[:name] + 10, y = :y) === (
x = 11,
y = 2,
)
@test (x = 1, y = 2, name = :x) |> @\((; :name => _[:name] + 10, y = :y)) === (
x = 11,
y = 2,
)
end
struct ObjectProxy
dict::AbstractDict{Symbol}
end
Base.getproperty(obj::ObjectProxy, name::Symbol) = getfield(obj, :dict)[name]
@testset "NonNamedTuple" begin
@test 1 + 2im |> @\(:re, :im) == (re = 1, im = 2)
@test ObjectProxy(Dict(:x => 1)) |> @\(:x, y = :x + 1) == (x = 1, y = 2)
end
@testset "Shadowing" begin
x = :nonlocal
@test (x = 1, y = 2) |> @\[:x, :y] == [1, 2]
@test (x = 1, y = 2) |> @\(_..., a = :x + :y, y = 10) === (x = 1, y = 10, a = 3)
@test (x = 1, y = 2) |> @\(:x, :y) === (x = 1, y = 2)
end
@testset "Free variable" begin
z = 3
@test (x = 1, y = 2) |> @\[:x, :y, z] == [1, 2, 3]
@test (x = 1, y = 2) |> @\(_..., a = :x + :y, y = z) === (x = 1, y = 3, a = 3)
@test (x = 1, y = 2) |> @\(z, :x) === (z = 3, x = 1)
end
@testset "macrocall" begin
z = 3
result = (x = 1, y = 2) |> @\(:x, z = @timed(z))
@test result.x === 1
@test result.z[1] === z
@test result.z[5].total_time isa Number
end
@testset "quote" begin
@test identity |> @\(_(:(x = 1, y = 2))) == :(x = 1, y = 2)
end
@testset "Non-Symbol QuoteNode" begin
ex = :(@\(; x=$(QuoteNode(:(some(expr))))))
@test nothing |> @eval($ex) == (x = :(some(expr)),)
end
@testset "Explicit nonlocal" begin
x = :nonlocal
@test (x = 1, y = 2) |> @\(a = :x, b = x) == (a = 1, b = :nonlocal)
@test (x = 1, y = 2) |> @\(x, :y) == (x = :nonlocal, y = 2)
@test (x = 1, y = 2) |> @\(x = string(x, :y)) == (x = "nonlocal2",)
@test (x = 1, y = 2) |> @\(string(x, :y)) == "nonlocal2"
@test (x = 1, y = 2) |> @\(; x) == (x = :nonlocal,)
@test (x = 1, y = 2) |> @\[x, :y] == [:nonlocal, 2]
end
@testset "Interpolation" begin
x = :nonlocal
@test (x = 1, y = 2) |> @\(a = :x, b = x, c = $:x) == (a = 1, b = :nonlocal, c = :x)
@test (x = 1, y = 2) |> @\(identity(:x)) == 1
@test (x = 1, y = 2) |> @\(identity(x)) == :nonlocal
@test (x = 1, y = 2) |> @\(identity($:x)) == :x
@test (x = 1, y = 2) |> @\($:x) == :x
@test (x = 1, y = 2) |>
@\(merge((; a = $:x), (; :x, y = x))) == (a = :x, x = 1, y = :nonlocal)
end
macro test_error(ex)
quote
let err = nothing
@test try
$(esc(ex))
false
catch err
true
end
err
end
end
end
@testset "Error handling" begin
⊏ = occursin
@testset "@\\ :arg" begin
err = @test_error @eval @\ :arg
@test raw"""
Ambiguous expression: `@\(:arg)`
Use `@\(_.:arg)` if you mean `x -> x.:arg`.
Use `@\(; :arg)` if you mean `x -> (:arg = x.:arg,)`.
""" ⊏ sprint(showerror, err)
end
@testset "@\\ arg" begin
err = @test_error @eval @\ arg
@test raw"""
Ambiguous expression: `@\(arg)`
Use `@\(_.arg)` if you mean `x -> x.arg`.
Use `@\(; arg)` if you mean `x -> (arg = x.arg,)`.
""" ⊏ sprint(showerror, err)
end
@testset "@\\(; \$(f(x)))" begin
ex = :(@\(; $(Expr(:$, :(f(x))))))
err = @test_error @eval $ex
@test "syntax: invalid named tuple element \"f(x)\"" ⊏ sprint(showerror, err)
end
@testset "@\\(; \$(x, y))" begin
ex = :(@\(; $(Expr(:$, :((x, y))))))
err = @test_error @eval $ex
@test "Only single-argument \$ is supported. Got: " ⊏ sprint(showerror, err)
end
@testset "@\\_" begin
ex = :(@\_)
err = @test_error @eval $ex
@test "`@\\_` not supported. Use `identity`." ⊏ sprint(showerror, err)
end
@testset "Unsupported expression" begin
ex = :(@\ import Base import Base)
err = @test_error @eval $ex
@test "Unsupported expression:" ⊏ sprint(showerror, err)
end
end
@testset "doctest" begin
doctest(AtBackslash; manual=false)
end
end # module
| AtBackslash | https://github.com/tkf/AtBackslash.jl.git |
|
[
"MIT"
] | 0.1.0 | 0769fa4e397e5181509fd3f68174574d0a903df4 | docs | 1964 | # AtBackslash
[](https://travis-ci.com/tkf/AtBackslash.jl)
[](https://codecov.io/gh/tkf/AtBackslash.jl)
[](https://coveralls.io/github/tkf/AtBackslash.jl?branch=master)
`AtBackslash` exports a macro `@\` to easily create functions that
work with named tuples as input and/or output.
The symbol literal like `:x` in the tuple argument is expanded to be
the property/field of the named tuple of the input and output:
```julia
julia> using AtBackslash
julia> (x = 1, y = 2, z = 3) |> @\(:x, :y)
(x = 1, y = 2)
```
It also supports normal "verbose" syntax for creating a named tuple:
```julia
julia> (x = 1, y = 2) |> @\(x = :x, y = :y)
(x = 1, y = 2)
```
which is handy when adding new properties:
```julia
julia> (x = 1, y = 2) |> @\(:x, z = :x + :y)
(x = 1, z = 3)
```
The argument can be explicitly referred to by `_`:
```julia
julia> (x = 1, y = 2) |> @\(_..., z = :x + :y)
(x = 1, y = 2, z = 3)
```
```julia
julia> (x = 1, y = 2) |> @\_.x
1
```
```julia
julia> 1 |> @\(x = _, y = 2_)
(x = 1, y = 2)
```
Automatic conversions of `:x` and `(; :x, :y)` work at any level of
expression:
```julia
julia> (x = 1, y = 2) |> @\ merge((; :x, :y), (a = :x, b = :y))
(x = 1, y = 2, a = 1, b = 2)
```
```julia
julia> (x = 1, y = 2) |> @\(:x < :y < 3)
true
```
Use `$:x` to avoid automatic conversion to `_.x`:
```julia
julia> (x = 1, y = 2) |> @\(x = $:x, :y)
(x = :x, y = 2)
```
Use plain names to refer to the variables in the outer scope:
```julia
julia> let z = 3
(x = 1, y = 2) |> @\(:x, :y, z)
end
(x = 1, y = 2, z = 3)
```
The input can be any object that support `getproperty`. For example,
it works with `Complex`:
```julia
julia> 1 + 2im |> @\(:re, :im)
(re = 1, im = 2)
```
| AtBackslash | https://github.com/tkf/AtBackslash.jl.git |
|
[
"MIT"
] | 0.1.0 | 0769fa4e397e5181509fd3f68174574d0a903df4 | docs | 74 | # AtBackslash.jl
```@index
```
```@autodocs
Modules = [AtBackslash]
```
| AtBackslash | https://github.com/tkf/AtBackslash.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 710 | using VectorizedStatistics
using Documenter
DocMeta.setdocmeta!(VectorizedStatistics, :DocTestSetup, :(using VectorizedStatistics); recursive=true)
makedocs(;
modules=[VectorizedStatistics],
authors="C. Brenhin Keller",
repo="https://github.com/brenhinkeller/VectorizedStatistics.jl/blob/{commit}{path}#{line}",
sitename="VectorizedStatistics.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://brenhinkeller.github.io/VectorizedStatistics.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/brenhinkeller/VectorizedStatistics.jl",
devbranch = "main",
)
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 971 | module VectorizedStatistics
using LoopVectorization, Static
import LoopVectorization.vsum # Will add more specific method for ::StridedArray
const IntOrStaticInt = Union{Integer, StaticInt}
_dim(::Type{StaticInt{N}}) where {N} = N::Int
# Dropdims if there are dims to be dropped
reducedims(A, dims) = A
reducedims(A::AbstractVector, dims) = A
reducedims(A::AbstractArray, dims) = dropdims(A; dims)
# Implemented by reduction, recursively
include("vreducibles.jl")
# Implemented with @generated functions, single- and multithreaded
include("vmean.jl")
include("vsum.jl")
include("vvar.jl")
include("vstd.jl")
include("vcov.jl")
# Sorting-based statistics
include("quicksort.jl")
include("argsort.jl")
include("vsort.jl")
include("vmedian.jl")
include("vquantile.jl")
# Fully precompile some commonly-used methods
using PrecompileTools
include("precompile.jl")
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 5629 | # Move all NaNs to the end of the array `A`
function sortnans!(I::AbstractArray, A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A))
# Count up NaNs
Nₙₐₙ = 0
@turbo check_empty=true for i = iₗ:iᵤ
Nₙₐₙ += A[i] != A[i]
end
# If none, return early
Nₙₐₙ == 0 && return I, A, iₗ, iᵤ
# Otherwise, swap all NaNs
i = iₗ
j = iᵤ
N = iᵤ - iₗ
@inbounds for n = 0:N-Nₙₐₙ
i = iₗ + n
if A[i] != A[i]
while A[j] != A[j]
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
I[i], I[j] = I[j], I[i]
j -= 1
end
end
return I, A, iₗ, iᵤ - Nₙₐₙ
end
# For integers, don't need to check for NaNs
sortnans!(I::AbstractArray, A::AbstractArray{<:Integer}, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A)) = I, A, iₗ, iᵤ
# Sort `A`, assuming no NaNs
function quicksort!(I::AbstractArray, A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A))
if issortedrange(A, iₗ, iᵤ)
# If already sorted, we're done here
return I, A
end
# Otherwise, we have to sort
N = iᵤ - iₗ + 1
if isantisortedrange(A, iₗ, iᵤ)
vreverse!(A, iₗ, iᵤ)
vreverse!(I, iₗ, iᵤ)
return I, A
elseif N == 3
# We know we are neither sorted nor antisorted, so only four possibilities remain
iₘ = iₗ + 1
a,b,c = A[iₗ], A[iₘ], A[iᵤ]
if a <= b
if a <= c
A[iₘ], A[iᵤ] = c, b # a ≤ c ≤ b
I[iₘ], I[iᵤ] = I[iᵤ], I[iₘ]
else
A[iₗ], A[iₘ], A[iᵤ] = c, a, b # c ≤ a ≤ b
I[iₗ], I[iₘ], I[iᵤ] = I[iᵤ], I[iₗ], I[iₘ]
end
else
if a <= c
A[iₗ], A[iₘ] = b, a # b ≤ a ≤ c
I[iₗ], I[iₘ] = I[iₘ], I[iₗ]
else
A[iₗ], A[iₘ], A[iᵤ] = b, c, a # b ≤ c ≤ a
I[iₗ], I[iₘ], I[iᵤ] = I[iₘ], I[iᵤ], I[iₗ]
end
end
return I, A
else
# Pick a pivot for partitioning
iₚ = iₗ + (N >> 2)
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
I[iₗ], I[iₚ] = I[iₚ], I[iₗ]
pivot = A[iₗ]
# Count up elements that must be moved to upper partition
Nᵤ = 0
@turbo for i = (iₗ+1):iᵤ
Nᵤ += A[i] >= pivot
end
Nₗ = N - Nᵤ
# Swap elements between upper and lower partitions
i = iₗ
j = iᵤ
@inbounds for n = 1:Nₗ-1
i = iₗ + n
if A[i] >= pivot
while A[j] >= pivot
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
I[i], I[j] = I[j], I[i]
j -= 1
end
end
# Move pivot to the top of the lower partition
iₚ = iₗ + Nₗ - 1
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
I[iₗ], I[iₚ] = I[iₚ], I[iₗ]
# Recurse: sort both upper and lower partitions
quicksort!(I, A, iₗ, iₚ)
quicksort!(I, A, iₚ+1, iᵤ)
end
end
# Sort `A`, assuming no NaNs, multithreaded
function quicksortt!(I::AbstractArray, A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A), level=1)
if issortedrange(A, iₗ, iᵤ)
# If already sorted, we're done here
return I, A
end
# Otherwise, we have to sort
N = iᵤ - iₗ + 1
if isantisortedrange(A, iₗ, iᵤ)
vreverse!(A, iₗ, iᵤ)
vreverse!(I, iₗ, iᵤ)
return I, A
elseif N == 3
# We know we are neither sorted nor antisorted, so only four possibilities remain
iₘ = iₗ + 1
a,b,c = A[iₗ], A[iₘ], A[iᵤ]
if a <= b
if a <= c
A[iₘ], A[iᵤ] = c, b # a ≤ c ≤ b
I[iₘ], I[iᵤ] = I[iᵤ], I[iₘ]
else
A[iₗ], A[iₘ], A[iᵤ] = c, a, b # c ≤ a ≤ b
I[iₗ], I[iₘ], I[iᵤ] = I[iᵤ], I[iₗ], I[iₘ]
end
else
if a <= c
A[iₗ], A[iₘ] = b, a # b ≤ a ≤ c
I[iₗ], I[iₘ] = I[iₘ], I[iₗ]
else
A[iₗ], A[iₘ], A[iᵤ] = b, c, a # b ≤ c ≤ a
I[iₗ], I[iₘ], I[iᵤ] = I[iₘ], I[iᵤ], I[iₗ]
end
end
return I, A
else
# Pick a pivot for partitioning
iₚ = iₗ + (N >> 2)
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
I[iₗ], I[iₚ] = I[iₚ], I[iₗ]
pivot = A[iₗ]
# Count up elements that must be moved to upper partition
Nᵤ = 0
@turbo for i = (iₗ+1):iᵤ
Nᵤ += A[i] >= pivot
end
Nₗ = N - Nᵤ
# Swap elements between upper and lower partitions
i = iₗ
j = iᵤ
@inbounds for n = 1:Nₗ-1
i = iₗ + n
if A[i] >= pivot
while A[j] >= pivot
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
I[i], I[j] = I[j], I[i]
j -= 1
end
end
# Move pivot to the top of the lower partition
iₚ = iₗ + Nₗ - 1
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
I[iₗ], I[iₚ] = I[iₚ], I[iₗ]
# Recurse: sort both upper and lower partitions
if level < 7
@sync begin
Threads.@spawn quicksortt!(I, A, iₗ, iₚ, level+1)
Threads.@spawn quicksortt!(I, A, iₚ+1, iᵤ, level+1)
end
else
quicksort!(I, A, iₗ, iₚ)
quicksort!(I, A, iₚ+1, iᵤ)
end
return I, A
end
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 1449 | @setup_workload begin
maxdims = 2
@compile_workload begin
for T in (Float64,)
for nd in 1:maxdims
A = ones(T, ntuple(i->10, nd))
vsum(A)
vmean(A)
vstd(A)
vvar(A)
vminimum(A)
vmaximum(A)
if nd > 1
for d in 1:nd
vsum(A, dims=d)
vmean(A, dims=d)
vstd(A, dims=d)
vvar(A, dims=d)
vminimum(A, dims=d)
vmaximum(A, dims=d)
end
# for i = 2:nd
# for j = 1:i-1
# vsum(A, dims=(j,i))
# vmean(A, dims=(j,i))
# vstd(A, dims=(j,i))
# vvar(A, dims=(j,i))
# vminimum(A, dims=(j,i))
# vmaximum(A, dims=(j,i))
# end
# end
end
end
end
for T in (Int,)
for nd in 1:maxdims
A = ones(T, ntuple(i->10, nd))
vsum(A)
vmean(A)
vstd(A)
vvar(A)
vminimum(A)
vmaximum(A)
end
end
end
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 7000 |
# Check for sortedness, assuming no NaNs
@inline function issortedrange(A::AbstractArray, iₗ, iᵤ)
@inbounds for i = iₗ+1:iᵤ
if A[i-1] > A[i]
return false
end
end
return true
end
# Check for anti-sortedness, assuming no NaNs
@inline function isantisortedrange(A::AbstractArray, iₗ, iᵤ)
@inbounds for i = iₗ+1:iᵤ
if A[i-1] < A[i]
return false
end
end
return true
end
# Reverse an array, faster than Base.reverse!
@inline function vreverse!(A::AbstractArray, iₗ, iᵤ)
N = (iᵤ - iₗ) + 1
n = (N ÷ 2) - 1
if N < 32
@inbounds for i ∈ 0:n
𝔦ₗ, 𝔦ᵤ = iₗ+i, iᵤ-i
A[𝔦ₗ], A[𝔦ᵤ] = A[𝔦ᵤ], A[𝔦ₗ]
end
else
@turbo for i ∈ 0:n
𝔦ₗ = iₗ+i
𝔦ᵤ = iᵤ-i
l = A[𝔦ₗ]
u = A[𝔦ᵤ]
A[𝔦ₗ] = u
A[𝔦ᵤ] = l
end
end
return A
end
# Move all NaNs to the end of the array `A`
function sortnans!(A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A))
# Count up NaNs
Nₙₐₙ = 0
@turbo check_empty=true for i = iₗ:iᵤ
Nₙₐₙ += A[i] != A[i]
end
# If none, return early
Nₙₐₙ == 0 && return A, iₗ, iᵤ
# Otherwise, swap all NaNs
i = iₗ
j = iᵤ
N = iᵤ - iₗ
@inbounds for n = 0:N-Nₙₐₙ
i = iₗ + n
if A[i] != A[i]
while A[j] != A[j]
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
j -= 1
end
end
return A, iₗ, iᵤ - Nₙₐₙ
end
# For integers, don't need to check for NaNs
sortnans!(A::AbstractArray{<:Integer}, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A)) = A, iₗ, iᵤ
# Partially sort `A` around the `k`th sorted element and return that element
function quickselect!(A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A), k=(iₗ+iᵤ)÷2)
# Fall back to Base implementation for very large arrays
if iᵤ-iₗ > 20000
return Base.Sort.partialsort!(view(A, iₗ:iᵤ), k-(iₗ-1))
end
# Pick a pivot for partitioning
N = iᵤ - iₗ + 1
A[iₗ], A[k] = A[k], A[iₗ]
pivot = A[iₗ]
# Count up elements that must be moved to upper partition
Nᵤ = 0
@turbo check_empty=true for i = (iₗ+1):iᵤ
Nᵤ += A[i] >= pivot
end
Nₗ = N - Nᵤ
# Swap elements between upper and lower partitions
i = iₗ
j = iᵤ
@inbounds for n = 1:Nₗ-1
i = iₗ + n
if A[i] >= pivot
while A[j] >= pivot
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
j -= 1
end
end
# Move pivot to the top of the lower partition
iₚ = iₗ + Nₗ - 1
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
# Recurse: select from partition containing k
if iₚ==k
return A[k]
elseif k < iₚ
Nₗ == 2 && return A[iₗ]
quickselect!(A, iₗ, iₚ, k)
else
Nᵤ == 2 && return A[iᵤ]
quickselect!(A, iₚ+1, iᵤ, k)
end
end
# Sort `A`, assuming no NaNs
function quicksort!(A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A))
if issortedrange(A, iₗ, iᵤ)
# If already sorted, we're done here
return A
end
# Otherwise, we have to sort
N = iᵤ - iₗ + 1
if isantisortedrange(A, iₗ, iᵤ)
vreverse!(A, iₗ, iᵤ)
return A
elseif N == 3
# We know we are neither sorted nor antisorted, so only four possibilities remain
iₘ = iₗ + 1
a,b,c = A[iₗ], A[iₘ], A[iᵤ]
if a <= b
if a <= c
A[iₘ], A[iᵤ] = c, b # a ≤ c ≤ b
else
A[iₗ], A[iₘ], A[iᵤ] = c, a, b # c ≤ a ≤ b
end
else
if a <= c
A[iₗ], A[iₘ] = b, a # b ≤ a ≤ c
else
A[iₗ], A[iₘ], A[iᵤ] = b, c, a # b ≤ c ≤ a
end
end
return A
else
# Pick a pivot for partitioning
iₚ = iₗ + (N >> 2)
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
pivot = A[iₗ]
# Count up elements that must be moved to upper partition
Nᵤ = 0
@turbo for i = (iₗ+1):iᵤ
Nᵤ += A[i] >= pivot
end
Nₗ = N - Nᵤ
# Swap elements between upper and lower partitions
i = iₗ
j = iᵤ
@inbounds for n = 1:Nₗ-1
i = iₗ + n
if A[i] >= pivot
while A[j] >= pivot
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
j -= 1
end
end
# Move pivot to the top of the lower partition
iₚ = iₗ + Nₗ - 1
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
# Recurse: sort both upper and lower partitions
quicksort!(A, iₗ, iₚ)
quicksort!(A, iₚ+1, iᵤ)
end
end
# Sort `A`, assuming no NaNs, multithreaded
function quicksortt!(A::AbstractArray, iₗ::Int=firstindex(A), iᵤ::Int=lastindex(A), level=1)
if issortedrange(A, iₗ, iᵤ)
# If already sorted, we're done here
return A
end
# Otherwise, we have to sort
N = iᵤ - iₗ + 1
if isantisortedrange(A, iₗ, iᵤ)
vreverse!(A, iₗ, iᵤ)
return A
elseif N == 3
# We know we are neither sorted nor antisorted, so only four possibilities remain
iₘ = iₗ + 1
a,b,c = A[iₗ], A[iₘ], A[iᵤ]
if a <= b
if a <= c
A[iₘ], A[iᵤ] = c, b # a ≤ c ≤ b
else
A[iₗ], A[iₘ], A[iᵤ] = c, a, b # c ≤ a ≤ b
end
else
if a <= c
A[iₗ], A[iₘ] = b, a # b ≤ a ≤ c
else
A[iₗ], A[iₘ], A[iᵤ] = b, c, a # b ≤ c ≤ a
end
end
return A
else
# Pick a pivot for partitioning
iₚ = iₗ + (N >> 2)
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
pivot = A[iₗ]
# Count up elements that must be moved to upper partition
Nᵤ = 0
@turbo for i = (iₗ+1):iᵤ
Nᵤ += A[i] >= pivot
end
Nₗ = N - Nᵤ
# Swap elements between upper and lower partitions
i = iₗ
j = iᵤ
@inbounds for n = 1:Nₗ-1
i = iₗ + n
if A[i] >= pivot
while A[j] >= pivot
j -= 1
end
j <= i && break
A[i], A[j] = A[j], A[i]
j -= 1
end
end
# Move pivot to the top of the lower partition
iₚ = iₗ + Nₗ - 1
A[iₗ], A[iₚ] = A[iₚ], A[iₗ]
# Recurse: sort both upper and lower partitions
if level < 7
@sync begin
Threads.@spawn quicksortt!(A, iₗ, iₚ, level+1)
Threads.@spawn quicksortt!(A, iₚ+1, iᵤ, level+1)
end
else
quicksort!(A, iₗ, iₚ)
quicksort!(A, iₚ+1, iᵤ)
end
return A
end
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 7397 | function _vcov(x::AbstractVector, y::AbstractVector, corrected::Bool, μᵪ::Number, μᵧ::Number, multithreaded::False)
# Calculate covariance
σᵪᵧ = zero(promote_type(typeof(μᵪ), typeof(μᵧ), Int))
@turbo check_empty=true for i ∈ indices((x,y))
δᵪ = x[i] - μᵪ
δᵧ = y[i] - μᵧ
σᵪᵧ += δᵪ * δᵧ
end
σᵪᵧ = σᵪᵧ / (length(x)-corrected)
return σᵪᵧ
end
function _vcov(x::AbstractVector, y::AbstractVector, corrected::Bool, μᵪ::Number, μᵧ::Number, multithreaded::True)
# Calculate covariance
σᵪᵧ = zero(promote_type(typeof(μᵪ), typeof(μᵧ), Int))
@tturbo check_empty=true for i ∈ indices((x,y))
δᵪ = x[i] - μᵪ
δᵧ = y[i] - μᵧ
σᵪᵧ += δᵪ * δᵧ
end
σᵪᵧ = σᵪᵧ / (length(x)-corrected)
return σᵪᵧ
end
"""
```julia
vcov(x::AbstractVector, y::AbstractVector; corrected::Bool=true, multithreaded=false)
```
Compute the covariance between the vectors `x` and `y`.
As `Statistics.cov`, but vectorized and (optionally) multithreaded.
If `corrected` is `true` as is the default, _Bessel's correction_ will be applied,
such that the sum is scaled by `n-1` rather than `n`, where `n = length(x)`.
"""
vcov(x::AbstractVector, y::AbstractVector; corrected::Bool=true, multithreaded=False()) = _vcov(x, y, corrected, multithreaded)
_vcov(x::AbstractVector, y::AbstractVector, corrected, multithreaded::Symbol) = _vcov(x, y, corrected, (multithreaded==:auto && length(x) > 4095) ? True() : False())
_vcov(x::AbstractVector, y::AbstractVector, corrected, multithreaded::Bool) = _vcov(x, y, corrected, static(multithreaded))
function _vcov(x::AbstractVector, y::AbstractVector, corrected::Bool, multithreaded::StaticBool)
# Check lengths
nᵪ = length(x)
nᵧ = length(y)
@assert nᵪ == nᵧ
μᵪ = _vmean(x, :, multithreaded)
μᵧ = _vmean(y, :, multithreaded)
σᵪᵧ = _vcov(x, y, corrected, μᵪ, μᵧ, multithreaded)
return σᵪᵧ
end
"""
```julia
vcov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true, multithreaded=false)
```
Compute the covariance matrix of the matrix `X`, along dimension `dims`.
As `Statistics.cov`, but vectorized and (optionally) multithreaded.
If `corrected` is `true` as is the default, _Bessel's correction_ will be applied,
such that the sum is scaled by `n-1` rather than `n`, where `n = length(x)`.
"""
vcov(X::AbstractMatrix; dims::Int=1, corrected::Bool=true, multithreaded=False()) = _vcov(X, dims, corrected, multithreaded)
export vcov
_vcov(X::AbstractMatrix, dims, corrected, multithreaded::Symbol) = _vcov(X, dims, corrected, (multithreaded===:auto && size(X,1) > 4095) ? True() : False())
_vcov(X::AbstractMatrix, dims, corrected, multithreaded::Bool) = _vcov(X, dims, corrected, static(multithreaded))
function _vcov(X, dims, corrected, multithreaded::StaticBool)
Tₒ = Base.promote_op(/, eltype(X), Int)
n = size(X, dims)
m = size(X, mod(dims,2)+1)
Σ = similar(X, Tₒ, (m, m))
# Only two dimensions are possible, so handle each manually
if dims == 1
# Precalculate means for each column
μ = ntuple(m) do d
_vmean(view(X,:,d),:,multithreaded)
end
# Fill covariance matrix symmetrically
@inbounds for i = 1:m
for j = 1:i
σᵢⱼ = _vcov(view(X,:,i), view(X,:,j), corrected, μ[i], μ[j], multithreaded)
Σ[i,j] = Σ[j,i] = σᵢⱼ
end
end
elseif dims == 2
# Precalculate means for each row
μ = ntuple(m) do d
_vmean(view(X,d,:),:,True())
end
# Fill covariance matrix symmetrically
@inbounds for i = 1:m
for j = 1:i
σᵢⱼ = _vcov(view(X,i,:), view(X,j,:), corrected, μ[i], μ[j], multithreaded)
Σ[i,j] = Σ[j,i] = σᵢⱼ
end
end
else
throw("Dimension not in range")
end
return Σ
end
"""
```julia
vcor(x::AbstractVector, y::AbstractVector, multithreaded=false)
```
Compute the (Pearson's product-moment) correlation between the vectors `x` and `y`.
As `Statistics.cor`, but vectorized and (optionally) multithreaded.
Equivalent to `cov(x,y) / (std(x) * std(y))`.
"""
vcor(x::AbstractVector, y::AbstractVector; corrected::Bool=true, multithreaded=False()) = _vcor(x, y, corrected, multithreaded)
_vcor(x::AbstractVector, y::AbstractVector, corrected, multithreaded::Symbol) = _vcor(x, y, corrected, (multithreaded===:auto && length(x) > 4095) ? True() : False())
_vcor(x::AbstractVector, y::AbstractVector, corrected, multithreaded::Bool) = _vcor(x, y, corrected, static(multithreaded))
function _vcor(x::AbstractVector, y::AbstractVector, corrected::Bool, multithreaded::StaticBool)
# Check lengths
nᵪ = length(x)
nᵧ = length(y)
@assert nᵪ == nᵧ
μᵪ = _vmean(x, :, multithreaded)
μᵧ = _vmean(y, :, multithreaded)
σᵪ = _vstd(μᵪ, corrected, x, :, multithreaded)
σᵧ = _vstd(μᵧ, corrected, y, :, multithreaded)
σᵪᵧ = _vcov(x, y, corrected, μᵪ, μᵧ, multithreaded)
ρᵪᵧ = σᵪᵧ / (σᵪ * σᵧ)
return ρᵪᵧ
end
"""
```julia
vcor(X::AbstractMatrix; dims::Int=1, multithreaded=false)
```
Compute the (Pearson's product-moment) correlation matrix of the matrix `X`,
along dimension `dims`. As `Statistics.cor`, but vectorized and (optionally)
multithreaded.
"""
vcor(X::AbstractMatrix; dims::Int=1, corrected::Bool=true, multithreaded=False()) = _vcor(X, dims, corrected, multithreaded)
export vcor
_vcor(X::AbstractMatrix, dims, corrected, multithreaded::Symbol) = _vcor(X, dims, corrected, (multithreaded===:auto && size(X,1) > 4095) ? True() : False())
_vcor(X::AbstractMatrix, dims, corrected, multithreaded::Bool) = _vcor(X, dims, corrected, static(multithreaded))
@inline function __vcor(X, dims, corrected, multithreaded::StaticBool, axm)
Tₒ = Base.promote_op(/, eltype(X), Int)
Ρ = similar(X, Tₒ, (axm, axm))
# Diagonal must be unity
@inbounds for i = axm
Ρ[i,i] = one(Tₒ)
end
# Only two dimensions are possible, so handle each manually
if dims == 1
# Precalculate means and standard deviations
# using a map may preserve static sizes
μcol = map(d -> _vmean(view(X,:,d), :, multithreaded), axm)
σcol = map(d -> _vstd(μcol[d], corrected, view(X,:,d), :, multithreaded), axm)
# Fill off-diagonals symmetrically
@inbounds for i = axm
for j = 1:i-1
σᵢⱼ = _vcov(view(X,:,i), view(X,:,j), corrected, μcol[i], μcol[j], multithreaded)
Ρ[i,j] = Ρ[j,i] = σᵢⱼ / (σcol[i] * σcol[j])
end
end
elseif dims == 2
# Precalculate means and standard deviations
μrow = map(d -> _vmean(view(X,d,:), :, multithreaded), axm)
σrow = map(d -> _vstd(μrow[d], corrected, view(X,d,:), :, multithreaded), axm)
@inbounds for i = axm
for j = 1:i-1
σᵢⱼ = _vcov(view(X,i,:), view(X,j,:), corrected, μrow[i], μrow[j], multithreaded)
Ρ[i,j] = Ρ[j,i] = σᵢⱼ / (σrow[i] * σrow[j])
end
end
else
throw("Dimension not in range")
end
return Ρ
end
Base.@constprop :aggressive function _vcor(X, dims, corrected, multithreaded::StaticBool)
Base.require_one_based_indexing(X)
axm = axes(X)[(2,1)[dims]]
# function barrier, in case axm is not type-inferred
__vcor(X, dims, corrected, multithreaded::StaticBool, axm)
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 9196 | """
```julia
vmean(A; dims, multithreaded=false)
```
Compute the mean of all elements in `A`, optionally over dimensions specified by `dims`.
As `Statistics.mean`, but vectorized and (optionally) multithreaded.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> vmean(A, dims=1)
1×2 Matrix{Float64}:
2.0 3.0
julia> vmean(A, dims=2)
2×1 Matrix{Float64}:
1.5
3.5
```
"""
vmean(A; dim=:, dims=:, multithreaded=False()) = _vmean(A, dim, dims, multithreaded)
_vmean(A, ::Colon, ::Colon, multithreaded) = _vmean(A, :, multithreaded)
_vmean(A, ::Colon, region, multithreaded) = _vmean(A, region, multithreaded)
_vmean(A, region, ::Colon, multithreaded) = reducedims(_vmean(A, region, multithreaded), region)
export vmean
_vmean(A, dims, multithreaded::Symbol) = _vmean(A, dims, (multithreaded===:auto && length(A) > 4095) ? True() : False())
_vmean(A, dims, multithreaded::Bool) = _vmean(A, dims, static(multithreaded))
# Reduce one dim
_vmean(A, dims::Int, multithreaded::StaticBool) = _vmean(A, (dims,), multithreaded)
# Reduce some dims
function _vmean(A::AbstractArray{T,N}, dims::Tuple, multithreaded::StaticBool) where {T,N}
sᵢ = size(A)
sₒ = ntuple(Val{N}()) do d
ifelse(d ∈ dims, 1, sᵢ[d])
end
Tₒ = Base.promote_op(/, T, Int)
B = similar(A, Tₒ, sₒ)
_vmean!(B, A, dims, multithreaded)
end
## Singlethreaded implementation
# Reduce all the dims!
function _vmean(A, ::Colon, multithreaded::False)
# Promote type of accumulator to avoid overflow
Tₒ = Base.promote_op(/, eltype(A), Int)
Σ = zero(Tₒ)
@turbo check_empty=true for i ∈ eachindex(A)
Σ += A[i]
end
return Σ / length(A)
end
# Chris Elrod metaprogramming magic:
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_mean_quote(static_dims::Vector{Int}, N::Int, multithreaded::Type{False})
M = length(static_dims)
# `static_dims` now contains every dim we're taking the mean over.
Bᵥ = Expr(:call, :view, :B)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(A[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
len = Expr(:call, :*)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
push!(Aind.args, ind)
if n ∈ static_dims
push!(reduct_inds, n)
push!(Bᵥ.args, :(firstindex(B,$n)))
push!(len.args, :(size(A, $n)))
else
push!(nonreduct_inds, n)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Σ = zero(eltype(Bᵥ))))
# Build the reduction loop
for n ∈ reduct_inds
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Push more things here if you want them at the end of the reduction loop
push!(rblock.args, :($Bind = Σ * invdenom))
# Put it all together
return quote
invdenom = inv($len)
Bᵥ = $Bᵥ
@turbo $loops
return B
end
else
firstn = first(reduct_inds)
# Build the reduction loop
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = axes(A,$firstn)), block)
if length(reduct_inds) > 1
for n ∈ @view(reduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Put it all together
return quote
invdenom = inv($len)
Bᵥ = $Bᵥ
Σ = zero(eltype(Bᵥ))
@turbo $loops
Bᵥ[] = Σ * invdenom
return B
end
end
end
## As above, but multithreaded
# Reduce all the dims!
function _vmean(A, ::Colon, multithreaded::True)
# Promote type of accumulator to avoid overflow
Tₒ = Base.promote_op(/, eltype(A), Int)
Σ = zero(Tₒ)
@tturbo check_empty=true for i ∈ eachindex(A)
Σ += A[i]
end
return Σ / length(A)
end
# Chris Elrod metaprogramming magic:
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_mean_quote(static_dims::Vector{Int}, N::Int, multithreaded::Type{True})
M = length(static_dims)
# `static_dims` now contains every dim we're taking the mean over.
Bᵥ = Expr(:call, :view, :B)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(A[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
len = Expr(:call, :*)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
push!(Aind.args, ind)
if n ∈ static_dims
push!(reduct_inds, n)
push!(Bᵥ.args, :(firstindex(B,$n)))
push!(len.args, :(size(A, $n)))
else
push!(nonreduct_inds, n)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Σ = zero(eltype(Bᵥ))))
# Build the reduction loop
for n ∈ reduct_inds
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Push more things here if you want them at the end of the reduction loop
push!(rblock.args, :($Bind = Σ * invdenom))
# Put it all together
return quote
invdenom = inv($len)
Bᵥ = $Bᵥ
@tturbo $loops
return B
end
else
firstn = first(reduct_inds)
# Build the reduction loop
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = axes(A,$firstn)), block)
if length(reduct_inds) > 1
for n ∈ @view(reduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Put it all together
return quote
invdenom = inv($len)
Bᵥ = $Bᵥ
Σ = zero(eltype(Bᵥ))
@tturbo $loops
Bᵥ[] = Σ * invdenom
return B
end
end
end
## --- @generated functions to handle all the possible branches
# Chris Elrod metaprogramming magic:
# Turn non-static integers in `dims` tuple into `StaticInt`s
# so we can construct `static_dims` vector within @generated code
function branches_mean_quote(N::Int, M::Int, D, multithreaded)
static_dims = Int[]
for m ∈ 1:M
param = D.parameters[m]
if param <: StaticInt
new_dim = _dim(param)::Int
@assert new_dim ∉ static_dims
push!(static_dims, new_dim)
else
t = Expr(:tuple)
for n ∈ static_dims
push!(t.args, :(StaticInt{$n}()))
end
q = Expr(:block, :(dimm = dims[$m]))
qold = q
ifsym = :if
for n ∈ 1:N
n ∈ static_dims && continue
tc = copy(t)
push!(tc.args, :(StaticInt{$n}()))
qnew = Expr(ifsym, :(dimm == $n), :(return _vmean!(B, A, $tc, multithreaded)))
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, qnew)
qold = qnew
ifsym = :elseif
end
# Else, if dimm ∉ 1:N, drop it from list and continue
tc = copy(t)
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, Expr(:block, :(return _vmean!(B, A, $tc, multithreaded))))
return q
end
end
return staticdim_mean_quote(static_dims, N, multithreaded)
end
# Efficient @generated in-place mean
@generated function _vmean!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, dims::D, multithreaded) where {Tₒ,T,N,M,D<:Tuple{Vararg{IntOrStaticInt,M}}}
branches_mean_quote(N, M, D, multithreaded)
end
@generated function _vmean!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, dims::Tuple{}, multithreaded) where {Tₒ,T,N}
:(copyto!(B, A); return B)
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 5857 | """
```julia
vmedian!(A; dims)
```
Compute the median of all elements in `A`, optionally over dimensions specified by `dims`.
As `Statistics.median!`, but slightly vectorized and supporting the `dims` keyword.
Be aware that, like `Statistics.median!`, this function modifies `A`, sorting or
partially sorting the contents thereof (specifically, along the dimensions specified
by `dims`, using either `quicksort!` or `quickselect!` around the median
depending on the size of the array). Do not use this function if you do not want
the contents of `A` to be rearranged.
If reducing over multiple `dims`, these dimensions must be contiguous (i.e.
`dims=(2,3)` but not `dims=(1,3)`). Note also that specifying `dims` other than
`:` creates `view`s, with some nonzero performance cost.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> vmedian!(A, dims=1)
1×3 Matrix{Float64}:
4.0 5.0 6.0
julia> vmedian!(A, dims=2)
3×1 Matrix{Float64}:
2.0
5.0
8.0
julia> vmedian!(A)
5.0
julia> A # Note that the array has been sorted
3×3 Matrix{Int64}:
1 4 7
2 5 8
3 6 9
```
"""
vmedian!(A; dim=:, dims=:) = _vmedian!(A, dim, dims)
_vmedian!(A, ::Colon, ::Colon) = _vmedian!(A, :)
_vmedian!(A, ::Colon, region) = _vmedian!(A, region)
_vmedian!(A, region, ::Colon) = reducedims(_vmedian!(A, region), region)
export vmedian!
vmedian(A; kwargs...) = vmedian!(copy(A); kwargs...)
export vmedian
# Reduce one dim
_vmedian!(A, dims::Int) = _vmedian!(A, (dims,))
# Reduce some dims
function _vmedian!(A::AbstractArray{T,N}, dims::Tuple) where {T,N}
iscontiguous(dims) || error("Only continuous `dims` are currently supported")
sᵢ = size(A)
sₒ = ntuple(Val{N}()) do d
ifelse(d ∈ dims, 1, sᵢ[d])
end
Tₒ = Base.promote_op(/, T, Int)
B = similar(A, Tₒ, sₒ)
_vmedian!(B, A, dims)
end
# Reduce all the dims!
_vmedian!(A, ::Tuple{Colon}) = _vmedian!(A, :)
function _vmedian!(A, ::Colon)
iₗ, iᵤ = firstindex(A), lastindex(A)
A, iₗ, iᵤ₋ = sortnans!(A, iₗ, iᵤ)
if iᵤ₋ < iᵤ
# Remove this if we'd rather ignore NaNs
return A[iᵤ]
end
N = iᵤ - iₗ + 1
i½ = (iₗ + iᵤ) ÷ 2
if iseven(N)
if N < 384
quicksort!(A, iₗ, iᵤ)
else
quickselect!(A, iₗ, iᵤ, i½)
quickselect!(A, i½+1, iᵤ, i½+1)
end
return (A[i½] + A[i½+1]) / 2
else
if N < 192
quicksort!(A, iₗ, iᵤ)
else
quickselect!(A, iₗ, iᵤ, i½)
end
return A[i½] / 1
end
end
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_median_quote(static_dims::Vector{Int}, N::Int)
M = length(static_dims)
# `static_dims` now contains every dim we're taking the median over.
Bᵥ = Expr(:call, :view, :B)
Aᵥ = Expr(:call, :view, :A)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(Aᵥ[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
if n ∈ static_dims
push!(reduct_inds, n)
push!(Aᵥ.args, :)
push!(Bᵥ.args, :(firstindex(B,$n)))
else
push!(nonreduct_inds, n)
push!(Aᵥ.args, ind)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Aᵥ = $Aᵥ))
push!(rblock.args, :($Bind = _vmedian!(Aᵥ, :)))
# Put it all together
return quote
Bᵥ = $Bᵥ
@inbounds $loops
return B
end
else
return quote
Bᵥ = $Bᵥ
Bᵥ[] = _vmedian!(A, :)
return B
end
end
end
# Chris Elrod metaprogramming magic:
# Turn non-static integers in `dims` tuple into `StaticInt`s
# so we can construct `static_dims` vector within @generated code
function branches_median_quote(N::Int, M::Int, D)
static_dims = Int[]
for m ∈ 1:M
param = D.parameters[m]
if param <: StaticInt
new_dim = _dim(param)::Int
@assert new_dim ∉ static_dims
push!(static_dims, new_dim)
else
t = Expr(:tuple)
for n ∈ static_dims
push!(t.args, :(StaticInt{$n}()))
end
q = Expr(:block, :(dimm = dims[$m]))
qold = q
ifsym = :if
for n ∈ 1:N
n ∈ static_dims && continue
tc = copy(t)
push!(tc.args, :(StaticInt{$n}()))
qnew = Expr(ifsym, :(dimm == $n), :(return _vmedian!(B, A, $tc)))
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, qnew)
qold = qnew
ifsym = :elseif
end
# Else, if dimm ∉ 1:N, drop it from list and continue
tc = copy(t)
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, Expr(:block, :(return _vmedian!(B, A, $tc))))
return q
end
end
return staticdim_median_quote(static_dims, N)
end
# Efficient @generated in-place median
@generated function _vmedian!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, dims::D) where {Tₒ,T,N,M,D<:Tuple{Vararg{IntOrStaticInt,M}}}
branches_median_quote(N, M, D)
end
@generated function _vmedian!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, dims::Tuple{}) where {Tₒ,T,N}
:(copyto!(B, A); return B)
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 7364 | """
```julia
vpercentile!(A, p; dims)
```
Compute the `p`th percentile (where `p ∈ [0,100]`) of all elements in `A`,
optionally over dimensions specified by `dims`.
As `StatsBase.percentile`, but in-place, slightly vectorized, and supporting the `dims` keyword.
Be aware that, like `Statistics.median!`, this function modifies `A`, sorting or
partially sorting the contents thereof (specifically, along the dimensions specified
by `dims`, using either `quicksort!` or `quickselect!` depending on the size
of the array). Do not use this function if you do not want the contents of `A`
to be rearranged.
If reducing over multiple `dims`, these dimensions must be contiguous (i.e.
`dims=(2,3)` but not `dims=(1,3)`). Note also that specifying `dims` other than
`:` creates `view`s, with some nonzero performance cost.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> vpercentile!(A, 50, dims=1)
1×3 Matrix{Float64}:
4.0 5.0 6.0
julia> vpercentile!(A, 50, dims=2)
3×1 Matrix{Float64}:
2.0
5.0
8.0
julia> vpercentile!(A, 50)
5.0
julia> A # Note that the array has been sorted
3×3 Matrix{Int64}:
1 4 7
2 5 8
3 6 9
```
"""
vpercentile!(A, p::Number; dim=:, dims=:) = _vquantile!(A, p/100, dim, dims)
export vpercentile!
vpercentile(A, p; kwargs...) = vpercentile!(copy(A), p; kwargs...)
export vpercentile
"""
```julia
vquantile!(A, q; dims)
```
Compute the `q`th quantile (where `q ∈ [0,1]`) of all elements in `A`,
optionally over dimensions specified by `dims`.
Similar to `StatsBase.quantile!`, but slightly vectorized, and supporting the `dims` keyword.
Be aware that, like `StatsBase.quantile!`, this function modifies `A`, sorting or
partially sorting the contents thereof (specifically, along the dimensions specified
by `dims`, using either `quicksort!` or `quickselect!` depending on the size
of the array). Do not use this function if you do not want the contents of `A`
to be rearranged.
If reducing over multiple `dims`, these dimensions must be contiguous (i.e.
`dims=(2,3)` but not `dims=(1,3)`). Note also that specifying `dims` other than
`:` creates `view`s, with some nonzero performance cost.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
1 2 3
4 5 6
7 8 9
julia> vquantile!(A, 0.5, dims=1)
1×3 Matrix{Float64}:
4.0 5.0 6.0
julia> vquantile!(A, 0.5, dims=2)
3×1 Matrix{Float64}:
2.0
5.0
8.0
julia> vquantile!(A, 0.5)
5.0
julia> A # Note that the array has been sorted
3×3 Matrix{Int64}:
1 4 7
2 5 8
3 6 9
```
"""
vquantile!(A, q::Number; dim=:, dims=:) = _vquantile!(A, q, dim, dims)
_vquantile!(A, q, ::Colon, ::Colon) = _vquantile!(A, q, :)
_vquantile!(A, q, ::Colon, region) = _vquantile!(A, q, region)
_vquantile!(A, q, region, ::Colon) = reducedims(_vquantile!(A, q, region), region)
export vquantile!
vquantile(A, q; kwargs...) = vquantile!(copy(A), q; kwargs...)
export vquantile
# Reduce one dim
_vquantile!(A, q::Real, dims::Int) = _vquantile!(A, q, (dims,))
# Reduce some dims
function _vquantile!(A::AbstractArray{T,N}, q::Real, dims::Tuple) where {T,N}
iscontiguous(dims) || error("Only continuous `dims` are currently supported")
sᵢ = size(A)
sₒ = ntuple(Val{N}()) do d
ifelse(d ∈ dims, 1, sᵢ[d])
end
Tₒ = Base.promote_op(/, T, Int)
B = similar(A, Tₒ, sₒ)
_vquantile!(B, A, q, dims)
end
# Reduce all the dims!
_vquantile!(A, q::Real, ::Tuple{Colon}) = _vquantile!(A, q, :)
function _vquantile!(A, q::Real, ::Colon)
iₗ, iᵤ = firstindex(A), lastindex(A)
A, iₗ, iᵤ₋ = sortnans!(A, iₗ, iᵤ)
if iᵤ₋ < iᵤ
# Remove this if we'd rather ignore NaNs
return A[iᵤ]
end
N₋ = iᵤ - iₗ
iₚ = q*N₋ + iₗ
iₚ₋ = floor(Int, iₚ)
iₚ₊ = ceil(Int, iₚ)
if N₋ < 384
quicksort!(A, iₗ, iᵤ)
else
quickselect!(A, iₗ, iᵤ, iₚ₋)
quickselect!(A, iₚ₊, iᵤ, iₚ₊)
end
f = iₚ - iₚ₋
return f*A[iₚ₊] + (1-f)*A[iₚ₋]
end
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_quantile_quote(static_dims::Vector{Int}, N::Int)
M = length(static_dims)
# `static_dims` now contains every dim we're taking the quantile over.
Bᵥ = Expr(:call, :view, :B)
Aᵥ = Expr(:call, :view, :A)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(Aᵥ[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
if n ∈ static_dims
push!(reduct_inds, n)
push!(Aᵥ.args, :)
push!(Bᵥ.args, :(firstindex(B,$n)))
else
push!(nonreduct_inds, n)
push!(Aᵥ.args, ind)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Aᵥ = $Aᵥ))
push!(rblock.args, :($Bind = _vquantile!(Aᵥ, q, :)))
# Put it all together
return quote
Bᵥ = $Bᵥ
@inbounds $loops
return B
end
else
return quote
Bᵥ = $Bᵥ
Bᵥ[] = _vquantile!(A, q, :)
return B
end
end
end
# Chris Elrod metaprogramming magic:
# Turn non-static integers in `dims` tuple into `StaticInt`s
# so we can construct `static_dims` vector within @generated code
function branches_quantile_quote(N::Int, M::Int, D)
static_dims = Int[]
for m ∈ 1:M
param = D.parameters[m]
if param <: StaticInt
new_dim = _dim(param)::Int
@assert new_dim ∉ static_dims
push!(static_dims, new_dim)
else
t = Expr(:tuple)
for n ∈ static_dims
push!(t.args, :(StaticInt{$n}()))
end
q = Expr(:block, :(dimm = dims[$m]))
qold = q
ifsym = :if
for n ∈ 1:N
n ∈ static_dims && continue
tc = copy(t)
push!(tc.args, :(StaticInt{$n}()))
qnew = Expr(ifsym, :(dimm == $n), :(return _vquantile!(B, A, q, $tc)))
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, qnew)
qold = qnew
ifsym = :elseif
end
# Else, if dimm ∉ 1:N, drop it from list and continue
tc = copy(t)
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, Expr(:block, :(return _vquantile!(B, A, q, $tc))))
return q
end
end
return staticdim_quantile_quote(static_dims, N)
end
# Efficient @generated in-place quantile
@generated function _vquantile!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, q::Real, dims::D) where {Tₒ,T,N,M,D<:Tuple{Vararg{IntOrStaticInt,M}}}
branches_quantile_quote(N, M, D)
end
@generated function _vquantile!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, q::Real, dims::Tuple{}) where {Tₒ,T,N}
:(copyto!(B, A); return B)
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 2418 |
for (op, name) in zip((:min, :max), (:_vminimum, :_vmaximum))
# Deal with dim vs dims
@eval $name(A, ::Colon, ::Colon) = $name(A, :)
@eval $name(A, ::Colon, region) = $name(A, region)
@eval $name(A, region, ::Colon) = reducedims($name(A, region), region)
# Reduce over all dimensions
@eval $name(A, ::Colon) = vreduce($op, A)
# Reduce over a single dimension
@eval $name(A, region::Int) = region <= ndims(A) ? vreduce($op, A, dims=region) : A
# General case: recursive
@eval function $name(A::AbstractArray, region::Tuple)
if length(region) == 1
# For tuple with single element, simply unwrap
$name(A, region[1])
elseif length(region) == 2
# For tuple with two elements, two evaluations suffice
$name($name(A, region[1]), region[2])
else
# Otherwise recurse
$name($name(A, region[1]), region[2:end])
end
end
end
"""
```julia
vminimum(A; dims)
```
Find the least value contained in `A`, optionally over dimensions specified by `dims`.
As `Base.minimum`, but vectorized
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> vminimum(A, dims=1)
1×2 Matrix{Int64}:
1 2
julia> vminimum(A, dims=2)
2×1 Matrix{Int64}:
1
3
```
"""
vminimum(A; dim=:, dims=:) = _vminimum(A, dim, dims)
export vminimum
"""
```julia
vmaximum(A; dims)
```
Find the greatest value contained in `A`, optionally over dimensions specified by `dims`.
As `Base.maximum`, but vectorized.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> vmaximum(A, dims=1)
1×2 Matrix{Int64}:
3 4
julia> vmaximum(A, dims=2)
2×1 Matrix{Int64}:
2
4
```
"""
vmaximum(A; dim=:, dims=:) = _vmaximum(A, dim, dims)
export vmaximum
"""
```julia
vextrema(A; dims)
```
Find the maximum and minimum of `A`, optionally along the dimensions specified by `dims`.
As `Base.extrema`, but vectorized.
## Examples
julia> A = reshape(Vector(1:2:16), (2,2,2))
2×2×2 Array{Int64, 3}:
[:, :, 1] =
1 5
3 7
[:, :, 2] =
9 13
11 15
julia> extrema(A, dims = (1,2))
1×1×2 Array{Tuple{Int64, Int64}, 3}:
[:, :, 1] =
(1, 7)
[:, :, 2] =
(9, 15)
"""
vextrema(A; dims=:) = _vextrema(A, dims)
_vextrema(A, region) = collect(zip(_vminimum(A, region), _vmaximum(A, region)))
_vextrema(A, ::Colon) = (_vminimum(A, :), _vmaximum(A, :))
export vextrema
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 6756 | ## ---
"""
```julia
vsort(A; dims, multithreaded=false)
```
Return a sorted copy of the array `A`, optionally along dimensions specified by `dims`.
If sorting over multiple `dims`, these dimensions must be contiguous (i.e.
`dims=(2,3)` but not `dims=(1,3)`). Note also that specifying `dims` other than
`:` creates `view`s, with some nonzero performance cost.
See also `vsort!` for a more efficient in-place version.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1, 3, 2, 4];
julia> vsort(A)
4-element Vector{Int64}:
1
2
3
4
"""
vsort(A; dims=:, multithreaded=False()) = vsort!(copy(A); dims, multithreaded)
"""
```julia
vsort!([I], A; dims, multithreaded=false)
```
Sort the array `A`, optionally along dimensions specified by `dims`.
If the optional argument `I` is supplied, it will be sorted following the
same permuation as `A`. For example, if `I = collect(1:length(A))`, then
after calling `vsort!(I, A)`, `A` will be sorted and `I` will be equal to
`sortperm(A)`
If sorting over multiple `dims`, these dimensions must be contiguous (i.e.
`dims=(2,3)` but not `dims=(1,3)`). Note also that specifying `dims` other than
`:` creates `view`s, with some nonezero performance cost.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1, 3, 2, 4];
julia> vsort!(A)
4-element Vector{Int64}:
1
2
3
4
```
"""
vsort!(A; dims=:, multithreaded=false) = _vsort!(A, dims, multithreaded)
function vsort!(I, A; dims=:, multithreaded=False())
@assert eachindex(I) === eachindex(A)
_vsort!(I, A, dims, multithreaded)
end
export vsort!
_vsort!(A, dims, multithreaded::Symbol) = _vsort!(A, dims, (multithreaded===:auto && length(A) > 16383) ? True() : False())
_vsort!(A, dims, multithreaded::Bool) = _vsort!(A, dims, static(multithreaded))
_vsort!(I, A, dims, multithreaded::Symbol) = _vsort!(I, A, dims, (multithreaded===:auto && length(A) > 16383) ? True() : False())
_vsort!(I, A, dims, multithreaded::Bool) = _vsort!(I, A, dims, static(multithreaded))
# Sort linearly (reducing along all dimensions)
function _vsort!(A::AbstractArray, ::Colon, ::False)
# IF there are NaNs, move them all to the end of the array
A, iₗ, iᵤ = sortnans!(A)
# Sort the non-NaN elements
quicksort!(A, iₗ, iᵤ)
end
# Also permute `I` via the same permutation that sorts `A`
function _vsort!(I, A::AbstractArray, ::Colon, ::False)
@assert eachindex(I) === eachindex(A)
# IF there are NaNs, move them all to the end of the array
I, A, iₗ, iᵤ = sortnans!(I, A)
# Sort the non-NaN elements
quicksort!(I, A, iₗ, iᵤ)
end
## --- as above, but multithreaded
# Sort linearly (reducing along all dimensions)
function _vsort!(A::AbstractArray, ::Colon, ::True)
# IF there are NaNs, move them all to the end of the array
A, iₗ, iᵤ = sortnans!(A)
# Sort the non-NaN elements
quicksortt!(A, iₗ, iᵤ)
end
function _vsort!(I, A::AbstractArray, ::Colon, ::True)
# IF there are NaNs, move them all to the end of the array
I, A, iₗ, iᵤ = sortnans!(I, A)
# Sort the non-NaN elements
quicksortt!(I, A, iₗ, iᵤ)
end
## -- multidimensional cases (singlethreaded only)
# Reducing / sorting over noncontiguous dims may be a problem
function iscontiguous(dims)
for i = 2:length(dims)
if !(dims[i] == dims[i-1] + 1 || dims[i] == dims[i-1] - 1)
return false
end
end
return true
end
# Sort one dim
_vsort!(A, dims::Int, multithreaded::StaticBool) = _vsort!(A, (dims,), multithreaded)
# Sort some dims
function _vsort!(A::AbstractArray{T,N}, dims::Tuple, multithreaded) where {T,N}
iscontiguous(dims) || error("Only continuous `dims` are supported")
__vsort!(A, dims, multithreaded)
end
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_sort_quote(static_dims::Vector{Int}, N::Int)
M = length(static_dims)
# `static_dims` now contains every dim we're taking the sort over.
Aᵥ = Expr(:call, :view, :A)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(Aᵥ[])
inds = Vector{Symbol}(undef, N)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
if n ∈ static_dims
push!(reduct_inds, n)
push!(Aᵥ.args, :)
else
push!(nonreduct_inds, n)
push!(Aᵥ.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices(A,$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices(A,$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Aᵥ = $Aᵥ))
push!(rblock.args, :(_vsort!(Aᵥ, :, multithreaded)))
# Put it all together
return quote
@inbounds $loops
return A
end
else
return quote
_vsort!(A, :, multithreaded)
return A
end
end
end
# Chris Elrod metaprogramming magic:
# Turn non-static integers in `dims` tuple into `StaticInt`s
# so we can construct `static_dims` vector within @generated code
function branches_sort_quote(N::Int, M::Int, D)
static_dims = Int[]
for m ∈ 1:M
param = D.parameters[m]
if param <: StaticInt
new_dim = _dim(param)::Int
@assert new_dim ∉ static_dims
push!(static_dims, new_dim)
else
t = Expr(:tuple)
for n ∈ static_dims
push!(t.args, :(StaticInt{$n}()))
end
q = Expr(:block, :(dimm = dims[$m]))
qold = q
ifsym = :if
for n ∈ 1:N
n ∈ static_dims && continue
tc = copy(t)
push!(tc.args, :(StaticInt{$n}()))
qnew = Expr(ifsym, :(dimm == $n), :(return __vsort!(A, $tc, multithreaded)))
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, qnew)
qold = qnew
ifsym = :elseif
end
# Else, if dimm ∉ 1:N, drop it from list and continue
tc = copy(t)
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, Expr(:block, :(return __vsort!(A, $tc, multithreaded))))
return q
end
end
return staticdim_sort_quote(static_dims, N)
end
# Efficient @generated in-place sort
@generated function __vsort!(A::AbstractArray{T,N}, dims::D, multithreaded) where {T,N,M,D<:Tuple{Vararg{IntOrStaticInt,M}}}
branches_sort_quote(N, M, D)
end
@generated function __vsort!(A::AbstractArray{T,N}, dims::Tuple{}, multithreaded) where {T,N}
:(return A)
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 1868 | """
```julia
vstd(A; dims=:, mean=nothing, corrected=true, multithreaded=false)
```
Compute the variance of all elements in `A`, optionally over dimensions specified by `dims`.
As `Statistics.var`, but vectorized and (optionally) multithreaded.
A precomputed `mean` may optionally be provided, which results in a somewhat faster
calculation. If `corrected` is `true`, then _Bessel's correction_ is applied, such
that the sum is divided by `n-1` rather than `n`.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> vstd(A, dims=1)
1×2 Matrix{Float64}:
1.41421 1.41421
julia> vstd(A, dims=2)
2×1 Matrix{Float64}:
0.7071067811865476
0.7071067811865476
```
"""
vstd(A; dim=:, dims=:, mean=nothing, corrected=true, multithreaded=False()) = _vstd(mean, corrected, A, dim, dims, multithreaded)
export vstd
_vstd(mean, corrected, A, ::Colon, ::Colon, multithreaded) = _vstd(mean, corrected, A, :, multithreaded)
_vstd(mean, corrected, A, ::Colon, region, multithreaded) = _vstd(mean, corrected, A, region, multithreaded)
_vstd(mean, corrected, A, region, ::Colon, multithreaded) = reducedims(_vstd(mean, corrected, A, region, multithreaded), region)
_vstd(mean, corrected, A, dims, multithreaded) = sqrt!(_vvar(mean, corrected, A, dims, multithreaded), multithreaded)
sqrt!(x, multithreaded::Symbol) = sqrt!(x, (multithreaded===:auto && length(x) > 4095) ? True() : False())
sqrt!(x, multithreaded::Bool) = sqrt!(x, static(multithreaded))
sqrt!(x::Number, multithreaded::StaticBool) = sqrt(x)
function sqrt!(A::AbstractArray, multithreaded::False)
@turbo check_empty=true for i ∈ eachindex(A)
A[i] = sqrt(A[i])
end
return A
end
function sqrt!(A::AbstractArray, multithreaded::True)
@tturbo check_empty=true for i ∈ eachindex(A)
A[i] = sqrt(A[i])
end
return A
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 8979 | """
```julia
vsum(A; dims, multithreaded=false)
```
Summate the values contained in `A`, optionally over dimensions specified by `dims`.
As `Base.sum`, but vectorized and (optionally) multithreaded.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> vsum(A, dims=1)
1×2 Matrix{Int64}:
4 6
julia> vsum(A, dims=2)
2×1 Matrix{Int64}:
3
7
```
"""
vsum(A::AbstractArray{N,T}; dim=:, dims=:, multithreaded=False()) where {N,T}= _vsum(A, dim, dims, multithreaded)
vsum(A::NTuple{N,T}; dim=:, dims=:, multithreaded=False()) where {N,T} = _vsum(A, dim, dims, multithreaded)
_vsum(A, ::Colon, ::Colon, multithreaded) = _vsum(A, :, multithreaded)
_vsum(A, ::Colon, region, multithreaded) = _vsum(A, region, multithreaded)
_vsum(A, region, ::Colon, multithreaded) = reducedims(_vsum(A, region, multithreaded), region)
export vsum
_vsum(A, dims, multithreaded::Symbol) = _vsum(A, dims, (multithreaded===:auto && length(A) > 4095) ? True() : False())
_vsum(A, dims, multithreaded::Bool) = _vsum(A, dims, static(multithreaded))
# Reduce one dim
_vsum(A, dims::Int, multithreaded::StaticBool) = _vsum(A, (dims,), multithreaded)
# Reduce some dims
function _vsum(A::AbstractArray{T,N}, dims::Tuple, multithreaded::StaticBool) where {T,N}
sᵢ = size(A)
sₒ = ntuple(Val{N}()) do d
ifelse(d ∈ dims, 1, sᵢ[d])
end
Tₒ = Base.promote_op(+, T, Int)
B = similar(A, Tₒ, sₒ)
_vsum!(B, A, dims, multithreaded)
end
## Singlethreaded implementation
# Reduce all the dims!
function _vsum(A, ::Colon, multithreaded::False)
# Promote type of accumulator to avoid overflow
Tₒ = Base.promote_op(+, eltype(A), Int)
Σ = zero(Tₒ)
@turbo check_empty=true for i ∈ eachindex(A)
Σ += A[i]
end
return Σ
end
# Chris Elrod metaprogramming magic:
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_sum_quote(static_dims::Vector{Int}, N::Int, multithreaded::Type{False})
M = length(static_dims)
# `static_dims` now contains every dim we're taking the sum over.
Bᵥ = Expr(:call, :view, :B)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(A[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
push!(Aind.args, ind)
if n ∈ static_dims
push!(reduct_inds, n)
push!(Bᵥ.args, :(firstindex(B,$n)))
else
push!(nonreduct_inds, n)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Σ = zero(eltype(Bᵥ))))
# Build the reduction loop
for n ∈ reduct_inds
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Push more things here if you want them at the end of the reduction loop
push!(rblock.args, :($Bind = Σ))
# Put it all together
return quote
Bᵥ = $Bᵥ
@turbo $loops
return B
end
else
firstn = first(reduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = axes(A,$firstn)), block)
# Build the reduction loop
if length(reduct_inds) > 1
for n ∈ @view(reduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Put it all together
return quote
Bᵥ = $Bᵥ
Σ = zero(eltype(Bᵥ))
@turbo $loops
Bᵥ[] = Σ
return B
end
end
end
## As above, but multithreaded
# Reduce all the dims!
function _vsum(A, ::Colon, multithreaded::True)
# Promote type of accumulator to avoid overflow
Tₒ = Base.promote_op(+, eltype(A), Int)
Σ = zero(Tₒ)
@tturbo check_empty=true for i ∈ eachindex(A)
Σ += A[i]
end
return Σ
end
# Chris Elrod metaprogramming magic:
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_sum_quote(static_dims::Vector{Int}, N::Int, multithreaded::Type{True})
M = length(static_dims)
# `static_dims` now contains every dim we're taking the sum over.
Bᵥ = Expr(:call, :view, :B)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(A[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
push!(Aind.args, ind)
if n ∈ static_dims
push!(reduct_inds, n)
push!(Bᵥ.args, :(firstindex(B,$n)))
else
push!(nonreduct_inds, n)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(Σ = zero(eltype(Bᵥ))))
# Build the reduction loop
for n ∈ reduct_inds
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Push more things here if you want them at the end of the reduction loop
push!(rblock.args, :($Bind = Σ))
# Put it all together
return quote
Bᵥ = $Bᵥ
@tturbo $loops
return B
end
else
firstn = first(reduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = axes(A,$firstn)), block)
# Build the reduction loop
if length(reduct_inds) > 1
for n ∈ @view(reduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(Σ += $Aind))
# Put it all together
return quote
Bᵥ = $Bᵥ
Σ = zero(eltype(Bᵥ))
@tturbo $loops
Bᵥ[] = Σ
return B
end
end
end
## @generated functions to handle all the possible branches
# Chris Elrod metaprogramming magic:
# Turn non-static integers in `dims` tuple into `StaticInt`s
# so we can construct `static_dims` vector within @generated code
function branches_sum_quote(N::Int, M::Int, D, multithreaded)
static_dims = Int[]
for m ∈ 1:M
param = D.parameters[m]
if param <: StaticInt
new_dim = _dim(param)::Int
@assert new_dim ∉ static_dims
push!(static_dims, new_dim)
else
t = Expr(:tuple)
for n ∈ static_dims
push!(t.args, :(StaticInt{$n}()))
end
q = Expr(:block, :(dimm = dims[$m]))
qold = q
ifsym = :if
for n ∈ 1:N
n ∈ static_dims && continue
tc = copy(t)
push!(tc.args, :(StaticInt{$n}()))
qnew = Expr(ifsym, :(dimm == $n), :(return _vsum!(B, A, $tc, multithreaded)))
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, qnew)
qold = qnew
ifsym = :elseif
end
# Else, if dimm ∉ 1:N, drop it from list and continue
tc = copy(t)
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, Expr(:block, :(return _vsum!(B, A, $tc, multithreaded))))
return q
end
end
return staticdim_sum_quote(static_dims, N, multithreaded)
end
# Efficient @generated in-place sum
@generated function _vsum!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, dims::D, multithreaded) where {Tₒ,T,N,M,D<:Tuple{Vararg{IntOrStaticInt,M}}}
branches_sum_quote(N, M, D, multithreaded)
end
@generated function _vsum!(B::AbstractArray{Tₒ,N}, A::AbstractArray{T,N}, dims::Tuple{}, multithreaded) where {Tₒ,T,N}
:(copyto!(B, A); return B)
end
##
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 11123 | """
```julia
vvar(A; dims=:, mean=nothing, corrected=true)
```
Compute the variance of all elements in `A`, optionally over dimensions specified by `dims`.
As `Statistics.var`, but vectorized and (optionally) multithreaded.
A precomputed `mean` may optionally be provided, which results in a somewhat faster
calculation. If `corrected` is `true`, then _Bessel's correction_ is applied, such
that the sum is divided by `n-1` rather than `n`.
## Examples
```julia
julia> using VectorizedStatistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> vvar(A, dims=1)
1×2 Matrix{Float64}:
2.0 2.0
julia> vvar(A, dims=2)
2×1 Matrix{Float64}:
0.5
0.5
```
"""
vvar(A; dim=:, dims=:, mean=nothing, corrected=true, multithreaded=False()) = _vvar(mean, corrected, A, dim, dims, multithreaded)
_vvar(mean, corrected, A, ::Colon, ::Colon, multithreaded) = _vvar(mean, corrected, A, :, multithreaded)
_vvar(mean, corrected, A, ::Colon, region, multithreaded) = _vvar(mean, corrected, A, region, multithreaded)
_vvar(mean, corrected, A, region, ::Colon, multithreaded) = reducedims(_vvar(mean, corrected, A, region, multithreaded), region)
export vvar
_vvar(mean, corrected, A, dims, multithreaded::Symbol) = _vvar(mean, corrected, A, dims, (multithreaded===:auto && length(A) > 4095) ? True() : False())
_vvar(mean, corrected, A, dims, multithreaded::Bool) = _vvar(mean, corrected, A, dims, static(multithreaded))
# If dims is an integer, wrap it in a tuple
_vvar(μ, corrected::Bool, A, dims::Int, multithreaded::StaticBool) = _vvar(μ, corrected, A, (dims,), multithreaded)
# If the mean is known, pass it on in the appropriate form
_vvar(μ, corrected::Bool, A, dims::Tuple, multithreaded::StaticBool) = _vvar!(collect(μ), corrected, A, dims, multithreaded)
_vvar(μ::Array, corrected::Bool, A, dims::Tuple, multithreaded::StaticBool) = _vvar!(copy(μ), corrected, A, dims, multithreaded)
_vvar(μ::Number, corrected::Bool, A, dims::Tuple, multithreaded::StaticBool) = _vvar!([μ], corrected, A, dims, multithreaded)
function _vvar(μ::Number, corrected::Bool, A, ::Colon, multithreaded::False)
# Reduce all the dims!
n = length(A)
σ² = zero(typeof(μ))
@turbo check_empty=true for i ∈ eachindex(A)
δ = A[i] - μ
σ² += δ * δ
end
return σ² / (n-corrected)
end
function _vvar(μ::Number, corrected::Bool, A, ::Colon, multithreaded::True)
# Reduce all the dims!
n = length(A)
σ² = zero(typeof(μ))
@tturbo check_empty=true for i ∈ eachindex(A)
δ = A[i] - μ
σ² += δ * δ
end
return σ² / (n-corrected)
end
# If the mean isn't known, compute it
_vvar(::Nothing, corrected::Bool, A, dims::Tuple, multithreaded::StaticBool) = _vvar!(_vmean(A, dims, multithreaded), corrected, A, dims, multithreaded)
function _vvar(::Nothing, corrected::Bool, A, ::Colon, multithreaded::False)
# Reduce all the dims!
n = length(A)
Tₒ = Base.promote_op(/, eltype(A), Int)
Σ = zero(Tₒ)
@turbo check_empty=true for i ∈ eachindex(A)
Σ += A[i]
end
μ = Σ / n
σ² = zero(typeof(μ))
@turbo check_empty=true for i ∈ eachindex(A)
δ = A[i] - μ
σ² += δ * δ
end
return σ² / (n-corrected)
end
function _vvar(::Nothing, corrected::Bool, A, ::Colon, multithreaded::True)
# Reduce all the dims!
n = length(A)
Tₒ = Base.promote_op(/, eltype(A), Int)
Σ = zero(Tₒ)
@tturbo check_empty=true for i ∈ eachindex(A)
Σ += A[i]
end
μ = Σ / n
σ² = zero(typeof(μ))
@tturbo check_empty=true for i ∈ eachindex(A)
δ = A[i] - μ
σ² += δ * δ
end
return σ² / (n-corrected)
end
## Singlethreaded implementation
# Chris Elrod metaprogramming magic:
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_var_quote(static_dims::Vector{Int}, N::Int, multithreaded::Type{False})
M = length(static_dims)
# `static_dims` now contains every dim we're taking the var over.
Bᵥ = Expr(:call, :view, :B)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(A[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
len = Expr(:call, :*)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
push!(Aind.args, ind)
if n ∈ static_dims
push!(reduct_inds, n)
push!(Bᵥ.args, :(firstindex(B,$n)))
push!(len.args, :(size(A, $n)))
else
push!(nonreduct_inds, n)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(μ = $Bind))
push!(rblock.args, :(σ² = zero(eltype(Bᵥ))))
# Build the reduction loop
for n ∈ reduct_inds
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(δ = $Aind - μ))
push!(block.args, :(σ² += δ * δ))
# Push more things here if you want them at the end of the reduction loop
push!(rblock.args, :($Bind = σ² * invdenom))
# Put it all together
return quote
invdenom = inv(($len) - corrected)
Bᵥ = $Bᵥ
@turbo $loops
return B
end
else
firstn = first(reduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = axes(A,$firstn)), block)
if length(reduct_inds) > 1
for n ∈ @view(reduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(δ = $Aind - μ))
push!(block.args, :(σ² += δ * δ))
# Put it all together
return quote
invdenom = inv(($len) - corrected)
Bᵥ = $Bᵥ
μ = Bᵥ[]
σ² = zero(eltype(Bᵥ))
@turbo $loops
Bᵥ[] = σ² * invdenom
return B
end
end
end
## Multithreaded implementation
# Chris Elrod metaprogramming magic:
# Generate customized set of loops for a given ndims and a vector
# `static_dims` of dimensions to reduce over
function staticdim_var_quote(static_dims::Vector{Int}, N::Int, multithreaded::Type{True})
M = length(static_dims)
# `static_dims` now contains every dim we're taking the var over.
Bᵥ = Expr(:call, :view, :B)
reduct_inds = Int[]
nonreduct_inds = Int[]
# Firstly, build our expressions for indexing each array
Aind = :(A[])
Bind = :(Bᵥ[])
inds = Vector{Symbol}(undef, N)
len = Expr(:call, :*)
for n ∈ 1:N
ind = Symbol(:i_,n)
inds[n] = ind
push!(Aind.args, ind)
if n ∈ static_dims
push!(reduct_inds, n)
push!(Bᵥ.args, :(firstindex(B,$n)))
push!(len.args, :(size(A, $n)))
else
push!(nonreduct_inds, n)
push!(Bᵥ.args, :)
push!(Bind.args, ind)
end
end
# Secondly, build up our set of loops
if !isempty(nonreduct_inds)
firstn = first(nonreduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = indices((A,B),$firstn)), block)
if length(nonreduct_inds) > 1
for n ∈ @view(nonreduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = indices((A,B),$n)), newblock))
block = newblock
end
end
rblock = block
# Push more things here if you want them at the beginning of the reduction loop
push!(rblock.args, :(μ = $Bind))
push!(rblock.args, :(σ² = zero(eltype(Bᵥ))))
# Build the reduction loop
for n ∈ reduct_inds
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(δ = $Aind - μ))
push!(block.args, :(σ² += δ * δ))
# Push more things here if you want them at the end of the reduction loop
push!(rblock.args, :($Bind = σ² * invdenom))
# Put it all together
return quote
invdenom = inv(($len) - corrected)
Bᵥ = $Bᵥ
@tturbo $loops
return B
end
else
firstn = first(reduct_inds)
block = Expr(:block)
loops = Expr(:for, :($(inds[firstn]) = axes(A,$firstn)), block)
if length(reduct_inds) > 1
for n ∈ @view(reduct_inds[2:end])
newblock = Expr(:block)
push!(block.args, Expr(:for, :($(inds[n]) = axes(A,$n)), newblock))
block = newblock
end
end
# Push more things here if you want them in the innermost loop
push!(block.args, :(δ = $Aind - μ))
push!(block.args, :(σ² += δ * δ))
# Put it all together
return quote
invdenom = inv(($len) - corrected)
Bᵥ = $Bᵥ
μ = Bᵥ[]
σ² = zero(eltype(Bᵥ))
@tturbo $loops
Bᵥ[] = σ² * invdenom
return B
end
end
end
## ---
# Chris Elrod metaprogramming magic:
# Turn non-static integers in `dims` tuple into `StaticInt`s
# so we can construct `static_dims` vector within @generated code
function branches_var_quote(N::Int, M::Int, D, multithreaded)
static_dims = Int[]
for m ∈ 1:M
param = D.parameters[m]
if param <: StaticInt
new_dim = _dim(param)::Int
@assert new_dim ∉ static_dims
push!(static_dims, new_dim)
else
t = Expr(:tuple)
for n ∈ static_dims
push!(t.args, :(StaticInt{$n}()))
end
q = Expr(:block, :(dimm = dims[$m]))
qold = q
ifsym = :if
for n ∈ 1:N
n ∈ static_dims && continue
tc = copy(t)
push!(tc.args, :(StaticInt{$n}()))
qnew = Expr(ifsym, :(dimm == $n), :(return _vvar!(B, corrected, A, $tc, multithreaded)))
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, qnew)
qold = qnew
ifsym = :elseif
end
# Else, if dimm ∉ 1:N, drop it from list and continue
tc = copy(t)
for r ∈ m+1:M
push!(tc.args, :(dims[$r]))
end
push!(qold.args, Expr(:block, :(return _vvar!(B, corrected, A, $tc, multithreaded))))
return q
end
end
staticdim_var_quote(static_dims, N, multithreaded)
end
# Efficient @generated in-place var
@generated function _vvar!(B::AbstractArray{Tₒ,N}, corrected::Bool, A::AbstractArray{T,N}, dims::D, multithreaded) where {Tₒ,T,N,M,D<:Tuple{Vararg{IntOrStaticInt,M}}}
branches_var_quote(N, M, D, multithreaded)
end
@generated function _vvar!(B::AbstractArray{Tₒ,N}, corrected::Bool, A::AbstractArray{T,N}, dims::Tuple{}, multithreaded) where {Tₒ,T,N}
:(fill!(B, Tₒ(NaN)); return B)
end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 374 | using Test
using Statistics
using VectorizedStatistics
using VectorizationBase
#VectorizationBase.vsum(x::Float64) = x
@testset "Vreducibles" begin include("testVreducibles.jl") end
@testset "ArrayStats" begin include("testArrayStats.jl") end
@testset "Correlation and Covariance" begin include("testCovCor.jl") end
@testset "Sorting" begin include("testSorting.jl") end
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 9538 | ## --- Test equivalence to Base/Stdlib for other summary statistics
# Test vsum
for nd = 1:5
@info "Testing vsum: $nd-dimensional arrays"
# Generate random array
A = rand((1 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
Σ = sum(A)
@test vsum(A, multithreaded=false) ≈ Σ
@test vsum(A, multithreaded=true) ≈ Σ
@test vsum(A, multithreaded=:auto) ≈ Σ
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vsum: reduction over dimension $i"
Σ = sum(A, dims=i)
@test vsum(A, dims=i, multithreaded=false) ≈ Σ
@test vsum(A, dims=i, multithreaded=true) ≈ Σ
@test vec(vsum(A, dim=i)) ≈ vec(Σ)
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vsum: reduction over dimensions $((j,i))"
Σ = sum(A, dims=(j,i))
@test vsum(A, dims=(j,i), multithreaded=false) ≈ Σ
@test vsum(A, dims=(j,i), multithreaded=true) ≈ Σ
@test vec(vsum(A, dim=(j,i))) ≈ vec(Σ)
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vsum: reduction over dimensions $((k,j,i))"
Σ = sum(A, dims=(k,j,i))
@test vsum(A, dims=(k,j,i), multithreaded=false) ≈ Σ
@test vsum(A, dims=(k,j,i), multithreaded=true) ≈ Σ
end
end
end
end
end
# Test vmean
for nd = 1:5
@info "Testing vmean: $nd-dimensional arrays"
# Generate random array
A = rand((2 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
μ = mean(A)
@test vmean(A, multithreaded=false) ≈ μ
@test vmean(A, multithreaded=true) ≈ μ
@test vmean(A, multithreaded=:auto) ≈ μ
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vmean: reduction over dimension $i"
μ = mean(A, dims=i)
@test vmean(A, dims=i, multithreaded=false) ≈ μ
@test vmean(A, dims=i, multithreaded=true) ≈ μ
@test vec(vmean(A, dim=i)) ≈ vec(μ)
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vmean: reduction over dimensions $((j,i))"
μ = mean(A, dims=(j,i))
@test vmean(A, dims=(j,i), multithreaded=false) ≈ μ
@test vmean(A, dims=(j,i), multithreaded=true) ≈ μ
@test vec(vmean(A, dim=(j,i))) ≈ vec(μ)
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vmean: reduction over dimensions $((k,j,i))"
μ = mean(A, dims=(k,j,i))
@test vmean(A, dims=(k,j,i), multithreaded=false) ≈ μ
@test vmean(A, dims=(k,j,i), multithreaded=true) ≈ μ
end
end
end
end
# Test equivalence when reducing over four dimensions
if nd > 3
for i = 4:nd
for j = 2:i-1
for k = 1:j-1
for l = 1:k-1
@info "Testing vmean: reduction over dimensions $((l,k,j,i))"
μ = mean(A, dims=(l,k,j,i))
@test vmean(A, dims=(l,k,j,i), multithreaded=false) ≈ μ
@test vmean(A, dims=(l,k,j,i), multithreaded=true) ≈ μ
end
end
end
end
end
end
# Test vvar
for nd = 1:5
@info "Testing vvar: $nd-dimensional arrays"
# Generate random array
A = randn((2 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
σ² = var(A, corrected=false)
@test vvar(A, corrected=false, multithreaded=false) ≈ σ²
@test vvar(A, corrected=false, multithreaded=true) ≈ σ²
@test vvar(A, corrected=false, multithreaded=:auto) ≈ σ²
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vvar: reduction over dimension $i"
σ² = var(A, dims=i, corrected=false)
@test vvar(A, dims=i, corrected=false, multithreaded=false) ≈ σ²
@test vvar(A, dims=i, corrected=false, multithreaded=true) ≈ σ²
@test vec(vvar(A, dim=i, corrected=false)) ≈ vec(σ²)
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vvar: reduction over dimensions $((j,i))"
σ² = var(A, dims=(j,i), corrected=false)
@test vvar(A, dims=(j,i), corrected=false, multithreaded=false) ≈ σ²
@test vvar(A, dims=(j,i), corrected=false, multithreaded=true) ≈ σ²
@test vec(vvar(A, dim=(j,i), corrected=false)) ≈ vec(σ²)
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vvar: reduction over dimensions $((k,j,i))"
σ² = var(A, dims=(k,j,i))
@test vvar(A, dims=(k,j,i), multithreaded=false) ≈ σ²
@test vvar(A, dims=(k,j,i), multithreaded=true) ≈ σ²
end
end
end
end
end
# Test vstd
for nd = 1:5
@info "Testing vstd: $nd-dimensional arrays"
# Generate random array
A = randn((2 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
σ = std(A)
@test vstd(A, multithreaded=true) ≈ σ
@test vstd(A, multithreaded=false) ≈ σ
@test vstd(A, multithreaded=:auto) ≈ σ
σ = std(A, corrected=false)
@test vstd(A, corrected=false, multithreaded=true) ≈ σ
@test vstd(A, corrected=false, multithreaded=false) ≈ σ
@test vstd(A, corrected=false, multithreaded=:auto) ≈ σ
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vstd: reduction over dimension $i"
σ = std(A, dims=i)
@test vstd(A, dims=i, multithreaded=true) ≈ σ
@test vstd(A, dims=i, multithreaded=false) ≈ σ
@test vec(vstd(A, dim=i)) ≈ vec(σ)
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vstd: reduction over dimensions $((j,i))"
σ = std(A, dims=(j,i))
@test vstd(A, dims=(j,i)) ≈ σ
@test vec(vstd(A, dim=(j,i))) ≈ vec(σ)
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vstd: reduction over dimensions $((k,j,i))"
@test vstd(A, dims=(k,j,i)) ≈ std(A, dims=(k,j,i))
end
end
end
end
# Test equivalence when reducing over four dimensions
if nd > 3
for i = 4:nd
for j = 2:i-1
for k = 1:j-1
for l = 1:k-1
@info "Testing vstd: reduction over dimensions $((l,k,j,i))"
@test vstd(A, dims=(l,k,j,i)) ≈ std(A, dims=(l,k,j,i))
end
end
end
end
end
end
# Test fallbacks for complex reductions
A = randn((2 .+ (1:6))...);
@test vmean(A, dims=(4,5,6)) ≈ mean(A, dims=(4,5,6))
@test vstd(A, dims=(4,5,6)) ≈ std(A, dims=(4,5,6))
@test vstd(A, dims=(4,5,6)) ≈ vstd(A, dims=(4,5,6), mean=vmean(A, dims=(4,5,6)))
# Test results when diminsions are out of range
A = rand(10,10)
@test vminimum(A, dims=3) == A
@test vminimum(A, dims=(1,3)) == minimum(A, dims=(1,3))
@test vsum(A, dims=3, multithreaded=false) == vmean(A, dims=(3,4), multithreaded=false) == A
@test vsum(A, dims=3, multithreaded=true) == vmean(A, dims=(3,4), multithreaded=true) == A
@test vmean(A, dims=3, multithreaded=false) == vmean(A, dims=(3,4), multithreaded=false) == A
@test vmean(A, dims=3, multithreaded=true) == vmean(A, dims=(3,4), multithreaded=true) == A
@test isequal(vstd(A, dims=(3,4), multithreaded=false), fill(NaN, 10, 10))
@test isequal(vstd(A, dims=(3,4), multithreaded=true), fill(NaN, 10, 10))
@test vstd(A, dims=(1,3)) == vstd(A, dims=1)
## -- End of File
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 1257 | # Test pair-wise correlation and covariance functions
x, y = rand(1000), rand(1000)
@test vcov(x,y, multithreaded=true) ≈ vcov(x,y, multithreaded=false) ≈ vcov(x,y, multithreaded=:auto) ≈ cov(x,y)
@test vcov(x,y, corrected=false, multithreaded=true) ≈ vcov(x,y, corrected=false, multithreaded=false) ≈ cov(x,y, corrected=false)
@test vcor(x,y, multithreaded=true) ≈ vcor(x,y, multithreaded=false) ≈ vcor(x,y, multithreaded=:auto) ≈ cor(x,y)
# Test correlation and covariance functions as applied to matrices
X = rand(100,10)
@test vcov(X, multithreaded=true) ≈ vcov(X, multithreaded=false) ≈ vcov(X, multithreaded=:auto) ≈ cov(X)
@test vcov(X, dims=1, multithreaded=true) ≈ vcov(X, dims=1, multithreaded=false) ≈ cov(X, dims=1)
@test vcov(X, dims=2, multithreaded=true) ≈ vcov(X, dims=2, multithreaded=false) ≈ cov(X, dims=2)
@test vcov(X, corrected=false, multithreaded=true) ≈ vcov(X, corrected=false, multithreaded=false) ≈ cov(X, corrected=false)
@test vcor(X, multithreaded=true) ≈ vcor(X, multithreaded=false) ≈ vcor(X, multithreaded=:auto) ≈ cor(X)
@test vcor(X, dims=1, multithreaded=true) ≈ vcor(X, dims=1, multithreaded=false) ≈ cor(X, dims=1)
@test vcor(X, dims=2, multithreaded=true) ≈ vcor(X, dims=2, multithreaded=false) ≈ cor(X, dims=2)
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 5569 | ## --- Test sorting functions directly
A = rand(100)
# SortNaNs
B, iₗ, iᵤ = VectorizedStatistics.sortnans!(copy(A))
@test B == A
@test (iₗ, iᵤ) == (1, 100)
# Quicksort
VectorizedStatistics.quicksort!(A)
a = sort(A)
@test A == a
A = rand(10_000)
a = sort(A)
VectorizedStatistics.quicksort!(A)
@test A == a
A = rand(10_000)
a = sort(A)
I = collect(1:10_000)
i = sortperm(A)
VectorizedStatistics.quicksort!(I, A)
@test A == a
@test I == i
# Multithreaded quicksort
A = rand(100)
a = sort(A)
VectorizedStatistics.quicksortt!(A)
@test A == a
A = rand(10_000)
a = sort(A)
VectorizedStatistics.quicksortt!(A)
@test A == a
A = rand(10_000)
a = sort(A)
I = collect(1:10_000)
i = sortperm(A)
VectorizedStatistics.quicksortt!(I, A)
@test A == a
@test I == i
# Partialsort
A = rand(101)
m = median(A)
VectorizedStatistics.quickselect!(A, 1, 101, 51)
@test A[51] == m
# Quicksort of already-sorted arrays
@test VectorizedStatistics.quicksort!(collect(1:100)) == 1:100
@test VectorizedStatistics.quicksort!(collect(100:-1:1)) == 1:100
@test VectorizedStatistics.quicksortt!(collect(1:100)) == 1:100
@test VectorizedStatistics.quicksortt!(collect(100:-1:1)) == 1:100
# Test quicksort of some potentially pathological cases
@test VectorizedStatistics.quicksort!(abs.(-50:50)) == sort(abs.(-50:50))
@test VectorizedStatistics.quicksortt!(abs.(-50:50)) == sort(abs.(-50:50))
# Vsort, Float64
A = rand(100)
B = VectorizedStatistics.vsort(A, multithreaded=false)
@test issorted(B)
A = rand(100)
B = VectorizedStatistics.vsort(A, multithreaded=true)
@test issorted(B)
# Vsort!, Float64
A = rand(100)
Ix = sortperm(A)
I = collect(1:length(A))
vsort!(I, A)
@test issorted(A)
@test Ix == I
A[rand(1:100, 10)] .= NaN
vsort!(I, A)
@test issorted(A)
A .= rand.()
vsort!(A)
@test issorted(A)
A .= rand.()
A[rand(1:100, 10)] .= NaN
vsort!(A)
@test issorted(A)
A = rand(10_000)
Ix = sortperm(A)
I = collect(1:length(A))
vsort!(I, A, multithreaded=false)
@test issorted(A)
@test Ix == I
A .= rand.()
vsort!(I)
Ix = sortperm(A)
vsort!(I, A, multithreaded=true)
@test issorted(A)
@test Ix == I
A .= rand.()
vsort!(I)
Ix = sortperm(A)
vsort!(I, A, multithreaded=:auto)
@test issorted(A)
@test Ix == I
A .= rand.()
vsort!(A)
@test issorted(A)
A .= rand.()
A[rand(1:10_000, 1_000)] .= NaN
vsort!(A)
@test issorted(A)
# Vsort, Int64
A = rand(Int, 100)
B = VectorizedStatistics.vsort(A, multithreaded=false)
@test issorted(B)
A = rand(Int, 100)
B = VectorizedStatistics.vsort(A, multithreaded=true)
@test issorted(B)
# Vsort!, Int64
Ix = sortperm(A)
I = collect(1:length(A))
vsort!(I, A)
@test Ix == I
# Vsort, dimensional cases
A = rand(100,100)
@test vsort!(copy(A), dims=1) == sort(A, dims=1)
@test vsort!(copy(A), dims=2) == sort(A, dims=2)
@test vsort!(copy(A), dims=3) == A
A = rand(10,11,12)
@test sort(A, dims=1) == vsort!(copy(A), dims=1)
@test sort(A, dims=2) == vsort!(copy(A), dims=2)
@test sort(A, dims=3) == vsort!(copy(A), dims=3)
## --- Test vmedian!
@test vmedian!(0:10) == 5
@test vmedian!(1:10) == 5.5
A = rand(100)
@test vmedian!(copy(A)) == vmedian(A) == median(A)
A = rand(10_000)
@test vmedian!(copy(A)) == median(A)
A = rand(55,82)
@test vmedian!(copy(A)) == vmedian(A) == median(A)
@test vmedian!(copy(A), dims=1) == median(A, dims=1)
@test vmedian!(copy(A), dims=2) == median(A, dims=2)
A = rand(10,11,12)
@test vmedian!(copy(A)) == vmedian(A) == median(A)
@test vmedian!(copy(A), dims=1) == vmedian(A, dims=1) == median(A, dims=1)
@test vmedian!(copy(A), dims=2) == vmedian(A, dims=2) == median(A, dims=2)
@test vmedian!(copy(A), dims=3) == vmedian(A, dims=3) == median(A, dims=3)
@test vmedian!(copy(A), dims=(1,2)) == vmedian(A, dims=(1,2)) == median(A, dims=(1,2))
@test vmedian!(copy(A), dims=(2,3)) == vmedian(A, dims=(2,3)) == median(A, dims=(2,3))
## --- Test vpercentile! / vquantile!
@test vpercentile!(0:10, 0) == 0
@test vpercentile!(0:10, 1) ≈ 0.1
@test vpercentile!(0:10, 100) == 10
@test vpercentile!(0:10, 13.582) ≈ 1.3582
@test vpercentile!(collect(1:10), 50) == 5.5
A = rand(100)
@test vpercentile!(copy(A), 50) == vpercentile(A, 50) == median(A)
A = rand(10_000)
@test vpercentile!(copy(A), 50) == median(A)
A = rand(55,82)
@test vpercentile!(copy(A), 50) == vpercentile(A, 50) == median(A)
@test vpercentile!(copy(A), 50, dims=1) == median(A, dims=1)
@test vpercentile!(copy(A), 50, dims=2) == median(A, dims=2)
A = rand(10,11,12)
@test vpercentile!(copy(A), 50) == vpercentile(A, 50) == median(A)
@test vpercentile!(copy(A), 50, dims=1) == median(A, dims=1)
@test vpercentile!(copy(A), 50, dims=2) == median(A, dims=2)
@test vpercentile!(copy(A), 50, dims=3) == median(A, dims=3)
@test vpercentile!(copy(A), 50, dims=(1,2)) == median(A, dims=(1,2))
@test vpercentile!(copy(A), 50, dims=(2,3)) == median(A, dims=(2,3))
A = rand(100)
@test median(A) == vpercentile!(copy(A), 50) == vquantile!(copy(A), 0.5) == vquantile(A, 0.5)
@test vpercentile!(copy(A), 50) == vquantile!(copy(A), 0.5)
## ---
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | code | 4114 | ## --- Test equivalence to Base/Stdlib for `vreduce`-ables
# Test vminimum
for nd = 1:5
@info "Testing vminimum: $nd-dimensional arrays"
# Generate random array
A = rand((1 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
@test vminimum(A) ≈ minimum(A)
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vminimum: reduction over dimension $i"
@test vminimum(A, dims=i) ≈ minimum(A, dims=i)
@test vec(vminimum(A, dim=i)) ≈ vec(minimum(A, dims=i))
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vminimum: reduction over dimensions $((j,i))"
@test vminimum(A, dims=(j,i)) ≈ minimum(A, dims=(j,i))
@test vec(vminimum(A, dim=(j,i))) ≈ vec(minimum(A, dims=(j,i)))
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vminimum: reduction over dimensions $((k,j,i))"
@test vminimum(A, dims=(k,j,i)) ≈ minimum(A, dims=(k,j,i))
end
end
end
end
end
# Test vmaximum
for nd = 1:5
@info "Testing vmaximum: $nd-dimensional arrays"
# Generate random array
A = rand((1 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
@test vmaximum(A) ≈ maximum(A)
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vmaximum: reduction over dimension $i"
@test vmaximum(A, dims=i) ≈ maximum(A, dims=i)
@test vec(vmaximum(A, dim=i)) ≈ vec(maximum(A, dims=i))
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vmaximum: reduction over dimensions $((j,i))"
@test vmaximum(A, dims=(j,i)) ≈ maximum(A, dims=(j,i))
@test vec(vmaximum(A, dim=(j,i))) ≈ vec(maximum(A, dims=(j,i)))
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vmaximum: reduction over dimensions $((k,j,i))"
@test vmaximum(A, dims=(k,j,i)) ≈ maximum(A, dims=(k,j,i))
end
end
end
end
end
# Test vextrema
for nd = 1:3
@info "Testing vextrema: $nd-dimensional arrays"
# Generate random array
A = rand((1 .+ (1:nd))...)
# Test equivlalence when reducing over all dims
@test vextrema(A) == extrema(A)
# Test equivalence when reducing over a single dimension
for i = 1:nd
@info "Testing vextrema: reduction over dimension $i"
@test vextrema(A, dims=i) == extrema(A, dims=i)
end
# Test equivalence when reducing over two dimensions
if nd > 1
for i = 2:nd
for j = 1:i-1
@info "Testing vextrema: reduction over dimensions $((j,i))"
@test vextrema(A, dims=(j,i)) == extrema(A, dims=(j,i))
end
end
end
# Test equivalence when reducing over three dimensions
if nd > 2
for i = 3:nd
for j = 2:i-1
for k = 1:j-1
@info "Testing vextrema: reduction over dimensions $((k,j,i))"
@test vextrema(A, dims=(k,j,i)) == extrema(A, dims=(k,j,i))
end
end
end
end
end
## -- End of File
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | docs | 7825 | # VectorizedStatistics
[![Dev][docs-dev-img]][docs-dev-url]
[![Build Status][ci-img]][ci-url]
[![codecov.io][codecov-img]][codecov-url]
Fast, [LoopVectorization.jl](https://github.com/JuliaSIMD/LoopVectorization.jl)-based summary statistics.
#### Implemented by reduction, recursively (singlethreaded only)
* `vminimum`
* `vmaximum`
* `vextrema`
#### Implemented directly by compile-time loop generation or manually-coded loops (optionally multithreaded)
* `vmean`
* `vsum`
* `vvar`
* `vstd`
* `vcov`
* `vcor`
#### Implemented via quicksort/quickselect (some easy steps vectorized), with multidimensional reductions handled by compile-time loop generation
* `vsort!`
* `vmedian!`
* `vquantile!`
* `vpercentile!`
#### See also
* [NaNStatistics.jl](https://github.com/brenhinkeller/NaNStatistics.jl) for equivalently-vectorized functions that additionally ignore `NaN`s
### Examples and benchmarks
As of Julia `v1.8.3`, VectorizedStatistics `v0.5.0`
##### `vminimum`/`vmaximum` (implemented by recursive `vreduce`)
```julia
julia> using Statistics, VectorizedStatistics, BenchmarkTools
julia> A = rand(10_000);
julia> minimum(A) == vminimum(A)
true
julia> @benchmark minimum($A)
BenchmarkTools.Trial: 10000 samples with 5 evaluations.
Range (min … max): 6.400 μs … 17.850 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 6.692 μs ┊ GC (median): 0.00%
Time (mean ± σ): 6.677 μs ± 426.730 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▃▁▅▇▂ ▇█▅ ▂
█████▆▆▇▇█████▆▆▄▅▄▃▅▄▅▃▃▁▄▁▅▅▄▁▄▃▄▄▃▁▄▅▄▄▄▄▃▁▄▁▄▃▄▄▄▃▄▄▄▄▃ █
6.4 μs Histogram: log(frequency) by time 8.13 μs <
Memory estimate: 0 bytes, allocs estimate: 0.
julia> @benchmark vminimum($A)
BenchmarkTools.Trial: 10000 samples with 190 evaluations.
Range (min … max): 532.237 ns … 760.084 ns ┊ GC (min … max): 0.00% … 0.00%
Time (median): 555.921 ns ┊ GC (median): 0.00%
Time (mean ± σ): 551.762 ns ± 14.327 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▅▃ ▆▅ ▅█▅▂ ▂
████▇███▆▅▅▆▆▆▆▇▆▅████▇▇▇▇▆▆▄▄▇▆▅▅▅▅▆▆▅▄▅▆▄▄▅▅▄▅▃▄▄▄▃▁▁▃▃▃▃▄▃ █
532 ns Histogram: log(frequency) by time 608 ns <
Memory estimate: 0 bytes, allocs estimate: 0.
julia> A = rand(11, 12, 13, 14);
julia> minimum(A, dims=(1,3,4)) == vminimum(A, dims=(1,3,4))
true
julia> @benchmark minimum($A, dims=(1,3,4))
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
Range (min … max): 45.083 μs … 445.208 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 47.166 μs ┊ GC (median): 0.00%
Time (mean ± σ): 47.126 μs ± 5.362 μs ┊ GC (mean ± σ): 0.00% ± 0.00%
▄▄▄▅▂ ▅█▅▂ ▂
██████▆▇▇█████▇▇▇▆▅▅▅▅▅▅▅▅▄▄▅▅▄▅▆▅▅▅▄▅▄▅▃▄▁▁▄▅▃▄▄▃▃▃▃▃▄▄▄▃▁▃ █
45.1 μs Histogram: log(frequency) by time 57.2 μs <
Memory estimate: 816 bytes, allocs estimate: 18.
julia> @benchmark vminimum($A, dims=(1,3,4))
BenchmarkTools.Trial: 10000 samples with 7 evaluations.
Range (min … max): 4.673 μs … 569.113 μs ┊ GC (min … max): 0.00% … 98.82%
Time (median): 5.833 μs ┊ GC (median): 0.00%
Time (mean ± σ): 6.639 μs ± 19.905 μs ┊ GC (mean ± σ): 11.21% ± 3.70%
▁▂▄▇██▅▂
▆▁▁▁▁▁▁▁▁▂▄████████▇▅▄▂▂▂▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▂
4.67 μs Histogram: frequency by time 9.04 μs <
Memory estimate: 18.89 KiB, allocs estimate: 7.
```
##### `vmean`, `vstd`, `vvar`, etc. (implemented by direct loop generation)
```julia
julia> A = rand(11, 12, 13, 14);
julia> mean(A, dims=(1,3,4)) ≈ vmean(A, dims=(1,3,4))
true
julia> @benchmark mean($A, dims=(1,3,4))
BenchmarkTools.Trial: 10000 samples with 5 evaluations.
Range (min … max): 6.350 μs … 13.800 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 6.417 μs ┊ GC (median): 0.00%
Time (mean ± σ): 6.461 μs ± 224.303 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▃▆█▇█▆▇▅▆▄▅▃▄▂▃▁▂▁▂▂▂▃▂▃▁▂▁▂▁▂ ▁ ▁ ▃
████████████████████████████████▇█▆█▇▇▅▇▆▆▆▄▅▃▆▅▅▁▆▁▄▃▁▁▅▃▅ █
6.35 μs Histogram: log(frequency) by time 7.08 μs <
Memory estimate: 976 bytes, allocs estimate: 14.
julia> @benchmark vmean($A, dims=(1,3,4))
BenchmarkTools.Trial: 10000 samples with 7 evaluations.
Range (min … max): 5.012 μs … 7.696 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 5.137 μs ┊ GC (median): 0.00%
Time (mean ± σ): 5.147 μs ± 75.912 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▁▁▂▁█
▂▂▁▂▂▂▂▂▃▃▃▄█████████▇▆▅▄▅▃▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃
5.01 μs Histogram: frequency by time 5.41 μs <
Memory estimate: 272 bytes, allocs estimate: 4.
julia> A = rand(10_000);
julia> @benchmark mean($A)
BenchmarkTools.Trial: 10000 samples with 10 evaluations.
Range (min … max): 1.733 μs … 5.954 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 1.750 μs ┊ GC (median): 0.00%
Time (mean ± σ): 1.754 μs ± 93.796 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▅ █ █ ▅ ▃ ▂ ▁ ▂ ▁ ▂
▃▁▁▁▁▆▁▁▁▁█▁▁▁▁█▁▁▁▁▁█▁▁▁▁█▁▁▁▁█▁▁▁▁█▁▁▁▁▁█▁▁▁▁█▁▁▁▁█▁▁▁▁█ █
1.73 μs Histogram: log(frequency) by time 1.78 μs <
Memory estimate: 0 bytes, allocs estimate: 0.
julia> @benchmark vmean($A)
BenchmarkTools.Trial: 10000 samples with 169 evaluations.
Range (min … max): 636.834 ns … 887.331 ns ┊ GC (min … max): 0.00% … 0.00%
Time (median): 638.562 ns ┊ GC (median): 0.00%
Time (mean ± σ): 639.624 ns ± 9.350 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▄▂█▂
▂▃████▄▅▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂▁▂▂▂▂▂▂▂▂▂▁▂▂▁▂▁▂▂▂▁▂ ▂
637 ns Histogram: frequency by time 662 ns <
Memory estimate: 0 bytes, allocs estimate: 0.
julia> @benchmark std($A)
BenchmarkTools.Trial: 10000 samples with 7 evaluations.
Range (min … max): 4.179 μs … 24.470 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 4.202 μs ┊ GC (median): 0.00%
Time (mean ± σ): 4.219 μs ± 275.224 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▂█▇▆▂▃▂▂ ▂
████████▇▁▄▄▄▃▄▄▃▃▃▃▁▄▄▅▃▃▁▃▁▃▃▃▃▃▃▁▁▃▃▁▃▁▃▁▁▃▄▃▃▁▁▁▁▄▁▃▁▁▄ █
4.18 μs Histogram: log(frequency) by time 4.73 μs <
Memory estimate: 0 bytes, allocs estimate: 0.
julia> @benchmark vstd($A)
BenchmarkTools.Trial: 10000 samples with 10 evaluations.
Range (min … max): 1.421 μs … 4.858 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 1.475 μs ┊ GC (median): 0.00%
Time (mean ± σ): 1.466 μs ± 94.269 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▄ ▇ ▇ ▄ ▃ ▂ ▁ ▅ █ █ ▅ ▄ ▃ ▂ ▁ ▂
▆▁█▁█▁█▁█▁▁█▁█▁█▁█▁▁▅▁▆▁█▁█▁▁█▁█▁█▁█▁█▁▁█▁█▁█▁█▁▁█▁█▁▆▁▆▁▃ █
1.42 μs Histogram: log(frequency) by time 1.53 μs <
Memory estimate: 0 bytes, allocs estimate: 0.
```
##### Sorting-based functions
```julia
julia> A = rand(10_000);
julia> sort(A) == vsort!(A)
true
julia> median(A) == vmedian!(A)
true
```
#### TODO
* Median and percentile could be made more efficient with better SIMD sorting
* Other various summary statistics (mad, aad, etc.?)
* multithreaded vminimum, vmaximum, vextrema
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JuliaSIMD.github.io/VectorizedStatistics.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://JuliaSIMD.github.io/VectorizedStatistics.jl/dev
[ci-img]: https://github.com/JuliaSIMD/VectorizedStatistics.jl/workflows/CI/badge.svg
[ci-url]: https://github.com/JuliaSIMD/VectorizedStatistics.jl/actions
[codecov-img]: https://codecov.io/gh/JuliaSIMD/VectorizedStatistics.jl/branch/main/graph/badge.svg
[codecov-url]: https://codecov.io/gh/JuliaSIMD/VectorizedStatistics.jl
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 0.5.10 | f59703fbab297efe6ad09ef1dc656f8f0a21ad28 | docs | 241 | ```@meta
CurrentModule = VectorizedStatistics
```
# VectorizedStatistics
Documentation for [VectorizedStatistics](https://github.com/brenhinkeller/VectorizedStatistics.jl).
```@index
```
```@autodocs
Modules = [VectorizedStatistics]
```
| VectorizedStatistics | https://github.com/JuliaSIMD/VectorizedStatistics.jl.git |
|
[
"MIT"
] | 1.11.0 | fd88057905837360e9635a10efa63df4a01cb81b | code | 554 | # This file is a part of Julia. License is MIT: https://julialang.org/license
module LazyArtifacts
# reexport the Artifacts API
using Artifacts: Artifacts,
artifact_exists, artifact_path, artifact_meta, artifact_hash,
select_downloadable_artifacts, find_artifacts_toml, @artifact_str
export artifact_exists, artifact_path, artifact_meta, artifact_hash,
select_downloadable_artifacts, find_artifacts_toml, @artifact_str
# define a function for satisfying lazy Artifact downloads
using Pkg.Artifacts: ensure_artifact_installed
end
| LazyArtifacts | https://github.com/JuliaPackaging/LazyArtifacts.jl.git |
|
[
"MIT"
] | 1.11.0 | fd88057905837360e9635a10efa63df4a01cb81b | code | 1066 | # This file is a part of Julia. License is MIT: https://julialang.org/license
using LazyArtifacts
using Test
mktempdir() do tempdir
LazyArtifacts.Artifacts.with_artifacts_directory(tempdir) do
redirect_stderr(devnull) do
socrates_dir = artifact"socrates"
@test isdir(socrates_dir)
end
ex = @test_throws ErrorException artifact"HelloWorldC"
@test startswith(ex.value.msg, "Artifact \"HelloWorldC\" was not found")
end
end
# Need to set depwarn flag before testing deprecations
@test success(run(setenv(`$(Base.julia_cmd()) --depwarn=no --startup-file=no -e '
using Artifacts, Pkg
using Test
mktempdir() do tempdir
Artifacts.with_artifacts_directory(tempdir) do
redirect_stderr(devnull) do
socrates_dir = @test_logs(
(:warn, "using Pkg instead of using LazyArtifacts is deprecated"),
artifact"socrates")
@test isdir(socrates_dir)
end
end
end'`,
dir=@__DIR__)))
| LazyArtifacts | https://github.com/JuliaPackaging/LazyArtifacts.jl.git |
|
[
"MIT"
] | 1.11.0 | fd88057905837360e9635a10efa63df4a01cb81b | docs | 209 | # LazyArtifacts.jl
This is a wrapper package meant to bridge the gap for packages that want to use the `LazyArtifacts` stdlib as a dependency within packages that still support Julia versions older than 1.6.
| LazyArtifacts | https://github.com/JuliaPackaging/LazyArtifacts.jl.git |
|
[
"MIT"
] | 1.11.0 | fd88057905837360e9635a10efa63df4a01cb81b | docs | 260 | # Lazy Artifacts
```@meta
DocTestSetup = :(using LazyArtifacts)
```
In order for a package to download artifacts lazily, `LazyArtifacts` must be
explicitly listed as a dependency of that package.
For further information on artifacts, see [Artifacts](@ref).
| LazyArtifacts | https://github.com/JuliaPackaging/LazyArtifacts.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 827 | using Documenter, LiveServer
makedocs(
modules = [LiveServer],
format = Documenter.HTML(
# Use clean URLs, unless built as a "local" build
prettyurls = !("local" in ARGS),
# custom CSS
assets = ["assets/custom.css"]
),
sitename = "LiveServer.jl",
authors = "Jonas Asprion, Thibaut Lienart",
pages = [
"Home" => "index.md",
"Manual" => [
"Functionalities" => "man/functionalities.md",
"Extending LiveServer" => "man/extending_ls.md",
"LiveServer + Literate" => "man/ls+lit.md"
],
"Library" => [
"Public" => "lib/public.md",
"Internals" => "lib/internals.md",
],
], # end page
)
deploydocs(
repo = "github.com/tlienart/LiveServer.jl.git"
)
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 1278 | module LiveServer
import Sockets, Pkg, MIMEs
using Base.Filesystem
using Base.Threads: @spawn
using HTTP
using LoggingExtras
export serve, servedocs
#
# Environment variables
#
"""Script to insert on a page for live reload, see `client.html`."""
const BROWSER_RELOAD_SCRIPT = read(joinpath(@__DIR__, "client.html"), String)
"""Whether to display messages while serving or not, see [`verbose`](@ref)."""
const VERBOSE = Ref(false)
"""Whether to display debug messages while serving"""
const DEBUG = Ref(false)
"""The folder to watch, either the current one or a specified one (dir=...)."""
const CONTENT_DIR = Ref("")
"""List of files being tracked with WebSocket connections."""
const WS_VIEWERS = Dict{String,Vector{HTTP.WebSockets.WebSocket}}()
"""Keep track of whether an interruption happened while processing a websocket."""
const WS_INTERRUPT = Ref(false)
set_content_dir(d::String) = (CONTENT_DIR[] = d;)
reset_content_dir() = set_content_dir("")
set_verbose(b::Bool) = (VERBOSE[] = b;)
set_debug(b::Bool) = (DEBUG[] = b;)
reset_ws_interrupt() = (WS_INTERRUPT[] = false)
# issue https://github.com/tlienart/Franklin.jl/issues/977
setverbose = set_verbose
#
# Functions
#
include("file_watching.jl")
include("server.jl")
include("utils.jl")
end # module
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 6227 | """
WatchedFile
Struct for a file being watched containing the path to the file as well as the
time of last modification.
"""
mutable struct WatchedFile{T<:AbstractString}
path::T
mtime::Float64
end
"""
WatchedFile(f_path)
Construct a new `WatchedFile` object around a file `f_path`.
"""
WatchedFile(f_path::AbstractString) = WatchedFile(f_path, mtime(f_path))
"""
has_changed(wf::WatchedFile)
Check if a `WatchedFile` has changed. Returns -1 if the file does not exist, 0
if it does exist but has not changed, and 1 if it has changed.
"""
function has_changed(wf::WatchedFile)::Int
if !isfile(wf.path)
# isfile may return false for a file
# currently being written. Wait for 0.1s
# then retry once more:
sleep(0.1)
isfile(wf.path) || return -1
end
return Int(mtime(wf.path) > wf.mtime)
end
"""
set_unchanged!(wf::WatchedFile)
Set the current state of a `WatchedFile` as unchanged
"""
set_unchanged!(wf::WatchedFile) = (wf.mtime = mtime(wf.path);)
"""
set_unchanged!(wf::WatchedFile)
Set the current state of a `WatchedFile` as deleted (if it re-appears it will
immediately be marked as changed and trigger the callback).
"""
set_deleted!(wf::WatchedFile) = (wf.mtime = -Inf;)
"""
FileWatcher
Abstract Type for file watching objects such as [`SimpleWatcher`](@ref).
"""
abstract type FileWatcher end
"""
SimpleWatcher([callback]; sleeptime::Float64=0.1) <: FileWatcher
A simple file watcher. You can specify a callback function, receiving the path
of each file that has changed as an `AbstractString`, at construction or later
by the API function [`set_callback!`](@ref).
The `sleeptime` is the time waited between two runs of the loop looking for
changed files, it is constrained to be at least 0.05s.
"""
mutable struct SimpleWatcher <: FileWatcher
callback::Union{Nothing,Function} # callback triggered upon file change
task::Union{Nothing,Task} # asynchronous file-watching task
sleeptime::Float64 # sleep before checking for file changes
watchedfiles::Vector{WatchedFile} # list of files being watched
status::Symbol # flag caught by server
end
function SimpleWatcher(
callback::Union{Nothing,Function}=nothing;
sleeptime::Float64=0.1
)
return SimpleWatcher(
callback,
nothing,
max(0.05, sleeptime),
Vector{WatchedFile}(),
:runnable
)
end
"""
file_watcher_task!(w::FileWatcher)
Helper function that's spawned as an asynchronous task and checks for file
changes. This task is normally terminated upon an `InterruptException` and
shows a warning in the presence of any other exception.
"""
function file_watcher_task!(fw::FileWatcher)::Nothing
try
while true
sleep(fw.sleeptime)
# only check files if there's a callback to call upon changes
fw.callback === nothing && continue
for wf ∈ fw.watchedfiles
state = has_changed(wf)
if state == 1
# file has changed, set it unchanged and trigger callback
set_unchanged!(wf)
fw.callback(wf.path)
elseif state == -1
# file has been deleted, set the mtime to -Inf so that
# if it re-appears then it's immediately marked as changed
set_deleted!(wf)
end
end
end
catch err
fw.status = :interrupted
# an InterruptException is the normal way for this task to end
if !isa(err, InterruptException) && VERBOSE[]
@error "fw error" exception=(err, catch_backtrace())
end
end
return nothing
end
"""
set_callback!(fw::FileWatcher, callback::Function)
Set or change the callback function being executed upon a file change.
Can be "hot-swapped", i.e. while the file watcher is running.
"""
function set_callback!(fw::FileWatcher, callback::Function)::Nothing
prev_running = stop(fw) # returns true if was running
fw.callback = callback
prev_running && start(fw) # restart if it was running before
fw.status = :runnable
return nothing
end
"""
is_running(fw::FileWatcher)
Checks whether the file watcher is running.
"""
is_running(fw::FileWatcher) = (fw.task !== nothing) && !istaskdone(fw.task)
"""
start(fw::FileWatcher)
Start the file watcher and wait to make sure the task has started.
"""
function start(fw::FileWatcher)
is_running(fw) || (fw.task = @spawn file_watcher_task!(fw))
# wait until task runs to ensure reliable start (e.g. if `stop` called
# right after start)
while fw.task.state != :runnable
sleep(0.01)
end
end
"""
stop(fw::FileWatcher)
Stop the file watcher. The list of files being watched is preserved and new
files can still be added to the file watcher using `watch_file!`. It can be
restarted with `start`. Returns a `Bool` indicating whether the watcher was
running before `stop` was called.
"""
function stop(fw::FileWatcher)::Bool
was_running = is_running(fw)
if was_running
# this may fail as the task may get interrupted in between which would
# lead to an error "schedule Task not runnable"
try
schedule(fw.task, InterruptException(), error=true)
catch
end
# wait until sure the task is done
while !istaskdone(fw.task)
sleep(0.1)
end
end
return was_running
end
"""
is_watched(fw::FileWatcher, f_path::AbstractString)
Checks whether the file specified by `f_path` is being watched.
"""
function is_watched(fw::FileWatcher, f_path::AbstractString)
return any(wf -> wf.path == f_path, fw.watchedfiles)
end
"""
watch_file!(fw::FileWatcher, f_path::AbstractString)
Add a file to be watched for changes.
"""
function watch_file!(fw::FileWatcher, f_path::AbstractString)
if isfile(f_path) && !is_watched(fw, f_path)
push!(fw.watchedfiles, WatchedFile(f_path))
if VERBOSE[]
@info "[FileWatcher]: now watching '$f_path'"
println()
end
end
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 24506 | # https://github.com/fonsp/Pluto.jl/blob/bedc7767d76439477bae8a5165f4f39906f9064c/src/notebook/path%20helpers.jl#L3-L8
function detectwsl()
Sys.islinux() &&
isfile("/proc/sys/kernel/osrelease") &&
occursin(r"Microsoft|WSL"i, read("/proc/sys/kernel/osrelease", String))
end
"""
open_in_default_browser(url)
Open a URL in the ambient default browser.
Note: this was copied from Pluto.jl.
"""
function open_in_default_browser(url::AbstractString)::Bool
try
if Sys.isapple()
Base.run(`open $url`)
true
elseif Sys.iswindows() || detectwsl()
Base.run(`cmd.exe /s /c start "" /b $url`)
true
elseif Sys.islinux()
Base.run(`xdg-open $url`)
true
else
false
end
catch
false
end
end
"""
update_and_close_viewers!(wss::Vector{HTTP.WebSockets.WebSocket})
Take a list of viewers, i.e. WebSocket connections from a client,
send a message with data "update" to each of them (to trigger a page reload),
then close the connection. Finally, empty the list since all connections are
closing anyway and clients will re-connect from the re-loaded page.
"""
function update_and_close_viewers!(
wss::Vector{HTTP.WebSockets.WebSocket}
)::Nothing
ws_to_update_and_close = collect(wss)
empty!(wss)
# send update message to all viewers
@sync for wsᵢ in ws_to_update_and_close
isopen(wsᵢ.io) && @spawn begin
try
HTTP.WebSockets.send(wsᵢ, "update")
catch
end
end
end
# force close all viewers (these will be replaced by 'fresh' ones
# after the reload triggered by the update message)
@sync for wsi in ws_to_update_and_close
isopen(wsi.io) && @spawn begin
try
wsi.writeclosed = wsi.readclosed = true
close(wsi.io)
catch
end
end
end
return nothing
end
"""
file_changed_callback(f_path::AbstractString)
Function reacting to the change of the file at `f_path`. Is set as callback for
the file watcher.
"""
function file_changed_callback(f_path::AbstractString)::Nothing
if VERBOSE[]
@info "[LiveServer]: Reacting to change in file '$f_path'..."
end
if endswith(f_path, ".html")
# if html file, update viewers of this file only
# check the viewer still exists otherwise may error
# see issue https://github.com/asprionj/LiveServer.jl/issues/95
if haskey(WS_VIEWERS, f_path)
update_and_close_viewers!(WS_VIEWERS[f_path])
end
else
# otherwise (e.g. modification to a CSS file), update all viewers
foreach(update_and_close_viewers!, values(WS_VIEWERS))
end
return nothing
end
"""
get_fs_path(req_path::AbstractString; silent=false)
Return the filesystem path corresponding to a requested path, or an empty
String if the file was not found.
### Cases:
* an explicit request to an existing `index.html` (e.g.
`foo/bar/index.html`) is given --> serve the page and change WEB_DIR
unless a parent dir should be preferred (e.g. foo/ has an index.html)
* an implicit request to an existing `index.html` (e.g. `foo/bar/` or
`foo/bar`) is given --> same as previous case after appending the
`index.html`
* a request to a file is given (e.g. `/sample.jpeg`) --> figure out what it
is relative to, reconstruct the full system path and serve the file
* a request for a dir without index is given (e.g. `foo/bar`) --> serve a
dedicated index file listing the content of the directory.
"""
function get_fs_path(
req_path::AbstractString;
silent::Bool=false,
onlyfs::Bool=false
)
uri = HTTP.URI(req_path)
r_parts = HTTP.URIs.unescapeuri.(split(lstrip(uri.path, '/'), '/'))
fs_path = joinpath(CONTENT_DIR[], r_parts...)
onlyfs && return fs_path, :onlyfs
cand_index = ifelse(
r_parts[end] == "index.html",
fs_path,
joinpath(fs_path, "index.html")
)
resolved_fs_path = ""
case = :undecided
if isfile(cand_index)
resolved_fs_path = cand_index
case = :dir_with_index
elseif isfile(fs_path)
resolved_fs_path = fs_path
case = :file
elseif isdir(fs_path)
resolved_fs_path = joinpath(fs_path, "")
case = :dir_without_index
elseif req_path == "/"
resolved_fs_path = "."
case = :dir_without_index
else
for cand_404 in (
joinpath(CONTENT_DIR[], "404.html"),
joinpath(CONTENT_DIR[], "404", "index.html")
)
if isfile(cand_404)
resolved_fs_path = cand_404
case = :not_found_with_404
break
end
end
if isempty(resolved_fs_path)
case = :not_found_without_404
end
end
if DEBUG[] && !silent
@info """
👀 PATH RESOLUTION
request: < $req_path >
fs_path: < $fs_path >
resolved: < $resolved_fs_path >
case: < $case >
"""
println()
end
return resolved_fs_path, case
end
"""
lstrip_cdir(s)
Discard the 'CONTENT_DIR' part (passed via `dir=...`) of a path.
"""
function lstrip_cdir(s::AbstractString)::String
# we can't easily do a regex match here because CONTENT_DIR may
# contain regex characters such as `+` or `-`
ss = string(s)
if startswith(s, CONTENT_DIR[])
ss = ss[nextind(s, lastindex(CONTENT_DIR[])):end]
end
return string(lstrip(ss, ['/', '\\']))
end
"""
get_dir_list(dir::AbstractString) -> index_page::String
Generate a page which lists content at path `dir`.
"""
function get_dir_list(dir::AbstractString)::String
list = readdir(dir; join=true, sort=true)
sdir = dir
cdir = CONTENT_DIR[]
if !isempty(cdir)
sdir = join([cdir, lstrip_cdir(dir)], "/")
end
pagehtml(title="Directory listing") do io
write(io, """
<h1 style='margin-top: 1em;'>
Directory listing
</h1>
<h3>
<a href="/" alt="root">🏠</a>
<a href="/$(dirname(dir))" alt="parent dir">⬆️</a>
path: <code style='color:gray;'>$(sdir)</code>
</h3>
<hr>
<ul>
"""
)
list_files = [f for f in list if isfile(f)]
list_dirs = [d for d in list if d ∉ list_files]
for fname in list_files
link = lstrip_cdir(fname)
name = splitdir(fname)[end]
post = ifelse(islink(fname), " @", "")
write(io, """
<li><a href="/$(link)">$(name)$(post)</a></li>
"""
)
end
for fdir in list_dirs
link = lstrip_cdir(fdir)
# ensure ends with slash, see #135
link *= ifelse(endswith(link, "/"), "", "/")
name = splitdir(fdir)[end]
pre = "📂 "
post = ifelse(islink(fdir), " @", "")
write(io, """
<li><a href="/$(link)">$(pre)$(name)$(post)</a></li>
"""
)
end
write(io, """
</ul>
<hr>
<a href="https://github.com/tlienart/LiveServer.jl">
💻 LiveServer.jl
</a>
</body>
</html>
"""
)
end
end
function pagehtml(f::Base.Callable; title::AbstractString)
io = IOBuffer()
# Construct the shared head part of the HTML
write(io, """
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/spcss">
<title>$(title)</title>
<style>
a {text-decoration: none;}
</style>
</head>
<body>
"""
)
# Write the page-specific HTML (should only write the _contents_ of <body>...</body> tag)
f(io)
# Write the shared footer
write(io, """
</body>
</html>
"""
)
return String(take!(io))
end
"""
serve_file(fw, req::HTTP.Request; inject_browser_reload_script = true)
Handler function for serving files. This takes a file watcher, to which files
to be watched can be added, and a request (e.g. a path entered in a tab of the
browser), and converts it to the appropriate file system path.
The cases are as follows:
1. FILE: the path corresponds exactly to a file. If it's a html-like file,
LiveServer will try injecting the reloading `<script>` (see file
`client.html`) at the end, just before the `</body>` tag. Otherwise
we let the browser attempt to show it (e.g. if it's an image).
2. WEB-DIRECTORY: the path corresponds to a directory in which there is an
`index.html`, same action as (1) assuming the `index.html` is implicit.
3. PLAIN-DIRECTORY: the path corresponds to a directory in which there is not
an `index.html`, list the directory contents.
4. 404: not (1,2,3), a 404 is served.
All files served are added to the file watcher, which is responsible to check
whether they're already watched or not. Finally the file is served via a 200
(successful) response. If the file does not exist, a response with status 404
and message is returned.
"""
function serve_file(
fw::FileWatcher,
req::HTTP.Request;
inject_browser_reload_script::Bool = true,
allow_cors::Bool = false
)::HTTP.Response
#
# Check if the request is effectively a path to a directory and,
# if so, whether the path was given with a trailing `/`. If it is
# a path to a dir but without the trailing slash, send a redirect.
#
# Example: foo/bar --> foo/bar/
# foo/bar?search --> foo/bar/?search
# foo/bar#anchor --> foo/bar/#anchor
#
uri = HTTP.URI(req.target)
cand_dir = joinpath(CONTENT_DIR[], split(uri.path, '/')...)
if !endswith(uri.path, "/") && isdir(cand_dir)
target = string(HTTP.URI(uri; path=uri.path * "/"))
DEBUG[] && @info """
🔃 REDIRECT ($(req.target) --> $target)
"""
return HTTP.Response(301, ["Location" => target], "")
end
ret_code = 200
fs_path, case = get_fs_path(req.target)
# Fast paths to execute if building documentation isn't currently failing
if fw.status != :documenter_jl_error
if case == :not_found_without_404
html_404 = pagehtml(title = "404 Not Found") do io
write(io, """
<div style="width: 100%; max-width: 500px; margin: auto">
<h1 style="margin-top: 2em">404 Not Found</h1>
<p>
The requested URL [<code>$(req.target)</code>] does not correspond to a resource on the server.
</p>
<p>
Perhaps you made a typo in the URL, or the URL corresponds to a file that has been
deleted or renamed.
</p>
<p>
<a href="/">Home</a>
</p>
</div>
"""
)
end
return HTTP.Response(404, html_404)
elseif case == :not_found_with_404
ret_code = 404
elseif case == :dir_without_index
index_page = get_dir_list(fs_path)
return HTTP.Response(200, index_page)
end
end
ext = nothing
content = nothing
# If building the documentation is failing we return a special error page,
# otherwise we just read the file from disk.
if fw.status == :documenter_jl_error
ret_code = 500
ext = "html"
content = pagehtml(title = "Documenter.jl error") do io
write(io, """
<div style="width: 100%; max-width: 500px; margin: auto">
<h1 style="margin-top: 2em">Error building docs</h1>
<p>
An error occurred when rebuilding the documentation, please check the <code>servedocs()</code> output.
</p>
</div>
"""
)
end
else
#
# In what follows, fs_path points to a file
# :dir_with_index
# :file
# :not_found_with_404
# --> html-like: try to inject reload-script
# --> other: just get the browser to show it
#
ext = lstrip(last(splitext(fs_path)), '.') |> string
content = read(fs_path, String)
end
# build the response with appropriate mime type (this is inspired from Mux
# https://github.com/JuliaWeb/Mux.jl/blob/master/src/examples/files.jl)
content_type = let
mime_from_ext = MIMEs.mime_from_extension(ext, nothing)
if mime_from_ext !== nothing
MIMEs.contenttype_from_mime(mime_from_ext)
else
HTTP.sniff(content)
end
end
# avoid overly-specific text types so the browser can try rendering
# all text-like documents instead of offering to download all files
m = match(r"^text\/(.*?);(.*)$", content_type)
if m !== nothing
text_type = m.captures[1]
if text_type ∉ ("html", "javascript", "css")
content_type = "text/plain;$(m.captures[2])"
end
end
plain = "text/plain; charset=utf8"
for p in ("application/toml", "application/x-sh")
content_type = replace(content_type, p => plain)
end
# if html-like, try adding the browser-sync script to it
inject_reload = inject_browser_reload_script && (
startswith(content_type, "text/html") ||
startswith(content_type, "application/xhtml+xml")
)
if inject_reload
end_body_match = match(r"</body>", content)
if end_body_match === nothing
# no </body> tag found, trying to add the reload script at the
# end. This may fail.
content *= BROWSER_RELOAD_SCRIPT
else
end_body = prevind(content, end_body_match.offset)
# reconstruct the page with the reloading script
io = IOBuffer()
write(io, SubString(content, 1:end_body))
write(io, BROWSER_RELOAD_SCRIPT)
content_from = nextind(content, end_body)
content_to = lastindex(content)
write(io, SubString(content, content_from:content_to))
content = take!(io)
end
end
range_match = match(r"bytes=(\d+)-(\d+)" , HTTP.header(req, "Range", ""))
is_ranged = !isnothing(range_match)
headers = [
"Content-Type" => content_type,
]
if is_ranged
range = parse.(Int, range_match.captures)
push!(headers,
"Content-Range" =>
"bytes $(range[1])-$(range[2])/$(binary_length(content))"
)
content = @view content[1+range[1]:1+range[2]]
ret_code = 206
end
if allow_cors
push!(headers, "Access-Control-Allow-Origin" => "*")
end
push!(headers, "Content-Length" => string(binary_length(content)))
resp = HTTP.Response(ret_code, content)
resp.headers = HTTP.mkheaders(headers)
# add the file to the file watcher
watch_file!(fw, fs_path)
# return the response
return resp
end
binary_length(s::AbstractString) = ncodeunits(s)
binary_length(s::AbstractVector{UInt8}) = length(s)
function add_to_viewers(fs_path, ws)
if haskey(WS_VIEWERS, fs_path)
push!(WS_VIEWERS[fs_path], ws)
else
WS_VIEWERS[fs_path] = [ws]
end
return
end
"""
ws_tracker(ws::HTTP.WebSockets.WebSocket, target::AbstractString)
Adds the websocket connection to the viewers in the global dictionary
`WS_VIEWERS` to the entry corresponding to the targeted file.
"""
function ws_tracker(ws::HTTP.WebSockets.WebSocket)::Nothing
# NOTE: unless we're in the case of a 404, this file always exists because
# the query is generated just after serving it; the 404 case will return an
# empty path.
fs_path, case = get_fs_path(ws.request.target, silent=true)
if case in (:not_found_with_404, :not_found_without_404)
raw_fs_path, _ = get_fs_path(ws.request.target, onlyfs=true)
add_to_viewers(raw_fs_path, ws)
end
# add to list of html files being "watched" if the file is already being
# viewed, add ws to it (e.g. several tabs) otherwise add to dict
if case != :not_found_without_404
add_to_viewers(fs_path, ws)
end
# if DEBUG[]
# for (k, v) in WS_VIEWERS
# println("$k > $(length(v)) viewers")
# for (i, vi) in enumerate(v)
# println(" $i - $(vi.writeclosed)")
# end
# end
# end
try
# NOTE: browsers will drop idle websocket connections so this
# forces the websocket to stay open until it's closed by LiveServer (and
# not by the browser) upon writing a `update` message on the websocket.
# See update_and_close_viewers
while isopen(ws.io)
sleep(0.1)
end
catch err
# NOTE: there may be several sources of errors caused by the precise
# moment at which the user presses CTRL+C and after what events. In an
# ideal world we would check that none of these errors have another
# source but for now we make the assumption it's always the case (note
# that it can cause other errors than InterruptException, for instance
# it can cause errors due to stream not being available etc but these
# all have the same source).
# - We therefore do not propagate the error but merely store the
# information that there was a forcible interruption of the websocket
# so that the interruption can be guaranteed to be propagated.
WS_INTERRUPT[] = true
end
return nothing
end
"""
serve(filewatcher; ...)
Main function to start a server at `http://host:port` and render what is in the
current directory. (See also [`example`](@ref) for an example folder).
# Arguments
- `filewatcher`: a file watcher implementing the API described for
[`SimpleWatcher`](@ref) (which also is the default) messaging the viewers
(via WebSockets) upon detecting file changes.
- `port`: integer
- `dir`: string specifying where to launch the server if not the current
working directory.
- `debug`: bolean switch to make the server print debug messages.
- `verbose`: boolean switch to make the server print information about file
changes and connections.
- `coreloopfun`: function which can be run every 0.1 second while the
server is running; it takes two arguments: the cycle counter and the
filewatcher. By default the coreloop does nothing.
- `launch_browser`: boolean specifying whether to launch the ambient browser
at the localhost or not (default: false).
`allow_cors`: boolean allowing cross origin (CORS) requests to access the
server via the "Access-Control-Allow-Origin" header.
`preprocess_request`: function specifying the transformation of a request
before it is returned; its only argument is the current request.
# Example
```julia
LiveServer.example()
serve(host="127.0.0.1", port=8080, dir="example", launch_browser=true)
```
You should then see the `index.html` page from the `example` folder being
rendered. If you change the file, the browser will automatically reload the
page and show the changes.
"""
function serve(
fw::FileWatcher=SimpleWatcher(file_changed_callback);
# kwargs
host::String = "127.0.0.1",
port::Int = 8000,
dir::AbstractString = "",
debug::Bool = false,
verbose::Bool = debug,
coreloopfun::Function = (c, fw)->nothing,
preprocess_request::Function = identity,
inject_browser_reload_script::Bool = true,
launch_browser::Bool = false,
allow_cors::Bool = false
)::Nothing
set_verbose(verbose)
set_debug(debug)
if !isempty(dir)
isdir(dir) || throw(
ArgumentError("The specified dir '$dir' is not recognised.")
)
set_content_dir(dir)
end
# starts the file watcher
start(fw)
# make request handler
req_handler = HTTP.Handlers.streamhandler() do req
req = preprocess_request(req)
serve_file(
fw, req;
inject_browser_reload_script = inject_browser_reload_script,
allow_cors = allow_cors
)
end
old_logger = global_logger()
old_stderr = stderr
global_logger(
EarlyFilteredLogger(
log -> log._module !== HTTP.Servers,
global_logger()
)
)
server, port = get_server(host, port, req_handler)
host_str = ifelse(host == string(Sockets.localhost), "localhost", host)
url = "http://$host_str:$port"
println(
"✓ LiveServer listening on $url/ ...\n (use CTRL+C to shut down)"
)
launch_browser && open_in_default_browser(url)
# wait until user interrupts the LiveServer (using CTRL+C).
try
counter = 1
while true
if WS_INTERRUPT[] || fw.status == :interrupted
# rethrow the interruption (which may have happened during
# the websocket handling or during the file watching)
throw(InterruptException())
end
# run the auxiliary function if there is one (by default this does
# nothing)
coreloopfun(counter, fw)
# update the cycle counter and sleep (yields to other threads)
counter += 1
sleep(0.1)
end
catch err
if !isa(err, InterruptException)
if VERBOSE[]
@error "serve error" exception=(err, catch_backtrace())
end
throw(err)
end
finally
# cleanup: close everything that might still be alive
print("\n⋮ shutting down LiveServer… ")
# stop the filewatcher
stop(fw)
# close any remaining websockets
for wss ∈ values(WS_VIEWERS)
@sync for wsi in wss
isopen(wsi.io) && @spawn begin
try
wsi.writeclosed = wsi.readclosed = true
close(wsi.io)
catch
end
end
end
end
# empty the dictionary of viewers
empty!(WS_VIEWERS)
# shut down the server
HTTP.Servers.forceclose(server)
# reset other environment variables
reset_content_dir()
reset_ws_interrupt()
println("✓")
end
# given that LiveServer is interrupted via an InterruptException, we have
# to be extra careful that things are back as they were before, otherwise
# there's a high risk of the disgusting broken pipe error...
redirect_stderr(old_stderr)
global_logger(old_logger)
return nothing
end
"""
get_server(host, port, req_handler; incr=0)
Helper function to return a server, if the server is already occupied, try
incrementing the port until a free one is found (after a few tries an error
is thrown).
"""
function get_server(
host,
port,
req_handler;
incr::Int = 0
)
incr >= 10 && @error "couldn't find a free port in $incr tries"
try
server = HTTP.listen!(host, port; readtimeout=0, verbose=-1) do http::HTTP.Stream
if HTTP.WebSockets.isupgrade(http.message)
# upgrade to websocket and add to list of viewers and keep open
# until written to
HTTP.WebSockets.upgrade(ws_tracker, http)
else
# handle HTTP request
return req_handler(http)
end
end
return server, port
catch
return get_server(host, port+1, req_handler; incr=incr+1)
end
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 13468 | """
servedocs_callback!(args...)
Custom callback used in [`servedocs`](@ref) triggered when a file is modified.
If the file is `docs/make.jl`, the callback will check whether any new files
have subsequently been generated in the `docs/src` folder and add them to the
watched files, it will also remove any file that may have been deleted or
renamed.
If the file is either in `docs/src`, a pass of Documenter is triggered to
regenerate the documentation, subsequently the LiveServer will render the
pages produced in `docs/build`.
## Arguments
See the docs of the parent function `servedocs`.
"""
function servedocs_callback!(
dw::SimpleWatcher,
fp::AbstractString,
path2makejl::AbstractString,
literate::Union{Nothing,String},
skip_dirs::Vector{String},
skip_files::Vector{String},
include_dirs::Vector{String},
include_files::Vector{String},
foldername::String,
buildfoldername::String)
# ignore things happening in the build folder (generated files etc)
startswith(fp, joinpath(foldername, buildfoldername)) && return nothing
# ignore files in skip_dirs and skip_files (unless the file is in include_files)
if !(fp in include_files)
for dir in skip_dirs
startswith(fp, dir) && return nothing
end
for file in skip_files
fp == file && return nothing
end
end
# if the file that was changed is the `make.jl` file, assume that maybe
# new files have been generated and so refresh the vector of watched files
if fp == path2makejl
# it's easier to start from scratch (takes negligible time)
empty!(dw.watchedfiles)
scan_docs!(dw, foldername, path2makejl, literate, include_dirs, include_files)
end
# Run a Documenter pass
try
Main.include(abspath(path2makejl))
dw.status = :runnable
catch ex
# If there was an error, record it so that an error is displayed to the user
dw.status = :documenter_jl_error
end
file_changed_callback(fp)
return
end
"""
scan_docs!(dw::SimpleWatcher, args...)
Scans the `docs/` folder and add all relevant files to the watched files.
## Arguments
See the docs of the parent function `servedocs`.
"""
function scan_docs!(dw::SimpleWatcher,
foldername::String,
path2makejl::String,
literate::Union{Nothing,String},
include_dirs::Vector{String},
include_files::Vector{String},
)::Nothing
# Typical expected structure:
# docs
# ├── make.jl
# └── src
# ├── *
# └── *
src = joinpath(foldername, "src")
if !isdir(foldername) || !isdir(src)
error("I didn't find a $foldername/ or $foldername/src/ folder.")
end
# watch the make.jl file as well as
push!(dw.watchedfiles, WatchedFile(path2makejl))
# include all files in the docs/src directory
if isdir(foldername)
# add all files in `docs/src` to watched files
for (root, _, files) ∈ walkdir(joinpath(foldername, "src")), file ∈ files
push!(dw.watchedfiles, WatchedFile(joinpath(root, file)))
end
end
# include all files in user-specified include directories
for idir in filter(isdir, include_dirs)
for (root, _, files) in walkdir(idir), file in files
push!(dw.watchedfiles, WatchedFile(joinpath(root, file)))
end
end
# include all user-specified files
for f in filter(isfile, include_files)
push!(dw.watchedfiles, WatchedFile(f))
end
# if the user is not using Literate, return early
literate === nothing && return
# If the user gave a specific directory for literate files, add all the
# files in that directory to the watched files.
# If the user did not (literate === "") then these files are already watched.
if !isempty(literate)
isdir(literate) || error("I didn't find the provided literate folder $literate.")
for (root, _, files) ∈ walkdir(literate), file ∈ files
push!(dw.watchedfiles, WatchedFile(joinpath(root, file)))
end
end
# When using Literate, each script *.jl is assumed to generate a corresponding *.md
# file. Only the source (*.jl) file should be watched to avoid an infinite loop where
# 1. the script is executed, generates the .md file
# 2. the .md file is seen as modified, triggers the make.jl file
# 3. the make.jl file executes the script (↩1)
# So here we remove from the watchlist all files.md that have a files.jl with the same path.
remove = Int[]
if isempty(literate)
# assumption is that the scripts are in `docs/src/...` and that the
# generated markdown goes in exactly the same spot so for instance:
# docs
# └── src
# ├── index.jl
# └── index.md
for wf ∈ dw.watchedfiles
spath = splitext(wf.path)
# ignore non `*.jl` files
spath[2] == ".jl" || continue
# if a `.jl` file is found, check if there's any corresponding `.md`
# file and, if so, remove that file from the watched files to avoid ∞
k = findfirst(e -> splitext(e.path) == (spath[1], ".md"), dw.watchedfiles)
k === nothing || push!(remove, k)
end
else
# assumption is that the scripts are in a specific folder and that the
# generated markdown goes in `docs/src` with the same relative path
# so for instance:
# docs
# ├── literate
# │ └── index.jl
# └── src
# └── index.md
# the logic is otherwise the same as above.
for (root, _, files) ∈ walkdir(literate), file ∈ files
spath = splitext(joinpath(root, file))
spath[2] == ".jl" || continue
path = replace(spath[1], Regex("^$literate") => joinpath(foldername, "src"))
k = findfirst(e -> splitext(e.path) == (path, ".md"), dw.watchedfiles)
k === nothing || push!(remove, k)
end
end
deleteat!(dw.watchedfiles, remove)
return
end
"""
servedocs(; kwargs...)
Can be used when developing a package to run the `docs/make.jl` file from
Documenter.jl and then serve the `docs/build` folder with LiveServer.jl.
This function assumes you are in the directory `[MyPackage].jl` with a
subfolder `docs`.
## Keyword Arguments
* `verbose=false`: boolean switch to make the server print information about
file changes and connections.
* `doc_env=false`: a boolean switch to make the server start by activating the
doc environment or not (i.e. the `Project.toml` in `docs/`).
* `literate=nothing`: see `literate_dir`.
* `literate_dir=nothing`: Path to a directory containing Literate scripts if
these are not simply under `docs/src`.
See also the docs for information about how to
work with Literate.
* `skip_dir=""`: a path starting with `docs/` where modifications should not
trigger the generation of the docs, this is useful for instance
if you're using Weave and Weave generates some files in
`docs/src/examples` in which case you should set
`skip_dir=joinpath("docs","src","examples")`.
* `skip_dirs=[]`: same as `skip_dir` but for a list of such dirs. Takes
precedence over `skip_dir`.
* `skip_files=[]`: a vector of files that should not trigger regeneration.
* `include_dirs=[]`: extra source directories to watch
(in addition to `joinpath(foldername, "src")`).
* `include_files=[]`: extra source files to watch. Takes precedence over
`skip_dirs` so can e.g. be used to track individual
files in an otherwise skipped directory.
* `foldername="docs"`: specify a different path for the content.
* `buildfoldername="build"`: specify a different path for the build.
* `makejl="make.jl"`: path of the script generating the documentation relative
to `foldername`.
* `host="127.0.0.1"`: where the server will start.
* `port=8000`: port number.
* `launch_browser=false`: specifies whether to launch a browser at the
localhost URL or not.
"""
function servedocs(;
verbose::Bool=false,
debug::Bool=false,
doc_env::Bool=false,
literate::Union{Nothing,String}=nothing,
literate_dir::Union{Nothing,String}=literate,
skip_dir::String="",
skip_dirs::Vector{String}=String[],
skip_files::Vector{String}=String[],
include_dirs::Vector{String}=String[],
include_files::Vector{String}=String[],
foldername::String="docs",
buildfoldername::String="build",
makejl::String="make.jl",
host::String="127.0.0.1",
port::Int=8000,
launch_browser::Bool=false
)::Nothing
# skip_dirs takes precedence over skip_dir
if isempty(skip_dirs) && !isempty(skip_dir)
skip_dirs = [skip_dir]
end
push!(skip_dirs, joinpath(foldername, buildfoldername))
skip_dirs = abspath.(skip_dirs)
skip_files = abspath.(skip_files)
include_dirs = abspath.(include_dirs)
include_files = abspath.(include_files)
# literate_dir takes precedence over literate
if isnothing(literate_dir) && !isnothing(literate)
literate_dir = literate
end
if !isnothing(literate_dir)
literate_dir = abspath(literate_dir)
end
path2makejl = joinpath(foldername, makejl)
# The file watcher is a default SimpleWatcher with a custom
# callback
docwatcher = SimpleWatcher()
set_callback!(
docwatcher,
fp -> servedocs_callback!(
docwatcher, abspath(fp), path2makejl,
literate_dir,
skip_dirs, skip_files, include_dirs, include_files,
foldername, buildfoldername
)
)
# Scan the folder and update the list of files to watch
scan_docs!(
docwatcher, foldername, path2makejl,
literate_dir, include_dirs, include_files
)
# activate the doc environment if required
doc_env && Pkg.activate(joinpath(foldername, "Project.toml"))
# trigger a first pass of Documenter (& possibly Literate)
Main.include(abspath(path2makejl))
# note the `docs/build` exists here given that if we're here it means
# the documenter pass did not error and, therefore that a docs/build
# has been generated.
# So we can now serve.
serve(
docwatcher,
host=host,
port=port,
dir=joinpath(foldername, buildfoldername),
verbose=verbose,
debug=debug,
launch_browser=launch_browser
)
# when the serve loop is interrupted, de-activate the environment
doc_env && Pkg.activate()
return
end
#
# Miscellaneous utils
#
"""
example()
Simple function to copy an example website folder to the current working directory that can be
watched by the LiveServer to get an idea of how things work.
### Example
```julia
LiveServer.example()
cd("example")
serve()
```
"""
function example(; basedir="")
isempty(basedir) && (basedir = pwd())
cp(joinpath(dirname(dirname(pathof(LiveServer))), "example"), joinpath(basedir, "example"))
end
#
# Generate example repo for servedocs
#
const INDEX_MD = raw"""
# Test
A link to the [other page](/man/pg1/)
"""
const PG1_JL = raw"""
# # Test literate
# We can include some code like so:
f(x) = x^5
f(5)
"""
const MAKE_JL = raw"""
using Documenter, Literate
src = joinpath(@__DIR__, "src")
lit = joinpath(@__DIR__, "literate")
for (root, _, files) ∈ walkdir(lit), file ∈ files
splitext(file)[2] == ".jl" || continue
ipath = joinpath(root, file)
opath = splitdir(replace(ipath, lit=>src))[1]
Literate.markdown(ipath, opath)
end
makedocs(
sitename = "testlit",
pages = ["Home" => "index.md",
"Other page" => "man/pg1.md"]
)
"""
"""
servedocs_literate_example(dir="servedocs_literate_example")
Generates a folder with the right structure for servedocs+literate example.
Requires Documenter and Literate.
You can then `cd` to that folder and use servedocs:
```
julia> using LiveServer, Documenter, Literate
julia> LiveServer.servedocs_literate_example()
julia> cd("servedocs_literate_example")
julia> servedocs(literate=joinpath("docs", "literate"))
```
"""
function servedocs_literate_example(dirname="servedocs_literate_example")
isdir(dirname) && rm(dirname, recursive=true)
mkdir(dirname)
# folder structure
src = joinpath(dirname, "src")
mkdir(src)
write(joinpath(src, "$dirname.jl"), "module $dirname\n foo()=1\n end")
docs = joinpath(dirname, "docs")
mkdir(docs)
src = joinpath(docs, "src")
lit = joinpath(docs, "literate")
man = joinpath(lit, "man")
mkdir(src)
mkdir(lit)
mkdir(man)
write(joinpath(src, "index.md"), INDEX_MD)
write(joinpath(man, "pg1.jl"), PG1_JL)
write(joinpath(docs, "make.jl"), MAKE_JL)
return
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 2675 | # create files in a temporary dir that we can modify
const tmpdir = mktempdir()
const file1 = joinpath(tmpdir, "file1")
const file2 = joinpath(tmpdir, "file2")
write(file1, ".")
write(file2, ".")
@testset "Watcher/WatchedFile struct " begin
wf1 = LS.WatchedFile(file1)
wf2 = LS.WatchedFile(file2)
# Basic struct
@test wf1.path == file1
@test wf2.path == file2
@test wf1.mtime == mtime(file1)
@test wf2.mtime == mtime(file2)
# Apply change and check if it's detecte
t1 = time()
sleep(FS_WAIT)
write(file1, "hello")
sleep(FS_WAIT)
@test LS.has_changed(wf1) == 1
@test LS.has_changed(wf2) == 0
# Set state as unchanged
LS.set_unchanged!(wf1)
@test LS.has_changed(wf1) == 0
@test wf1.mtime > t1
end
@testset "Watcher/SimpleWatcher struct" begin
sw = LS.SimpleWatcher()
isa(sw, LS.FileWatcher)
sw1 = LS.SimpleWatcher(identity, sleeptime=0.0)
# Base constructor check
@test sw.callback === nothing
@test sw.task === nothing
@test sw.sleeptime == 0.1
@test isempty(sw.watchedfiles)
@test eltype(sw.watchedfiles) == LS.WatchedFile
@test sw1.sleeptime == 0.05 # via the clamping
@test sw1.callback(2) == 2 # identity function
@test sw1.callback("blah") == "blah"
@test isempty(sw1.watchedfiles)
@test sw1.task === nothing
end
@testset "Watcher/watch file routines" begin
sw = LS.SimpleWatcher(identity)
LS.watch_file!(sw, file1)
LS.watch_file!(sw, file2)
@test sw.watchedfiles[1].path == file1
@test sw.watchedfiles[2].path == file2
# is_watched
@test LS.is_watched(sw, file1)
@test LS.is_watched(sw, file2)
# is_running?
@test !LS.is_running(sw)
LS.start(sw)
sleep(0.001)
@test LS.is_running(sw)
@test LS.stop(sw)
@test !LS.is_running(sw)
#
# modify callback to something that will eventually throw an error
#
LS.set_callback!(sw, log)
@test sw.callback(exp(1.0)) ≈ 1.0
LS.start(sw)
sleep(0.001)
# causing a modification will generate an error because the callback
# function will fail on a string
cray = Crayon(foreground=:cyan, bold=true)
println(cray, "\n⚠ Deliberately causing an error to be displayed and handled...\n")
write(file1, "modif")
sleep(0.25) # needs to be sufficient to give time for propagation.
@test sw.status == :interrupted
#
# deleting files
#
file3 = joinpath(tmpdir, "file3")
write(file3, "hello")
sw = LS.SimpleWatcher(identity)
LS.watch_file!(sw, file1)
LS.watch_file!(sw, file2)
LS.watch_file!(sw, file3)
@test length(sw.watchedfiles) == 3
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 263 | using LiveServer, Test, Crayons, Sockets, HTTP
using Base.Threads: @spawn
const LS = LiveServer
# depending on the OS, the resolution of stat(f).mtime can be over a second.
const FS_WAIT = 1.1
include("utils.jl")
include("file_watching.jl")
include("server.jl")
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 8400 | @testset "Server/Paths " begin
# requested path --> a filesystem path
bk = pwd()
cd(joinpath(@__DIR__, ".."))
req = "tmp"
@test LS.get_fs_path(req) == ("", :not_found_without_404)
req = "/test/dummies/foofile"
@test LS.get_fs_path(req) == ("test/dummies/foofile", :file)
req = "/test/dummies/index.html"
@test LS.get_fs_path(req) == ("test/dummies/index.html", :dir_with_index)
req = "/test/dummies/r%C3%A9sum%C3%A9/"
@test LS.get_fs_path(req) == ("test/dummies/résumé/index.html", :dir_with_index)
req = "/test/dummies/"
@test LS.get_fs_path(req) == ("test/dummies/index.html", :dir_with_index)
req = "/test/dummies/?query=string"
@test LS.get_fs_path(req) == ("test/dummies/index.html", :dir_with_index)
cd(bk)
end
#=
NOTE: if extending these tests, please be careful. As they involve @async tasks which,
themselves, spawn async tasks, if your tests fail for some reason you will HAVE to kill
the current Julia session and restart one otherwise the tasks that haven't been killed
due to the tests not being finished properly will keep running and may clash with new
tasks that you will try to start.
=#
@testset "Server/Step-by-step testing " begin
#
# STEP 0: cd to dummies
#
bk = pwd()
cd(dirname(dirname(pathof(LiveServer))))
cd(joinpath("test", "dummies"))
port = 8123
isdir("css") && rm("css", recursive=true)
isfile("tmp.html") && rm("tmp.html")
isdir("404") && rm("404", recursive=true)
write("tmp.html", "blah")
mkdir("css")
write("css/foo.css", "body { color: pink; }")
#
# STEP 1: launching the listener
#
# define filewatcher outside so that can follow it
fw = LS.SimpleWatcher(LS.file_changed_callback)
task = @spawn serve(fw; port=port)
sleep(0.1) # give it time to get started
# there should be a callback associated with fw now
@test fw.status == :runnable
# the filewatcher should be running
@test LS.is_running(fw)
# it also should be empty thus far
@test isempty(fw.watchedfiles)
#
# STEP 2: triggering a request
#
response = HTTP.get("http://localhost:$port/")
@test response.status == 200
# the browser script should be appended
@test String(response.body) == replace(read("index.html", String),
"</body>"=>"$(LS.BROWSER_RELOAD_SCRIPT)</body>")
hdict = Dict(response.headers)
@test occursin("text/html", hdict["Content-Type"])
# if one asks for something incorrect, a 404 should be returned
response = HTTP.get("http://localhost:$port/no.html"; status_exception=false)
@test response.status == 404
@test occursin("404 Not Found", String(response.body))
# test custom 404.html page
mkdir("404"); write("404/index.html", "custom 404")
response = HTTP.get("http://localhost:$port/no.html"; status_exception=false)
@test response.status == 404
@test occursin("custom 404", String(response.body))
# if one asks for something without a </body>, it should just be appended
response = HTTP.get("http://localhost:$port/tmp.html")
@test response.status == 200
@test String(response.body) == read("tmp.html", String) * LS.BROWSER_RELOAD_SCRIPT
response = HTTP.get("http://localhost:$port/css/foo.css")
@test String(response.body) == read("css/foo.css", String)
@test response.status == 200
# we asked earlier for index.html therefore that file should be followed
@test fw.watchedfiles[1].path == "index.html"
# also 404
@test fw.watchedfiles[2].path == "404/index.html"
# also tmp
@test fw.watchedfiles[3].path == "tmp.html"
# and the css
@test fw.watchedfiles[4].path == "css/foo.css"
# if we modify the file, it should trigger the callback function which should open
# and then subsequently close a websocket. We check this happens properly by adding
# our own sentinel websocket
function makews()
req = HTTP.Request()
return HTTP.WebSockets.WebSocket(
HTTP.Connection(IOBuffer()), req, req.response; client=false
)
end
sentinel = makews()
LS.WS_VIEWERS["tmp.html"] = [sentinel]
@test sentinel.io.io.writable
write("tmp.html", "something new")
sleep(0.5)
# the sentinel websocket should be closed
@test !sentinel.io.io.writable
# the websockets should have been flushed
@test isempty(LS.WS_VIEWERS["tmp.html"])
# let's do this again with an infra file which will ping all websockets
sentinel1 = makews()
sentinel2 = makews()
push!(LS.WS_VIEWERS["tmp.html"], sentinel1)
LS.WS_VIEWERS["css/foo.css"] = [sentinel2]
write("css/foo.css", "body { color:blue; }")
sleep(0.5)
# all sentinel websockets should be closed
@test !sentinel1.io.io.writable
@test !sentinel2.io.io.writable
# Mimic an error when building documentation with Documenter.jl. When this
# happens servedocs_callback!() will set the watcher status to
# :documenter_jl_error.
fw.status = :documenter_jl_error
# Now any requests should give us the custom error page
response = HTTP.get("http://localhost:$port/"; status_exception=false)
body_str = String(response.body)
@test response.status == 500
@test occursin("error occurred when rebuilding", body_str)
# And they should include the browser reload script so they automatically
# reload when the docs build again.
@test occursin(LS.BROWSER_RELOAD_SCRIPT, body_str)
# Reset the watcher status for the rest of the tests
fw.status = :runnable
# if we remove the files, it shall stop following it
rm("tmp.html")
rm("css", recursive=true)
rm("404", recursive=true)
sleep(0.5)
# everything is still watched (#160)
@test length(fw.watchedfiles) == 4
#
# SHUTTING DOWN
#
# this should have interrupted the server, so it should be possible
# to restart one on the same port (otherwise this will throw an error, already in use)
schedule(task, InterruptException(), error=true)
sleep(1.5) # give it time to get done
@test istaskdone(task)
@test begin
server = Sockets.listen(port)
sleep(0.1)
close(server)
true
end == true
# Check that WS_FILES is properly destroyed
isempty(LS.WS_VIEWERS)
cd(bk)
end
@testset "Server/ws_tracker testing " begin
bk = pwd()
cd(mktempdir())
write("test_file.html", "Hello!")
server = Sockets.listen(Sockets.localhost, 8001)
io = Sockets.connect(Sockets.localhost, 8001)
key = "k5zQsAMXfFlvmWIE/YCiEg=="
s = HTTP.Stream(
HTTP.Request(
"GET",
"http://localhost:8562/test_file.html",
[
"Connection" => "upgrade",
"Upgrade" => "websocket",
"Sec-WebSocket-Key" => key,
"Sec-WebSocket-Version" => "13"
]
),
HTTP.Connection(io)
)
fs_path, _ = LS.get_fs_path(s.message.target)
@test fs_path == "test_file.html"
tsk = @spawn LS.HTTP.WebSockets.upgrade(LS.ws_tracker, s)
sleep(1.0)
# the websocket should have been added to the list
@test LS.WS_VIEWERS[fs_path] isa Vector{HTTP.WebSockets.WebSocket}
@test length(LS.WS_VIEWERS[fs_path]) >= 1
# simulate a "good" closure (an event caused a write on the websocket and then closes it)
ws = LS.WS_VIEWERS[fs_path][1]
close(ws)
sleep(1.0)
@test istaskdone(tsk)
@test !LS.WS_INTERRUPT[]
io = Sockets.connect(Sockets.localhost, 8001)
key = "k5zQsAMXfFlvmWIE/YCiEg=="
s = HTTP.Stream(
HTTP.Request(
"GET",
"http://localhost:8562/test_file.html",
[
"Connection" => "upgrade",
"Upgrade" => "websocket",
"Sec-WebSocket-Key" => key,
"Sec-WebSocket-Version" => "13"
]
),
HTTP.Connection(io)
)
tsk = @spawn LS.HTTP.WebSockets.upgrade(LS.ws_tracker, s)
sleep(1.0)
# simulate a "bad" closure
schedule(tsk, InterruptException(), error=true)
sleep(5.1)
@test istaskdone(tsk)
@test LS.WS_INTERRUPT[]
@test length(LS.WS_VIEWERS[fs_path]) == 2
# cleanup
close(server)
empty!(LS.WS_VIEWERS)
cd(bk)
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 7033 | @testset "utils/servedocs-callback " begin
bk = pwd()
cd(mktempdir())
mkdir("docs")
mkdir(joinpath("docs", "src"))
write(joinpath("docs", "src", "index.md"), "Index file")
write(joinpath("docs", "src", "index2.md"), "Random file")
thispath = pwd()
makejl = joinpath("docs", "make.jl")
# this is a slight of hand to increment a counter when `make.jl` is executed so that
# we can check it's executed the appropriate number of times
write("tempfile", "0")
write(makejl,
"""
c = parse(Int, read(\"tempfile\", String)); write(\"tempfile\", \"\$(c+1)\")
"""
)
readmake() = parse(Int, read("tempfile", String))
include(abspath(makejl))
@test readmake() == 1
def = (nothing, String[], String[], String[], String[], "docs", "build")
# callback function
dw = LS.SimpleWatcher()
LS.servedocs_callback!(dw, makejl, makejl, def...)
@test length(dw.watchedfiles) == 3
@test dw.watchedfiles[1].path == joinpath("docs", "make.jl")
@test dw.watchedfiles[2].path == joinpath("docs", "src", "index.md")
@test dw.watchedfiles[3].path == joinpath("docs", "src", "index2.md")
@test readmake() == 2
# let's now remove `index2.md`
rm(joinpath("docs", "src", "index2.md"))
LS.servedocs_callback!(dw, makejl, makejl, def...)
# the file has been removed
@test length(dw.watchedfiles) == 2
@test readmake() == 3
# let's check there's an appropriate trigger for index
LS.servedocs_callback!(dw, joinpath("docs", "src", "index.md"), makejl, def...)
@test length(dw.watchedfiles) == 2
@test readmake() == 4
# Modify make.jl to force an error
write(makejl, "error()")
LS.servedocs_callback!(dw, joinpath("docs", "src", "index.md"), makejl, def...)
@test dw.status == :documenter_jl_error
# Fixing the error should reset the status
write(makejl, "42")
LS.servedocs_callback!(dw, joinpath("docs", "src", "index.md"), makejl, def...)
@test dw.status == :runnable
cd(bk)
end
@testset "utils/servedocs-scan-docs " begin
bk = pwd()
cd(mktempdir())
dw = LS.SimpleWatcher()
# error if there's no docs/ folder
cray = Crayon(foreground=:cyan, bold=true)
println(cray, "\n⚠ Deliberately causing an error to be displayed and handled...\n")
@test_throws ErrorException LS.scan_docs!(dw, "docs", "", "", String[], String[])
empty!(dw.watchedfiles)
mkdir("docs")
mkdir(joinpath("docs", "src"))
write(joinpath("docs", "src", "index.md"), "Index file")
write(joinpath("docs", "src", "index2.md"), "Random file")
write(joinpath("docs", "make.jl"), "1+1")
mkdir("extradir")
write(joinpath("extradir", "extra.md"), "Extra source file")
mkdir("extradir2")
write(joinpath("extradir2", "extra2.md"), "Extra source file 2")
mkdir(joinpath("docs", "lit"))
write(joinpath("docs", "lit", "index.jl"), "1+1")
LS.scan_docs!(dw, "docs", "docs/make.jl", joinpath("docs", "lit"), [abspath("extradir")], [abspath("extradir2", "extra2.md")])
@test length(dw.watchedfiles) == 5 # index.jl, index2.md, make.jl, extra.md, extra2.md
@test endswith(dw.watchedfiles[1].path, "make.jl")
@test endswith(dw.watchedfiles[2].path, "index2.md")
@test endswith(dw.watchedfiles[3].path, "extra.md")
@test endswith(dw.watchedfiles[4].path, "extra2.md")
@test endswith(dw.watchedfiles[5].path, "index.jl")
cd(bk)
end
@testset "utils/servedocs-callback with foldername " begin
bk = pwd()
cd(mktempdir())
mkdir("site")
mkdir(joinpath("site", "src"))
write(joinpath("site", "src", "index.md"), "Index file")
write(joinpath("site", "src", "index2.md"), "Random file")
makejl = joinpath("site", "make.jl")
# this is a slight of hand to increment a counter when `make.jl` is executed so that
# we can check it's executed the appropriate number of times
write("tempfile", "0")
write(makejl, "c = parse(Int, read(\"tempfile\", String)); write(\"tempfile\", \"\$(c+1)\")")
readmake() = parse(Int, read("tempfile", String))
include(abspath(makejl))
@test readmake() == 1
# callback function
dw = LS.SimpleWatcher()
LS.servedocs_callback!(dw, makejl, makejl, "", String[], String[], String[], String[], "site", "build")
@test length(dw.watchedfiles) == 3
@test dw.watchedfiles[1].path == joinpath("site", "make.jl")
@test dw.watchedfiles[2].path == joinpath("site", "src", "index.md")
@test dw.watchedfiles[3].path == joinpath("site", "src", "index2.md")
@test readmake() == 2
# let's now remove `index2.md`
rm(joinpath("site", "src", "index2.md"))
LS.servedocs_callback!(dw, makejl, makejl, "", String[], String[], String[], String[], "site", "build")
# the file has been removed
@test length(dw.watchedfiles) == 2
@test readmake() == 3
# let's check there's an appropriate trigger for index
LS.servedocs_callback!(dw, joinpath("site", "src", "index.md"), makejl, "", String[], String[], String[], String[], "site", "build")
@test length(dw.watchedfiles) == 2
@test readmake() == 4
cd(bk)
end
@testset "utils/servedocs-scan-docs with foldername " begin
bk = pwd()
cd(mktempdir())
dw = LS.SimpleWatcher()
# error if there's no docs/ folder
cray = Crayon(foreground=:cyan, bold=true)
println(cray, "\n⚠ Deliberately causing an error to be displayed and handled...\n")
@test_throws ErrorException LS.scan_docs!(dw, "site", "site", "", String[], String[])
empty!(dw.watchedfiles)
mkdir("site")
mkdir(joinpath("site", "src"))
write(joinpath("site", "src", "index.md"), "Index file")
write(joinpath("site", "src", "index2.md"), "Random file")
write(joinpath("site", "make.jl"), "1+1")
mkdir(joinpath("site", "lit"))
write(joinpath("site", "lit", "index.jl"), "1+1")
LS.scan_docs!(dw, "site", "site/make.jl", joinpath("site", "lit"), String[], String[])
@test length(dw.watchedfiles) == 3 # index.jl, index2.md, make.jl
@test endswith(dw.watchedfiles[1].path, "make.jl")
@test endswith(dw.watchedfiles[2].path, "index2.md")
@test endswith(dw.watchedfiles[3].path, "index.jl")
cd(bk)
end
@testset "Misc utils " begin
LS.set_verbose(false)
@test !LS.VERBOSE.x
LS.set_verbose(true)
@test LS.VERBOSE.x
LS.set_verbose(false) # we don't want the tests to show lots of stuff
bk = pwd()
cd(mktempdir())
LS.example()
@test isdir("example")
@test isfile("example/index.html")
cd(bk)
end
@testset "utils/servedocs_literate " begin
bk = pwd()
tdir = mktempdir()
cd(tdir)
LiveServer.servedocs_literate_example("test")
@test isdir("test")
@test isfile(joinpath("test", "docs", "literate", "man", "pg1.jl"))
@test isfile(joinpath("test", "docs", "src", "index.md"))
@test isfile(joinpath("test", "src", "test.jl"))
cd(bk)
rm(tdir, recursive=true)
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | code | 32 | function foo()
return 0
end
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 5456 | # Live Server for Julia
[](https://github.com/tlienart/LiveServer.jl/actions)
[](https://codecov.io/gh/tlienart/LiveServer.jl)
[](https://tlienart.github.io/LiveServer.jl/dev/)
This is a simple and lightweight development web-server written in Julia,
based on [HTTP.jl](https://github.com/JuliaWeb/HTTP.jl).
It has live-reload capability, i.e. when modifying a file, every browser (tab)
currently displaying the corresponding page is automatically refreshed.
LiveServer is inspired from Python's [`http.server`](https://docs.python.org/3/library/http.server.html)
and Node's [`browsersync`](https://www.browsersync.io/).
## Installation
To install it in Julia ≥ 1.6, use the package manager with
```julia-repl
pkg> add LiveServer
```
### Broken pipe message
Infrequently, you _may_ see an error message in your console while using LiveServer that does not
interrupt the server and does not otherwise affect your ability to see updates in the browser.
This error message will look like
```
┌ LogLevel(1999): handle_connection handler error
│ exception =
│ IOError: write: broken pipe (EPIPE)
```
You can basically ignore this message, it's a problem with [HTTP.jl](https://github.com/JuliaWeb/HTTP.jl).
If your application depends on LiveServer and you'd like to avoid having that kind of messages being shown to your users, you can consider using [LoggingExtras.jl](https://github.com/JuliaLogging/LoggingExtras.jl) which
allows you to filter out messages based on their provenance.
We experimented with shipping LoggingExtras in LiveServer but ended up rolling that back as it made
other applications less stable.
### Legacy notes
For Julia `< 1.6`, you can use LiveServer's version 0.9.2:
```julia-repl
pkg> add [email protected]
```
For Julia `[1.0, 1.3)`, you can use LiveServer's version 0.7.4:
```julia-repl
pkg> add [email protected]
```
### Make it a shell command
LiveServer is a small package and fast to load with one main functionality (`serve`),
it can be convenient to make it a shell command: (I'm using the name `lss` here but
you could use something else):
```
alias lss='julia -e "import LiveServer as LS; LS.serve(launch_browser=true)"'
```
you can then use `lss` in any directory to show a directory listing in your browser,
and if the directory has an `index.html` then that will be rendered in your browser.
## Usage
The main function `LiveServer` exports is `serve` which starts listening to the current
folder and makes its content available to a browser.
The following code creates an example directory and serves it:
```julia-repl
julia> using LiveServer
julia> LiveServer.example() # creates an "example/" folder with some files
julia> cd("example")
julia> serve() # starts the local server & the file watching
✓ LiveServer listening on http://localhost:8000/ ...
(use CTRL+C to shut down)
```
Open a Browser and go to `http://localhost:8000/` to see the content being rendered;
try modifying files (e.g. `index.html`) and watch the changes being rendered immediately in the browser.
In the REPL:
```julia-repl
julia> using LiveServer
julia> serve(host="0.0.0.0", port=8001, dir=".") # starts the remote server & the file watching
✓ LiveServer listening on http://0.0.0.0:8001...
(use CTRL+C to shut down)
```
In the terminal:
```bash
julia -e 'using LiveServer; serve(host="0.0.0.0", port=8001, dir=".")'
```
Open a browser and go to https://localhost:8001/ to see the rendered content of index.html or,
if it doesn't exist, the content of the directory.
You can set the port to a custom number.
This is similar to the [`http.server`](https://docs.python.org/3/library/http.server.html) in Python.
### Serve docs
`servedocs` is a convenience function that runs `Documenter` along with `LiveServer` to watch
your doc files for any changes and render them in your browser when modifications are detected.
Assuming you are in `directory/to/YourPackage.jl`, that you have a `docs/` folder as
prescribed by [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl) and `LiveServer`
installed in your global environment, you can run:
```julia-repl
$ julia
pkg> activate docs
julia> using YourPackage, LiveServer
julia> servedocs()
[ Info: SetupBuildDirectory: setting up build directory.
[ Info: ExpandTemplates: expanding markdown templates.
...
└ Deploying: ✘
✓ LiveServer listening on http://localhost:8000/ ...
(use CTRL+C to shut down)
```
Open a browser and go to `http://localhost:8000/` to see your docs being rendered;
try modifying files (e.g. `docs/index.md`) and watch the changes being rendered in the browser.
To run the server with one line of code, run:
```
$ julia --project=docs -ie 'using YourPackage, LiveServer; servedocs()'
```
**Note**: this works with [Literate.jl](https://github.com/fredrikekre/Literate.jl) as well.
See [the docs](https://tlienart.github.io/LiveServer.jl/dev/man/ls+lit/).
## DEV/Path testing
See also issue #135 and related PRs.
* `servedocs()`, navigate to literate, images should show
* `serve()` navigate manually to `docs/build/` should show, remove trailing slash in URL `docs/build` should redirect to `docs/build/`
* `serve(dir=...)` should work + when navigating to assets etc
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 5297 | # LiveServer.jl - Documentation
LiveServer is a simple and lightweight development web-server written in Julia, based on [HTTP.jl](https://github.com/JuliaWeb/HTTP.jl).
It has live-reload capability, i.e. when changing files, every browser (tab) currently displaying a corresponding page is automatically refreshed.
LiveServer is inspired from Python's [`http.server`](https://docs.python.org/3/library/http.server.html) and Node's [`browsersync`](https://www.browsersync.io/).
## Installation
In Julia ≥ 1.0, you can add it using the Package Manager with
```julia-repl
pkg> add LiveServer
```
## Usage
The main function `LiveServer` exports is [`serve`](@ref) which starts listening to the current folder and makes its content available to a browser.
The following code creates an example directory and serves it:
```julia-repl
julia> using LiveServer
julia> LiveServer.example() # creates an "example/" folder with some files
julia> cd("example")
julia> serve() # starts the local server & the file watching
✓ LiveServer listening on http://localhost:8000/ ...
(use CTRL+C to shut down)
```
Open a Browser and go to `http://localhost:8000/` to see the content being rendered; try modifying files (such as `index.html`) and watch the changes being rendered immediately in the browser.
In the REPL:
```julia-repl
julia> using LiveServer
julia> serve(host="0.0.0.0", port=8001, dir=".") # starts the remote server & the file watching
✓ LiveServer listening on http://0.0.0.0:8001...
(use CTRL+C to shut down)
```
In the terminal:
```julia-repl
julia -e 'using LiveServer; serve(host="0.0.0.0", port=8001, dir=".")' # like as: python -m http.server 8001
```
Open a browser and go to https://localhost:8001/ to see the rendered content of index.html or, if it doesn't exist, the content of the directory.
You can set the port to a custom number.
This is similar to the [`http.server`](https://docs.python.org/3/library/http.server.html) in Python.
### Live serve your docs
A function derived from `serve` that will be convenient to Julia package developers is `servedocs`.
It runs [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl) along with `LiveServer` to render your docs and will track and render any modifications to your docs.
This instantaneous feedback makes writing docs significantly easier and faster.
Assuming you are in `directory/to/YourPackage.jl` and that you have a `docs/` folder as prescribed by `Documenter`, just run:
```julia
julia> using YourPackage, LiveServer
julia> servedocs()
[ Info: SetupBuildDirectory: setting up build directory.
[ Info: ExpandTemplates: expanding markdown templates.
...
└ Deploying: ✘
✓ LiveServer listening on http://localhost:8000/ ...
(use CTRL+C to shut down)
```
Open a browser and go to `http://localhost:8000/` to see your docs being rendered; try modifying files (e.g. `docs/index.md`) and watch the changes being rendered in the browser.
You can also use LiveServer with both Documenter and [Literate.jl](https://github.com/fredrikekre/Literate.jl).
This is explained [here](man/ls+lit/).
## How it works
Let's assume you have a directory similar to that generated by [`LiveServer.example()`](@ref):
```
.
├── css
│ └── master.css
├── files
│ └── TestImage.png
├── index.html
└── pages
└── blah.html
```
Calling `serve()` from within this directory starts a file server.
It serves the contents of the directory as a static site, with the folder structure defining the paths of the URLs.
That is, the file `blah.html` can be viewed at `/pages/blah.html`.
When a directory is specified instead of a file, the server checks whether there is a file `index.html` in this directory and serves it if available.
Visiting `http://localhost:8000/` makes your browser send a standard HTTP `GET`
request to the server.
The server, running a listener loop, receives this request, looks for `index.html` in the root folder, and serves it.
After serving it, `LiveServer` adds this file to the list of watched files.
That is, whenever this file changes, a callback is fired (see below).
The HTML page may also contain references to style sheets or pictures, which are then requested by your browser as well.
The server sends them to the browser, and also adds them to the list of watched files.
#### But what about the live reloading?
Triggering a page refresh in the browser is achieved by a WebSocket connection.
The WebSocket API, according to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), is
> an advanced technology that makes it possible to open a two-way interactive
> communication session between the user's browser and a server.
`LiveServer` injects a small piece of JavaScript code into every HTML file
before serving it. This snippet is executed by the browser and opens a WebSocket
connection to the server, which in turn adds it to a list of viewers of this page.
The server can now send the message "update" to all viewers of a page whenever the page is changed.
The code snippet reacts to this message by triggering a page reload.
The update is triggered by the callback mentioned above.
When the file is not an HTML file, the viewers of _any_ HTML file are updated, since `LiveServer` currently does not keep track of which HTML files reference what other files.
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 1884 | # Internal Interface
Documentation for `LiveServer.jl`'s internal interface
## File watching
There are two key types related to file watching:
1. one to wrap a file being watched ([`LiveServer.WatchedFile`](@ref)),
2. one for the file watcher itself wrapping the list of watched files and what to do upon file changes ("callback" function)
Any file watcher will be a subtype of the abstract type [`LiveServer.FileWatcher`](@ref) with, for instance, the default watcher being [`LiveServer.SimpleWatcher`](@ref).
### WatchedFile
```@docs
LiveServer.WatchedFile
LiveServer.has_changed
LiveServer.set_unchanged!
```
### FileWatcher
#### Key types
```@docs
LiveServer.FileWatcher
LiveServer.SimpleWatcher
```
#### Functions related to a `FileWatcher`
```@docs
LiveServer.start
LiveServer.stop
LiveServer.set_callback!
LiveServer.watch_file!
LiveServer.file_watcher_task!
```
#### Additional helper functions:
```@docs
LiveServer.is_running
LiveServer.is_watched
```
## Live serving
The [`serve`](@ref) method instantiates a listener (`HTTP.listen`) in an asynchronous task.
The callback upon an incoming HTTP stream decides whether it is a standard HTTP request or a request for an upgrade to a websocket connection.
The former case is handled by [`LiveServer.serve_file`](@ref), the latter by
[`LiveServer.ws_tracker`](@ref).
Finally, [`LiveServer.file_changed_callback`](@ref) is the function passed to the file watcher to be executed upon file changes.
```@docs
LiveServer.serve_file
LiveServer.ws_upgrade
LiveServer.ws_tracker
LiveServer.file_changed_callback
```
#### Additional helper functions:
```@docs
LiveServer.get_fs_path
LiveServer.update_and_close_viewers!
```
#### Helper functions associated with `servedocs`
```@docs
LiveServer.servedocs_callback!
LiveServer.scan_docs!
```
## Miscellaneous
```@docs
LiveServer.example
LiveServer.set_verbose
```
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 127 | # Public Interface
Documentation for `LiveServer.jl`'s exported functions
```@docs
LiveServer.serve
LiveServer.servedocs
```
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 6119 | # Extending LiveServer
There may be circumstances where you will want the page-reloading to be triggered by your own mechanism.
As a very simple example, you may want to display your own custom messages every time a file is updated.
This page explains how to extend `SimpleWatcher <: FileWatcher` and, more generally, how to write your own `FileWatcher`.
We also explain how in some circumstances it may be easier to feed a custom `coreloopfun` to [`serve`](@ref) rather than writing a custom callback.
## Using `SimpleWatcher` with a custom callback
In most circumstances, using an instance of the `SimpleWatcher` type with your own _custom callback function_ is what you will want to do.
The `SimpleWatcher` does what you expect: it watches files for changes and triggers a function (the _callback_) when a change is detected.
The callback function takes as argument the path of the file that was modified and returns `nothing`.
The base callback function ([`LiveServer.file_changed_callback`](@ref)) does only one thing: it sends a signal to the relevant viewers to trigger page reloads.
You will typically want to re-use `file_changed_callback` or copy its code.
As an example of a custom callback, here is a simple modified callback mechanism which prints `Hello!` before using the base callback function:
```julia
custom_callback(fp::AbstractString) = (println("Hello!"); file_changed_callback(fp))
```
A more sophisticated customised callback is the one that is used in [`servedocs`](@ref) (see [`LiveServer.servedocs_callback!`](@ref)).
The callback has a different behaviour depending on which file is modified and does a few extra steps before signalling the viewers to reload appropriate pages.
## Writing your own `FileWatcher`
If you decide to write your own `FileWatcher` type, you will need to meet the API.
The easier is probably that you look at the code for [`LiveServer.SimpleWatcher`](@ref) and adapt it to your need.
Let's assume for now that you want to define a `CustomWatcher <: FileWatcher`.
### Fields
The only field that is _required_ by the rest of the code is
* `status`: a symbol that must be set to `:interrupted` upon errors in the file watching task
Likely you will want to have some (probably most) of the fields of a `SimpleWatcher` i.e.:
* `callback`: the callback function to be triggered upon an event,
* `task`: the asynchronous file watching task,
* `watchedfiles`: the vector of [`LiveServer.WatchedFile`](@ref) i.e. the paths to the file being watched as well as their time of last modification,
* `sleeptime`: the time to wait before going over the list of `watchedfiles` to check for changes, you won't want this to be too small and it's lower bounded to `0.05` in `SimpleWatcher`.
Of course you can add any extra field you may want.
### Methods
Subsequently, your `CustomWatcher` may redefine some or all of the following methods (those that aren't will use the default method defined for `FileWatcher` and thus
all of its sub-types).
The methods that are _required_ by the rest of the code are
* `start(::FileWatcher)` and `stop(::FileWatcher)` to start and stop the watcher,
* `watch_file!(::FileWatcher, ::AbstractString)` to consider an additional file.
You may also want to re-define existing methods such as
* `file_watcher_task!(::FileWatcher)`: the loop that goes over the watched files, checking for modifications and triggering the callback function. This task will be referenced by the field `CustomWatcher.task`. If errors happen in this asynchronous task, the `CustomWatcher.status` should be set to `:interrupted` so that all running tasks can be stopped properly.
* `set_callback!(::FileWatcher, ::Function)`: a helper function to bind a watcher with a callback function.
* `is_running(::FileWatcher)`: a helper function to check whether `CustomWatcher.task` is done.
* `is_watched(::FileWatcher, ::AbstractString)`: check if a file is watched by the watcher.
## Using a custom `coreloopfun`
In some circumstances, your code may be using specific data structures or be such that it would not easily play well with a `FileWatcher` mechanism.
In that case, you may want to also specify a `coreloopfun` which is called continuously from within the [`serve`](@ref) main loop.
The code of [`serve`](@ref) is essentially structured as follows:
```julia
function serve(...)
# ...
@async HTTP.listen(...) # handles messages with the client (browser)
# ...
try
counter = 1
while true # the main loop
# ...
coreloopfun(counter, filewatcher)
counter += 1
sleep(0.1)
end
catch err
# ...
finally
# cleanup ...
end
return nothing
end
```
That is, the `coreloopfun` is called roughly every 100 ms while the server is running.
By default the `coreloopfun` does nothing.
An example where this mechanism could be used is when your code handles the processing of files from one format (say markdown) to HTML. You want the `FileWatcher` to trigger browser reloads whenever new versions of these HTML files are produced. However, at the same time, you want another process to keep track of the markdown files and re-process them as they change. You can hook this second watcher into the core loop of `LiveServer` using the `coreloopfun`.
An example for this use case is [JuDoc.jl](https://github.com/tlienart/JuDoc.jl).
## Why not use `FileWatching`?
You may be aware of the [`FileWatching`](https://docs.julialang.org/en/v1/stdlib/FileWatching/index.html) module in `Base` and may wonder why we did not just use that one.
The main reasons we decided not to use it are:
* it triggers _a lot_: where our system only triggers the callback function upon _saving_ a file (e.g. you modified the file and saved the modification), `FileWatching` is more sensitive (for instance it will trigger when you _open_ the file),
* it is somewhat harder to make your own custom mechanisms to fire page reloads.
So ultimately, our system can be seen as a poor man's implementation of `FileWatching` that is robust, simple and easy to customise.
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 4257 | # Main functions
The two main functions exported by the package are
* [`serve`](@ref) and
* [`servedocs`](@ref),
they are discussed in some details here.
## `serve`
The exported [`serve`](@ref) function is the main function of the package.
The basic usage is
```julia-repl
julia> cd("directory/of/website")
julia> serve()
✓ LiveServer listening on http://localhost:8000/ ...
(use CTRL+C to shut down)
```
which will make the content of the folder available to be viewed in a browser.
You can specify the port that the server should listen to (default is `8000`) as well as the directory to serve (if not the current one) as keyword arguments.
There is also a `verbose` keyword-argument if you want to see messages being displayed on file changes and
connections.
More interestingly, you can optionally specify the `filewatcher` (the only
regular argument) which allows to define what will trigger the messages to the client and ultimately cause the active browser tabs to reload.
By default, it is file modifications that will trigger page reloads but you may want to write your own file watcher to perform additional actions upon file changes or trigger browser reload differently.
Finally, you can specify a function `coreloopfun` which is called continuously while the server is running.
There may be circumstances where adjusting `coreloopfun` helps to complement the tuning of a `FileWatcher`.
See the section on [Extending LiveServer](@ref) for more informations.
## `servedocs`
The exported [`servedocs`](@ref) function is a convenient function derived from `serve`.
The main purpose is to allow Julia package developpers to live-preview their documentation while working on it by coupling `Documenter.jl` and `LiveServer.jl`.
Let's assume the structure of your package looks like
```
.
├── LICENSE.md
├── Manifest.toml
├── Project.toml
├── README.md
├── docs
│ ├── Project.toml
│ ├── build
│ ├── make.jl
│ └── src
│ └── index.md
├── src
│ └── MyPackage.jl
└── test
└── runtests.jl
```
The standard way of running `Documenter.jl` is to run `make.jl`, wait for completion and then use a standard browser or maybe some third party tool to see the output.
With `servedocs` however, you can edit the `.md` files in your `docs/src` and see the changes being applied directly in your browser which makes writing documentation faster and easier.
To launch it, navigate to `YourPackage.jl/` and simply
```julia-repl
julia> using YourPackage, LiveServer
julia> servedocs()
```
This will execute `make.jl` (a pass of `Documenter.jl`) before live serving the resulting `docs/build` folder with `LiveServer.jl`.
Upon modifying a `.md` file (e.g. updating `docs/src/index.md`), the `make.jl` will be applied and the corresponding changes propagated to active tabs (e.g. a tab watching `http://localhost:8000/index.html`)
!!! note
The first pass of `Documenter.jl` takes a few seconds to complete, but subsequent passes are quite fast so that the workflow with `Documenter.jl`+`LiveServer.jl` is pretty quick.
The first pass collects all information in the code (i.e. docstrings), while
subsequent passes only consider changes in the markdown (`.md`) files. This
restriction is necessary to achieve a fast update behavior.
### Additional keywords
The `servedocs` function now takes extra keywords which may, in some cases, make your life easier:
* `foldername="docs"`, is the name of folder that contains the documentation, which can be changed if it's different than `docs`.
* `doc_env=false`, if set to true, the `Project.toml` available in `docs/` will be activated (note 1),
* `skip_dir=""`, indicates a directory to skip when looking at the docs folder for change, this can be useful when using packages like Literate or Weave that may generate files inside your `src` folder.
Note that in latter two cases these keywords are there for your convenience but would be best not used. See also the discussion in [this issue](https://github.com/asprionj/LiveServer.jl/issues/85).
In the first case, doing
```
julia --project=docs -e 'using LiveServer; servedocs()'
```
is more robust.
In the second case, it would be best if you made sure that all generated files are saved in `docs/build/...`.
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 1.3.1 | 1e46b873b8ef176e23ee43f96e72cd45c20bafb4 | docs | 4964 | # LiveServer + Literate
(_Thanks to [Fredrik Ekre](https://github.com/fredrikekre) and [Benoit Pasquier](https://github.com/briochemc) for their input; a lot of this section is drawn from an early prototype suggested by Fredrik._)
You've likely already seen how LiveServer could be used along with Documenter to have live updating documentation (see [`servedocs`](/man/functionalities/#servedocs-1) if not).
It is also easy to use LiveServer with both Documenter and [Literate.jl](https://github.com/fredrikekre/Literate.jl), a package for literate programming written by Fredrik Ekre that can convert julia script files into markdown.
This can be particularly convenient for documentation pages with a lot of code examples.
There are mainly two steps
1. have the `make.jl` file process the literate files to go from `.jl` to `.md` files,
2. call `servedocs` with appropriate keywords.
The function `LiveServer.servedocs_literate_example` generates a directory which has the right structure that you can copy for your package.
To experiment, do:
```julia-repl
julia> using LiveServer
julia> LiveServer.servedocs_literate_example("test_dir")
julia> cd("test_dir")
julia> servedocs(literate_dir=joinpath("docs", "literate"))
```
if you then navigate to `localhost:8000` you should end up with

if you modify `test_dir/docs/literate/man/pg1.jl` for instance writing `f(4)` it will be applied directly:

In the explanations below we assume you have defined
* `LITERATE_INPUT` the directory where the literate files are,
* `LITERATE_OUTPUT` the directory where the generated markdown files will be.
## Having the make file call Literate
Here's a basic `make.jl` file which loops over the files in `LITERATE_INPUT` to generate files
in `LITERATE_OUTPUT`
```julia
using Documenter, Literate
LITERATE_INPUT = ...
LITERATE_OUTPUT = ...
for (root, _, files) ∈ walkdir(LITERATE_INPUT), file ∈ files
# ignore non julia files
splitext(file)[2] == ".jl" || continue
# full path to a literate script
ipath = joinpath(root, file)
# generated output path
opath = splitdir(replace(ipath, LITERATE_INPUT=>LITERATE_OUTPUT))[1]
# generate the markdown file calling Literate
Literate.markdown(ipath, opath)
end
makedocs(
...
)
```
## Calling servedocs with the right arguments
`LiveServer.servedocs` needs to know two things to work with literate scripts properly:
* where the scripts are
* where the generated files will be
it can make assumptions for some basic cases but, in general, you'll have to provide both.
Doing so improperly may lead to an infinite loop where:
* the first `make.jl` call generates markdown files with Literate
* these generated markdown files themselves trigger `make.jl`
* (infinite loop)
To avoid this, you must generally call `servedocs` as follows when working with literate files:
```
servedocs(
literate_dir = LITERATE_INPUT,
skip_dir = LITERATE_OUTPUT
)
```
where
* `literate_dir` is the parent directory of the literate scripts, and
* `skip_dir` is the parent directory where the generated markdown files are placed.
**Special cases**:
* if the literate scripts are located in `docs/src` you can just specify `literate_dir=""`,
* if the literate scripts are generated with in `docs/src` with the exact same relative path, you do not need to specify `skip_dir`.
## Examples
In the examples below, the file `literate_script.jl` represents a Literate script and `literate_script.md` represents the markdown file generated by Literate.
What matters here is where these files are with respect to one another and with respect to `docs/src`.
### Example 1
```
docs
└── src
├── literate_script.jl
└── literate_script.md
```
in this case we can simply call
```julia
servedocs(literate="")
```
since
1. the literate scripts are under `docs/src` (and so are watched by default),
2. the generated markdown files have exactly the same relative path (so there's no need to specify where the literate files are placed, this is implicit).
### Example 2
```
docs
├── literate
│ └── literate_script.jl
└── src
└── literate_script.md
```
in this case we can call
```julia
servedocs(
literate=joinpath("docs", "literate")
)
```
since
1. the literate scripts are under a dedicated folder that is not under `docs/src` and so must also be watched for changes,
2. the generated markdown files have exactly the same relative path.
### Example 3
```
foo
├── literate
│ └── literate_script.jl
docs
└── src
└── generated
└── literate_script.md
```
in this case we can call
```julia
servedocs(
literate=joinpath("foo", "literate"),
skip_dir=joinpath("docs", "src", "generated")
)
```
since
1. the literate scripts are under a dedicated folder,
2. the generated markdown files do not have exactly the same relative path (since there is the added `generated` in the path).
| LiveServer | https://github.com/tlienart/LiveServer.jl.git |
|
[
"MIT"
] | 0.1.0 | b82c1da2a9bde0821926927b2185f312c0c8e4c5 | code | 3129 |
module Ditherings
using Images
export Quantise
export ZeroOne
export ZeroOne_PerChannel
export FloydSteinbergDither4Sample
export FloydSteinbergDither12Sample
function Quantise(pixel)
shift = 4
scale = 255.0
r = Int64.(round(scale * (red(pixel) )))>>shift
g = Int64.(round(scale * (green(pixel))))>>shift
b = Int64.(round(scale * (blue(pixel) )))>>shift
r = Float64.((r<<shift)/scale)
g = Float64.((g<<shift)/scale)
b = Float64.((b<<shift)/scale)
RGB(r,g,b)
end
function ZeroOne(pixel)
r = red(pixel)
g = green(pixel)
b = blue(pixel)
if(r + b + g >= 1.5)
return RGB(1.0, 1.0, 1.0)
else
return RGB(0.0, 0.0, 0.0)
end
end
function ZeroOne_PerChannel(pixel)
r = red(pixel)
g = green(pixel)
b = blue(pixel)
r= r>0.5 ? 1.0 : 0.0
g= g>0.5 ? 1.0 : 0.0
b= b>0.5 ? 1.0 : 0.0
return RGB(r, g, b)
end
function FloydSteinbergDither4Sample(_img, PaletteFunction, weights=[7/16,3/16,5/16,1/16])
width, height = size(_img);
inputtype = typeof(_img)
newimg = RGB{Float64}.(_img)
for y in 2:height-1
for x in 2:width-1
oldpix = newimg[x,y]
newpix = PaletteFunction(oldpix)
newimg[x,y] = newpix
quant_error = oldpix - newpix
newimg[x+1,y ] = newimg[x+1,y ] + (quant_error * weights[1])
newimg[x-1,y+1] = newimg[x-1,y+1] + (quant_error * weights[2])
newimg[x ,y+1] = newimg[x ,y+1] + (quant_error * weights[3])
newimg[x+1,y+1] = newimg[x+1,y+1] + (quant_error * weights[4])
end
end
newimg
end
function FloydSteinbergDither12Sample(_img, PaletteFunction, weights = [0.243228, 0.0810761, 0.0417918, 0.0573652, 0.243228, 0.0573652, 0.0417918, 0.0347469, 0.0417918, 0.0810761, 0.0417918, 0.0347469])
width, height = size(_img);
inputtype = typeof(_img)
newimg = RGB{Float64}.(_img)
for y in 3:height-2
for x in 3:width-2
oldpix = newimg[x,y]
newpix = PaletteFunction(oldpix)
newimg[x,y] = newpix
quant_error = oldpix - newpix
newimg[x+1,y ] = newimg[x+1,y ] + (quant_error * weights[1] )
newimg[x+2,y ] = newimg[x+2,y ] + (quant_error * weights[2] )
newimg[x-2,y+1] = newimg[x-2,y+1] + (quant_error * weights[3] )
newimg[x-1,y+1] = newimg[x-1,y+1] + (quant_error * weights[4] )
newimg[x ,y+1] = newimg[x ,y+1] + (quant_error * weights[5] )
newimg[x+1,y+1] = newimg[x+1,y+1] + (quant_error * weights[6] )
newimg[x+2,y+1] = newimg[x+2,y+1] + (quant_error * weights[7] )
newimg[x-2,y+2] = newimg[x-2,y+2] + (quant_error * weights[8] )
newimg[x-1,y+2] = newimg[x-1,y+2] + (quant_error * weights[9] )
newimg[x ,y+2] = newimg[x ,y+2] + (quant_error * weights[10] )
newimg[x+1,y+2] = newimg[x+1,y+2] + (quant_error * weights[11] )
newimg[x+2,y+2] = newimg[x+2,y+2] + (quant_error * weights[12] )
end
end
newimg
end
end | Ditherings | https://github.com/NTimmons/Ditherings.jl.git |
|
[
"MIT"
] | 0.1.0 | b82c1da2a9bde0821926927b2185f312c0c8e4c5 | code | 49 | using Ditherings
using Base.Test
@test true
| Ditherings | https://github.com/NTimmons/Ditherings.jl.git |
|
[
"MIT"
] | 0.1.0 | b82c1da2a9bde0821926927b2185f312c0c8e4c5 | docs | 986 | # Ditherings
Dithering Algorithms for Julia
# Basic Usage Examples
`julia> using Ditherings`
---
#### Simple Reduced Precision Colour
`julia> img = load("lenna.png");`

---
#### Switch to zero or one per pixel
`julia> Ditherings.FloydSteinbergDither4Sample(img, Ditherings.ZeroOne)`

---
#### Switch to zero or one per channel
`julia> Ditherings.FloydSteinbergDither4Sample(img, Ditherings.ZeroOne_PerChannel)`

# Approach
The aim of these funcions is that you can call a function which represents an error diffusion shape, and then pass in a palette function which maps the input function into the reduced precision space. Optionally you can also pass in custom weights for the error diffusion kernel
| Ditherings | https://github.com/NTimmons/Ditherings.jl.git |
|
[
"MPL-2.0"
] | 0.1.0 | fac1b8e5051146e12819eebda2f8e1d19bd1c1ea | code | 573 | using XSteamUnits
using Documenter
DocMeta.setdocmeta!(XSteamUnits, :DocTestSetup, :(using XSteamUnits); recursive=true)
makedocs(;
modules=[XSteamUnits],
authors="",
repo="https://github.com/hzgzh/XSteamUnits.jl/blob/{commit}{path}#{line}",
sitename="XSteamUnits.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://hzgzh.github.io/XSteamUnits.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/hzgzh/XSteamUnits.jl",
)
| XSteamUnits | https://github.com/hzgzh/XSteamUnits.jl.git |
|
[
"MPL-2.0"
] | 0.1.0 | fac1b8e5051146e12819eebda2f8e1d19bd1c1ea | code | 163065 | module XSteamUnits
using Unitful
#h_prho beh鰒er T_prho f鰎 samtliga regioner!!!!
#***********************************************************************************************************
#* Water and steam properties according to IAPWS IF-97 *
#* By Magnus Holmgren, www.x-eng.com *
#* The steam tables are free and provided as is. *
#* We take no responsibilities for any errors in the code or damage thereby. *
#* You are free to use, modify and distribute the code as long as authorship is properly acknowledged. *
#* Please notify me at [email protected] if the code is used in commercial applications *
#***********************************************************************************************************
#
# XSteam provides accurate steam and water properties from 0 - 1000 bar and from 0 - 2000 deg C according to
# the standard IAPWS IF-97. For accuracy of the functions in different regions see IF-97 (www.iapws.org)
#
# *** Using XSteam *****************************************************************************************
#XSteam take 2 or 3 arguments. The first argument must always be the steam table function you want to use.
#The other arguments are the inputs to that function.
#Example: XSteam("h_pt",1,20) Returns the enthalpy of water at 1 bar and 20 degC
#Example: XSteam("TSat_p",1) Returns the saturation temperature of water at 1 bar.
#For a list of valid Steam Table functions se bellow or the XSteam macros for MS Excel.
#
#*** Nomenclature ******************************************************************************************
# First the wanted property then a _ then the wanted input properties.
# Example. T_ph is temperature as a function of pressure and enthalpy.
# For a list of valid functions se bellow or XSteam for MS Excel.
# T Temperature (deg C)
# p Pressure (bar)
# h Enthalpy (kJ/kg)
# v Specific volume (m3/kg)
# rho Density
# s Specific entropy
# u Specific internal energy
# Cp Specific isobaric heat capacity
# Cv Specific isochoric heat capacity
# w Speed of sound
# my Viscosity
# tc Thermal Conductivity
# st Surface Tension
# x Vapour fraction
# vx Vapour Volume Fraction
#
#*** Valid Steam table functions. ****************************************************************************
#
#Temperature
#Tsat_p Saturation temperature
#T_ph Temperture as a function of pressure and enthalpy
#T_ps Temperture as a function of pressure and entropy
#T_hs Temperture as a function of enthalpy and entropy
#
#Pressure
#psat_T Saturation pressure
#p_hs Pressure as a function of h and s.
#p_hrho Pressure as a function of h and rho. Very unaccurate for solid water region since it"s almost incompressible!
#
#Enthalpy
#hV_p Saturated vapour enthalpy
#hL_p Saturated liquid enthalpy
#hV_T Saturated vapour enthalpy
#hL_T Saturated liquid enthalpy
#h_pT Entalpy as a function of pressure and temperature.
#h_ps Entalpy as a function of pressure and entropy.
#h_px Entalpy as a function of pressure and vapour fraction
#h_prho Entalpy as a function of pressure and density. Observe for low temperatures (liquid) this equation has 2 solutions.
#h_Tx Entalpy as a function of temperature and vapour fraction
#
#Specific volume
#vV_p Saturated vapour volume
#vL_p Saturated liquid volume
#vV_T Saturated vapour volume
#vL_T Saturated liquid volume
#v_pT Specific volume as a function of pressure and temperature.
#v_ph Specific volume as a function of pressure and enthalpy
#v_ps Specific volume as a function of pressure and entropy.
#
#Density
#rhoV_p Saturated vapour density
#rhoL_p Saturated liquid density
#rhoV_T Saturated vapour density
#rhoL_T Saturated liquid density
#rho_pT Density as a function of pressure and temperature.
#rho_ph Density as a function of pressure and enthalpy
#rho_ps Density as a function of pressure and entropy.
#
#Specific entropy
#sV_p Saturated vapour entropy
#sL_p Saturated liquid entropy
#sV_T Saturated vapour entropy
#sL_T Saturated liquid entropy
#s_pT Specific entropy as a function of pressure and temperature (Returns saturated vapour entalpy if mixture.)
#s_ph Specific entropy as a function of pressure and enthalpy
#
#Specific internal energy
#uV_p Saturated vapour internal energy
#uL_p Saturated liquid internal energy
#uV_T Saturated vapour internal energy
#uL_T Saturated liquid internal energy
#u_pT Specific internal energy as a function of pressure and temperature.
#u_ph Specific internal energy as a function of pressure and enthalpy
#u_ps Specific internal energy as a function of pressure and entropy.
#
#Specific isobaric heat capacity
#CpV_p Saturated vapour heat capacity
#CpL_p Saturated liquid heat capacity
#CpV_T Saturated vapour heat capacity
#CpL_T Saturated liquid heat capacity
#Cp_pT Specific isobaric heat capacity as a function of pressure and temperature.
#Cp_ph Specific isobaric heat capacity as a function of pressure and enthalpy
#Cp_ps Specific isobaric heat capacity as a function of pressure and entropy.
#
#Specific isochoric heat capacity
#CvV_p Saturated vapour isochoric heat capacity
#CvL_p Saturated liquid isochoric heat capacity
#CvV_T Saturated vapour isochoric heat capacity
#CvL_T Saturated liquid isochoric heat capacity
#Cv_pT Specific isochoric heat capacity as a function of pressure and temperature.
#Cv_ph Specific isochoric heat capacity as a function of pressure and enthalpy
#Cv_ps Specific isochoric heat capacity as a function of pressure and entropy.
#
#Speed of sound
#wV_p Saturated vapour speed of sound
#wL_p Saturated liquid speed of sound
#wV_T Saturated vapour speed of sound
#wL_T Saturated liquid speed of sound
#w_pT Speed of sound as a function of pressure and temperature.
#w_ph Speed of sound as a function of pressure and enthalpy
#w_ps Speed of sound as a function of pressure and entropy.
#
#Viscosity
#Viscosity is not part of IAPWS Steam IF97. Equations from
#"Revised Release on the IAPWS Formulation 1985 for the Viscosity of Ordinary Water Substance", 2003 are used.
#Viscosity in the mixed region (4) is interpolated according to the density. This is not true since it will be two fases.
#my_pT Viscosity as a function of pressure and temperature.
#my_ph Viscosity as a function of pressure and enthalpy
#my_ps Viscosity as a function of pressure and entropy.
#
#Thermal Conductivity
#Revised release on the IAPS Formulation 1985 for the Thermal Conductivity of ordinary water substance (IAPWS 1998)
#tcL_p Saturated vapour thermal conductivity
#tcV_p Saturated liquid thermal conductivity
#tcL_T Saturated vapour thermal conductivity
#tcV_T Saturated liquid thermal conductivity
#tc_pT Thermal conductivity as a function of pressure and temperature.
#tc_ph Thermal conductivity as a function of pressure and enthalpy
#tc_hs Thermal conductivity as a function of enthalpy and entropy
#
#Surface tension
#st_T Surface tension for two phase water/steam as a function of T
#st_p Surface tension for two phase water/steam as a function of T
#Vapour fraction
#x_ph Vapour fraction as a function of pressure and enthalpy
#x_ps Vapour fraction as a function of pressure and entropy.
#
#Vapour volume fraction
#vx_ph Vapour volume fraction as a function of pressure and enthalpy
#vx_ps Vapour volume fraction as a function of pressure and entropy.
#*Contents.
#*1 Calling functions
#*1.1
#*1.2 Temperature (T)
#*1.3 Pressure (p)
#*1.4 Enthalpy (h)
#*1.5 Specific Volume (v)
#*1.6 Density (rho)
#*1.7 Specific entropy (s)
#*1.8 Specific internal energy (u)
#*1.9 Specific isobaric heat capacity (Cp)
#*1.10 Specific isochoric heat capacity (Cv)
#*1.11 Speed of sound
#*1.12 Viscosity
#*1.13 Prandtl
#*1.14 Kappa
#*1.15 Surface tension
#*1.16 Heat conductivity
#*1.17 Vapour fraction
#*1.18 Vapour Volume Fraction
#
#*2 IAPWS IF 97 Calling functions
#*2.1 Functions for region 1
#*2.2 Functions for region 2
#*2.3 Functions for region 3
#*2.4 Functions for region 4
#*2.5 Functions for region 5
#
#*3 Region Selection
#*3.1 Regions as a function of pT
#*3.2 Regions as a function of ph
#*3.3 Regions as a function of ps
#*3.4 Regions as a function of hs
#
#4 Region Borders
#4.1 Boundary between region 1 and 3.
#4.2 Region 3. pSat_h and pSat_s
#4.3 Region boundary 1to3 and 3to2 as a functions of s
#
#5 Transport properties
#5.1 Viscosity (IAPWS formulation 1985)
#5.2 Thermal Conductivity (IAPWS formulation 1985)
#5.3 Surface Tension
#
#6 Units
#
#7 Verification
#7.1 Verifiy region 1
#7.2 Verifiy region 2
#7.3 Verifiy region 3
#7.4 Verifiy region 4
#7.5 Verifiy region 5
#***********************************************************************************************************
#*1 Calling functions *
#***********************************************************************************************************
#***********************************************************************************************************
#*1.1
#fun=lower(fun);
#switch fun
#***********************************************************************************************************
#*1.2 Temperature
function Tsat_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_T(T4_p(p));
else
Out = NaN;
end
Out
end
function Tsat_s(s)
s = toSIunit_s(s);
if s > -0.0001545495919 && s < 9.155759395
ps = p4_s(s);
Out = fromSIunit_T(T4_p(ps));
else
Out = NaN;
end
Out
end
function T_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
region = region_ph(p, h);
if region == 1
Out = fromSIunit_T(T1_ph(p, h));
elseif region == 2
Out = fromSIunit_T(T2_ph(p, h));
elseif region == 3
Out = fromSIunit_T(T3_ph(p, h));
elseif region == 4
Out = fromSIunit_T(T4_p(p));
elseif region == 5
Out = fromSIunit_T(T5_ph(p, h));
else
Out = NaN;
end
Out
end
function T_ps(p,s)
#println("p=",p,"s=",s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Out = fromSIunit_T(T1_ps(p, s));
elseif Region == 2
Out = fromSIunit_T(T2_ps(p, s));
elseif Region == 3
Out = fromSIunit_T(T3_ps(p, s));
elseif Region == 4
Out = fromSIunit_T(T4_p(p));
elseif Region == 5
Out = fromSIunit_T(T5_ps(p, s));
else
Out = NaN;
end
Out
end
function T_hs(h,s)
h = toSIunit_h(h);
s = toSIunit_s(s);
Region = region_hs(h, s);
if Region == 1
p1 = p1_hs(h, s);
Out = fromSIunit_T(T1_ph(p1, h));
elseif Region == 2
p2 = p2_hs(h, s);
Out = fromSIunit_T(T2_ph(p2, h));
elseif Region == 3
p3 = p3_hs(h, s);
Out = fromSIunit_T(T3_ph(p3, h));
elseif Region == 4
Out = fromSIunit_T(T4_hs(h, s));
elseif Region == 5
#error("functions of hs is not avlaible in region 5");
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.3 Pressure (p)
function psat_T(t)
T = toSIunit_T(t);
if T < 647.096 && T > 273.15
Out = fromSIunit_p(p4_T(T));
else
Out = NaN;
end
Out
end
function psat_s(s)
s = toSIunit_s(s);
if s > -0.0001545495919 && s < 9.155759395
Out = fromSIunit_p(p4_s(s));
else
Out = NaN;
end
Out
end
function p_hs(h,s)
h = toSIunit_h(h);
s = toSIunit_s(s);
Region = region_hs(h, s);
if Region == 1
Out = fromSIunit_p(p1_hs(h, s));
elseif Region == 2
Out = fromSIunit_p(p2_hs(h, s));
elseif Region == 3
Out = fromSIunit_p(p3_hs(h, s));
elseif Region == 4
tSat = T4_hs(h, s);
Out = fromSIunit_p(p4_T(tSat));
elseif Region == 5
#error("functions of hs is not avlaible in region 5");
else
Out = NaN;
end
Out
end
function p_hrho(h,rho)
h=h;
rho=rho;
#Not valid for water or sumpercritical since water rho does not change very much with p.
#Uses iteration to find p.
High_Bound = fromSIunit_p(100);
Low_Bound = fromSIunit_p(0.000611657);
ps = fromSIunit_p(10);
rhos = 1 / v_ph(ps, h);
while abs(rho - rhos) > 0.0000001
rhos = 1 / v_ph(ps, h);
if rhos >= rho
High_Bound = ps;
else
Low_Bound = ps;
end
ps = (Low_Bound + High_Bound) / 2;
end
Out = ps;
Out
end
#***********************************************************************************************************
#*1.4 Enthalpy (h)
function hV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_h(h4V_p(p));
else
Out = NaN;
end
Out
end
function hL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_h(h4L_p(p));
else
Out = NaN;
end
Out
end
function hV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
p = p4_T(T);
Out = fromSIunit_h(h4V_p(p));
else
Out = NaN;
end
Out
end
function hL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
p = p4_T(T);
Out = fromSIunit_h(h4L_p(p));
else
Out = NaN;
end
Out
end
function h_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_h(h1_pT(p, T));
elseif Region == 2
Out = fromSIunit_h(h2_pT(p, T));
elseif Region == 3
Out = fromSIunit_h(h3_pT(p, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_h(h5_pT(p, T));
else
Out = NaN;
end
Out
end
function h_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Out = fromSIunit_h(h1_pT(p, T1_ps(p, s)));
elseif Region == 2
Out = fromSIunit_h(h2_pT(p, T2_ps(p, s)));
elseif Region == 3
Out = fromSIunit_h(h3_rhoT(1 / v3_ps(p, s), T3_ps(p, s)));
elseif Region == 4
xs = x4_ps(p, s);
Out = fromSIunit_h(xs * h4V_p(p) + (1 - xs) * h4L_p(p));
elseif Region == 5
Out = fromSIunit_h(h5_pT(p, T5_ps(p, s)));
else
Out = NaN;
end
Out
end
function h_px(p,x)
p = toSIunit_p(p);
x = toSIunit_x(x);
if x > 1 || x < 0 || p >= 22.064
Out = NaN;
return
end
hL = h4L_p(p);
hV = h4V_p(p);
Out = hL + x * (hV - hL);
Out
end
function h_prho(p,rho)
p = toSIunit_p(p);
rho = 1 / toSIunit_v(1 / rho);
Region = Region_prho(p, rho);
if Region == 1
Out = fromSIunit_h(h1_pT(p, T1_prho(p, rho)));
elseif Region == 2
Out = fromSIunit_h(h2_pT(p, T2_prho(p, rho)));
elseif Region == 3
Out = fromSIunit_h(h3_rhoT(rho, T3_prho(p, rho)));
elseif Region == 4
if p < 16.529
vV = v2_pT(p, T4_p(p));
vL = v1_pT(p, T4_p(p));
else
vV = v3_ph(p, h4V_p(p));
vL = v3_ph(p, h4L_p(p));
end
hV = h4V_p(p);
hL = h4L_p(p);
x = (1 / rho - vL) / (vV - vL);
Out = fromSIunit_h((1 - x) * hL + x * hV);
elseif Region == 5
Out = fromSIunit_h(h5_pT(p, T5_prho(p, rho)));
else
Out = NaN;
end
Out
end
function h_Tx(t,x)
T = toSIunit_T(t);
x = toSIunit_x(x);
if x > 1 || x < 0 || T >= 647.096
Out = NaN;
return Out
end
p = p4_T(T);
hL = h4L_p(p);
hV = h4V_p(p);
Out = hL + x * (hV - hL);
Out
end
#***********************************************************************************************************
#*1.5 Specific Volume (v)
function vV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_v(v2_pT(p, T4_p(p)));
else
Out = fromSIunit_v(v3_ph(p, h4V_p(p)));
end
else
Out = NaN;
end
Out
end
rhoV_p(p)=1/vV_p(p)
function vL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_v(v1_pT(p, T4_p(p)));
else
Out = fromSIunit_v(v3_ph(p, h4L_p(p)));
end
else
Out = NaN;
end
Out
end
rhoL_p(p)=1/vL_p(p)
function vV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_v(v2_pT(p4_T(T), T));
else
Out = fromSIunit_v(v3_ph(p4_T(T), h4V_p(p4_T(T))));
end
else
Out = NaN;
end
Out
end
rhoV_T(t)=1/vV_T(t)
function vL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_v(v1_pT(p4_T(T), T));
else
Out = fromSIunit_v(v3_ph(p4_T(T), h4L_p(p4_T(T))));
end
else
Out = NaN;
end
Out
end
rhoL_T(t)=1/vL_T(t)
function v_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_v(v1_pT(p, T));
elseif Region == 2
Out = fromSIunit_v(v2_pT(p, T));
elseif Region == 3
Out = fromSIunit_v(v3_ph(p, h3_pT(p, T)));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_v(v5_pT(p, T));
else
Out = NaN;
end
Out
end
rho_pT(p,t)=1/v_pT(p,t)
function v_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Out = fromSIunit_v(v1_pT(p, T1_ph(p, h)));
elseif Region == 2
Out = fromSIunit_v(v2_pT(p, T2_ph(p, h)));
elseif Region == 3
Out = fromSIunit_v(v3_ph(p, h));
elseif Region == 4
xs = x4_ph(p, h);
if p < 16.529
v4v = v2_pT(p, T4_p(p));
v4L = v1_pT(p, T4_p(p));
else
v4v = v3_ph(p, h4V_p(p));
v4L = v3_ph(p, h4L_p(p));
end
Out = fromSIunit_v((xs * v4v + (1 - xs) * v4L));
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_v(v5_pT(p, Ts));
else
Out = NaN;
end
Out
end
rho_ph(p,h)=1/v_ph(p,h)
function v_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Out = fromSIunit_v(v1_pT(p, T1_ps(p, s)));
elseif Region == 2
Out = fromSIunit_v(v2_pT(p, T2_ps(p, s)));
elseif Region == 3
Out = fromSIunit_v(v3_ps(p, s));
elseif Region == 4
xs = x4_ps(p, s);
if p < 16.529
v4v = v2_pT(p, T4_p(p));
v4L = v1_pT(p, T4_p(p));
else
v4v = v3_ph(p, h4V_p(p));
v4L = v3_ph(p, h4L_p(p));
end
Out = fromSIunit_v((xs * v4v + (1 - xs) * v4L));
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_v(v5_pT(p, Ts));
else
Out = NaN;
end
Out
end
rho_ps(p,s)=1/v_ps(p,s)
#***********************************************************************************************************
#*1.6 Density (rho)
# Density is calculated as 1/v. Se section 1.5 Volume
#***********************************************************************************************************
#*1.7 Specific entropy (s)
function sV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_s(s2_pT(p, T4_p(p)));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function sL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_s(s1_pT(p, T4_p(p)));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function sV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_s(s2_pT(p4_T(T), T));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function sL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_s(s1_pT(p4_T(T), T));
else
Out = fromSIunit_s(s3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function s_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_s(s1_pT(p, T));
elseif Region == 2
Out = fromSIunit_s(s2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_s(s3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_s(s5_pT(p, T));
else
Out = NaN;
end
Out
end
function s_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
T = T1_ph(p, h);
Out = fromSIunit_s(s1_pT(p, T));
elseif Region == 2
T = T2_ph(p, h);
Out = fromSIunit_s(s2_pT(p, T));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_s(s3_rhoT(rhos, Ts));
elseif Region == 4
Ts = T4_p(p);
xs = x4_ph(p, h);
if p < 16.529
s4v = s2_pT(p, Ts);
s4L = s1_pT(p, Ts);
else
v4v = v3_ph(p, h4V_p(p));
s4v = s3_rhoT(1 / v4v, Ts);
v4L = v3_ph(p, h4L_p(p));
s4L = s3_rhoT(1 / v4L, Ts);
end
Out = fromSIunit_s((xs * s4v + (1 - xs) * s4L));
elseif Region == 5
T = T5_ph(p, h);
Out = fromSIunit_s(s5_pT(p, T));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.8 Specific internal energy (u)
function uV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_u(u2_pT(p, T4_p(p)));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function uL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_u(u1_pT(p, T4_p(p)));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function uV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_u(u2_pT(p4_T(T), T));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function uL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_u(u1_pT(p4_T(T), T));
else
Out = fromSIunit_u(u3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function u_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_u(u1_pT(p, T));
elseif Region == 2
Out = fromSIunit_u(u2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_u(u3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_u(u5_pT(p, T));
else
Out = NaN;
end
Out
end
function u_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_u(u1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_u(u2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_u(u3_rhoT(rhos, Ts));
elseif Region == 4
Ts = T4_p(p);
xs = x4_ph(p, h);
if p < 16.529
u4v = u2_pT(p, Ts);
u4L = u1_pT(p, Ts);
else
v4v = v3_ph(p, h4V_p(p));
u4v = u3_rhoT(1 / v4v, Ts);
v4L = v3_ph(p, h4L_p(p));
u4L = u3_rhoT(1 / v4L, Ts);
end
Out = fromSIunit_u((xs * u4v + (1 - xs) * u4L));
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_u(u5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function u_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_u(u1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_u(u2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_u(u3_rhoT(rhos, Ts));
elseif Region == 4
if p < 16.529
uLp = u1_pT(p, T4_p(p));
uVp = u2_pT(p, T4_p(p));
else
uLp = u3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p));
uVp = u3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p));
end
xs = x4_ps(p, s);
Out = fromSIunit_u((xs * uVp + (1 - xs) * uLp));
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_u(u5_pT(p, Ts));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.9 Specific isobaric heat capacity (Cp)
function CpV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cp(Cp2_pT(p, T4_p(p)));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CpL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cp(Cp1_pT(p, T4_p(p)));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CpV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cp(Cp2_pT(p4_T(T), T));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function CpL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cp(Cp1_pT(p4_T(T), T));
else
Out = fromSIunit_Cp(Cp3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function Cp_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_Cp(Cp1_pT(p, T));
elseif Region == 2
Out = fromSIunit_Cp(Cp2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_Cp(Cp3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_Cp(Cp5_pT(p, T));
else
Out = NaN;
end
Out
end
function Cp_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_Cp(Cp1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_Cp(Cp2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_Cp(Cp3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_Cp(Cp5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function Cp_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_Cp(Cp1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_Cp(Cp2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_Cp(Cp3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_Cp(Cp5_pT(p, Ts));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.10 Specific isochoric heat capacity (Cv)
function CvV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cv(Cv2_pT(p, T4_p(p)));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CvL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_Cv(Cv1_pT(p, T4_p(p)));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function CvV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cv(Cv2_pT(p4_T(T), T));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function CvL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_Cv(Cv1_pT(p4_T(T), T));
else
Out = fromSIunit_Cv(Cv3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function Cv_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_Cv(Cv1_pT(p, T));
elseif Region == 2
Out = fromSIunit_Cv(Cv2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_Cv(Cv3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_Cv(Cv5_pT(p, T));
else
Out = NaN;
end
Out
end
function Cv_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_Cv(Cv1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_Cv(Cv2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_Cv(Cv3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_Cv(Cv5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function Cv_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_Cv(Cv1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_Cv(Cv2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_Cv(Cv3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN; #(xs * CvVp + (1 - xs) * CvLp) / Cv_scale - Cv_offset
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_Cv(Cv5_pT(p, Ts));
else
#Out = CVErr(xlErrValue);
end
Out
end
#***********************************************************************************************************
#*1.11 Speed of sound
function wV_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_w(w2_pT(p, T4_p(p)));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function wL_p(p)
p = toSIunit_p(p);
if p > 0.000611657 && p < 22.06395
if p < 16.529
Out = fromSIunit_w(w1_pT(p, T4_p(p)));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p)));
end
else
Out = NaN;
end
Out
end
function wV_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_w(w2_pT(p4_T(T), T));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p4_T(T), h4V_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function wL_T(t)
T = toSIunit_T(t);
if T > 273.15 && T < 647.096
if T <= 623.15
Out = fromSIunit_w(w1_pT(p4_T(T), T));
else
Out = fromSIunit_w(w3_rhoT(1 / (v3_ph(p4_T(T), h4L_p(p4_T(T)))), T));
end
else
Out = NaN;
end
Out
end
function w_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 1
Out = fromSIunit_w(w1_pT(p, T));
elseif Region == 2
Out = fromSIunit_w(w2_pT(p, T));
elseif Region == 3
hs = h3_pT(p, T);
rhos = 1 / v3_ph(p, hs);
Out = fromSIunit_w(w3_rhoT(rhos, T));
elseif Region == 4
Out = NaN;
elseif Region == 5
Out = fromSIunit_w(w5_pT(p, T));
else
Out = NaN;
end
Out
end
function w_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region == 1
Ts = T1_ph(p, h);
Out = fromSIunit_w(w1_pT(p, Ts));
elseif Region == 2
Ts = T2_ph(p, h);
Out = fromSIunit_w(w2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ph(p, h);
Ts = T3_ph(p, h);
Out = fromSIunit_w(w3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN;
elseif Region == 5
Ts = T5_ph(p, h);
Out = fromSIunit_w(w5_pT(p, Ts));
else
Out = NaN;
end
Out
end
function w_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
Region = region_ps(p, s);
if Region == 1
Ts = T1_ps(p, s);
Out = fromSIunit_w(w1_pT(p, Ts));
elseif Region == 2
Ts = T2_ps(p, s);
Out = fromSIunit_w(w2_pT(p, Ts));
elseif Region == 3
rhos = 1 / v3_ps(p, s);
Ts = T3_ps(p, s);
Out = fromSIunit_w(w3_rhoT(rhos, Ts));
elseif Region == 4
Out = NaN; #(xs * wVp + (1 - xs) * wLp) / w_scale - w_offset
elseif Region == 5
Ts = T5_ps(p, s);
Out = fromSIunit_w(w5_pT(p, Ts));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.12 Viscosity
function my_pT(p,t)
p = toSIunit_p(p);
T = toSIunit_T(t);
Region = region_pT(p, T);
if Region == 4
Out = NaN;
elseif Region in [1,2,3,5]
Out = fromSIunit_my(my_AllRegions_pT(p, T));
else
Out = NaN;
end
Out
end
function my_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
Region = region_ph(p, h);
if Region in [1, 2, 3, 5]
Out = fromSIunit_my(my_AllRegions_ph(p, h));
elseif Region == 4
Out = NaN;
else
Out = NaN;
end
Out
end
function my_ps(p,s)
h = h_ps(p,s);
Out = my_ph(p,h);
Out
end
#***********************************************************************************************************
#*1.13 Prandtl
function pr_pT(p,t)
Cp = toSIunit_Cp(Cp_pT(p,t));
my = toSIunit_my(my_pT(p,t));
tc = toSIunit_tc(tc_pT(p,t));
Out = Cp * 1000 * my / tc;
Out
end
function pr_ph(p,h)
Cp = toSIunit_Cp(Cp_ph(p, h));
my = toSIunit_my(my_ph(p,h));
tc = toSIunit_tc(tc_ph(p,h));
Out = Cp * 1000 * my / tc;
Out
end
#***********************************************************************************************************
#*1.14 Kappa
#***********************************************************************************************************
#***********************************************************************************************************
#*1.15 Surface tension
function st_T(t)
T = toSIunit_T(t);
Out = fromSIunit_st(Surface_Tension_T(T));
Out
end
function st_p(p)
T = Tsat_p(p);
T = toSIunit_T(T);
Out = fromSIunit_st(Surface_Tension_T(T));
Out
end
#***********************************************************************************************************
#*1.16 Thermal conductivity
function tcL_p(p)
T = Tsat_p(p);
v = vL_p(p);
p = toSIunit_p(p);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tcV_p(p)
ps = p;
T = Tsat_p(ps);
v = vV_p(ps);
p = toSIunit_p(p);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tcL_T(t)
Ts = t;
p = psat_T(Ts);
v = vL_T(Ts);
p = toSIunit_p(p);
T = toSIunit_T(Ts);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tcV_T(t)
Ts = t;
p = psat_T(Ts);
v = vV_T(Ts);
p = toSIunit_p(p);
T = toSIunit_T(Ts);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tc_pT(p,t)
Ts = t;
ps = p;
v = v_pT(ps, Ts);
p = toSIunit_p(ps);
T = toSIunit_T(Ts);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tc_ph(p,h)
hs = h;
ps = p;
v = v_ph(ps, hs);
T = T_ph(ps, hs);
p = toSIunit_p(ps);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
function tc_hs(h,s)
hs = h;
p = p_hs(hs, s);
ps = p;
v = v_ph(ps, hs);
T = T_ph(ps, hs);
p = toSIunit_p(p);
T = toSIunit_T(T);
v = toSIunit_v(v);
rho = 1 / v;
Out = fromSIunit_tc(tc_ptrho(p, T, rho));
Out
end
#***********************************************************************************************************
#*1.17 Vapour fraction
function x_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_x(x4_ph(p, h));
else
Out = NaN;
end
Out
end
function x_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
if p > 0.000611657 && p < 22.06395
Out = fromSIunit_x(x4_ps(p, s));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*1.18 Vapour Volume Fraction
function vx_ph(p,h)
p = toSIunit_p(p);
h = toSIunit_h(h);
if p > 0.000611657 && p < 22.06395
if p < 16.529
vL = v1_pT(p, T4_p(p));
vV = v2_pT(p, T4_p(p));
else
vL = v3_ph(p, h4L_p(p));
vV = v3_ph(p, h4V_p(p));
end
xs = x4_ph(p, h);
Out = fromSIunit_vx((xs * vV / (xs * vV + (1 - xs) * vL)));
else
Out = NaN;
end
Out
end
function vx_ps(p,s)
p = toSIunit_p(p);
s = toSIunit_s(s);
if p > 0.000611657 && p < 22.06395
if p < 16.529
vL = v1_pT(p, T4_p(p));
vV = v2_pT(p, T4_p(p));
else
vL = v3_ph(p, h4L_p(p));
vV = v3_ph(p, h4V_p(p));
end
xs = x4_ps(p, s);
Out = fromSIunit_vx((xs * vV / (xs * vV + (1 - xs) * vL)));
else
Out = NaN;
end
Out
end
#***********************************************************************************************************
#*2 IAPWS IF 97 Calling functions *
#***********************************************************************************************************
#
#***********************************************************************************************************
#*2.1 Functions for region 1
function v1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_pi = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i]- 1) * (tau - 1.222) ^ J1[i];
end
v1_pT = R * T / p * Pi * gamma_der_pi / 1000;
v1_pT
end
function h1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_tau = 0;
for i = 1 : 34
gamma_der_tau = gamma_der_tau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i]* (tau - 1.222) ^ (J1[i] - 1));
end
h1_pT = R * T * tau * gamma_der_tau;
h1_pT
end
function u1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_tau = 0;
gamma_der_pi = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * (tau - 1.222) ^ J1[i];
gamma_der_tau = gamma_der_tau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (tau - 1.222) ^ (J1[i] - 1));
end
u1_pT = R * T * (tau * gamma_der_tau - Pi * gamma_der_pi);
u1_pT
end
function s1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma = 0;
gamma_der_tau = 0;
for i = 1 : 34
gamma_der_tau = gamma_der_tau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (tau - 1.222) ^ (J1[i] - 1));
gamma = gamma + n1[i] * (7.1 - Pi) ^ I1[i] * (tau - 1.222) ^ J1[i];
end
s1_pT = R * tau * gamma_der_tau - R * gamma;
s1_pT
end
function Cp1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_tautau = 0;
for i = 1 :34
gamma_der_tautau = gamma_der_tautau + (n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (J1[i] - 1) * (tau - 1.222) ^ (J1[i] - 2));
end
Cp1_pT = -R * tau ^ 2 * gamma_der_tautau;
Cp1_pT
end
function Cv1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_pi = 0;
gamma_der_pipi = 0;
gamma_der_pitau = 0;
gamma_der_tautau = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * (tau - 1.222) ^ J1[i];
gamma_der_pipi = gamma_der_pipi + n1[i] * I1[i] * (I1[i] - 1) * (7.1 - Pi) ^ (I1[i] - 2) * (tau - 1.222) ^ J1[i];
gamma_der_pitau = gamma_der_pitau - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * J1[i] * (tau - 1.222) ^ (J1[i] - 1);
gamma_der_tautau = gamma_der_tautau + n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (J1[i] - 1) * (tau - 1.222) ^ (J1[i] - 2);
end
Cv1_pT = R * (-tau ^ 2 * gamma_der_tautau + (gamma_der_pi - tau * gamma_der_pitau) ^ 2 / gamma_der_pipi);
Cv1_pT
end
function w1_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation
#Eqution 7, Table 3, Page 6
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32];
J1 = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41];
n1 = [0.14632971213167, -0.84548187169114, -3.756360367204, 3.3855169168385, -0.95791963387872, 0.15772038513228, -0.016616417199501, 8.1214629983568E-04, 2.8319080123804E-04, -6.0706301565874E-04, -0.018990068218419, -0.032529748770505, -0.021841717175414, -5.283835796993E-05, -4.7184321073267E-04, -3.0001780793026E-04, 4.7661393906987E-05, -4.4141845330846E-06, -7.2694996297594E-16, -3.1679644845054E-05, -2.8270797985312E-06, -8.5205128120103E-10, -2.2425281908E-06, -6.5171222895601E-07, -1.4341729937924E-13, -4.0516996860117E-07, -1.2734301741641E-09, -1.7424871230634E-10, -6.8762131295531E-19, 1.4478307828521E-20, 2.6335781662795E-23, -1.1947622640071E-23, 1.8228094581404E-24, -9.3537087292458E-26];
R = 0.461526; #kJ/(kg K)
Pi = p / 16.53;
tau = 1386 / T;
gamma_der_pi = 0;
gamma_der_pipi = 0;
gamma_der_pitau = 0;
gamma_der_tautau = 0;
for i = 1 : 34
gamma_der_pi = gamma_der_pi - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * (tau - 1.222) ^ J1[i];
gamma_der_pipi = gamma_der_pipi + n1[i] * I1[i] * (I1[i] - 1) * (7.1 - Pi) ^ (I1[i] - 2) * (tau - 1.222) ^ J1[i];
gamma_der_pitau = gamma_der_pitau - n1[i] * I1[i] * (7.1 - Pi) ^ (I1[i] - 1) * J1[i] * (tau - 1.222) ^ (J1[i] - 1);
gamma_der_tautau = gamma_der_tautau + n1[i] * (7.1 - Pi) ^ I1[i] * J1[i] * (J1[i] - 1) * (tau - 1.222) ^ (J1[i] - 2);
end
w1_pT = (1000 * R * T * gamma_der_pi ^ 2 / ((gamma_der_pi - tau * gamma_der_pitau) ^ 2 / (tau ^ 2 * gamma_der_tautau) - gamma_der_pipi)) ^ 0.5;
w1_pT
end
function T1_ph(p, h)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation, 5.2.1 The Backward Equation T ( p,h )
#Eqution 11, Table 6, Page 10
I1 = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6];
J1 = [0, 1, 2, 6, 22, 32, 0, 1, 2, 3, 4, 10, 32, 10, 32, 10, 32, 32, 32, 32];
n1 = [-238.72489924521, 404.21188637945, 113.49746881718, -5.8457616048039, -1.528548241314E-04, -1.0866707695377E-06, -13.391744872602, 43.211039183559, -54.010067170506, 30.535892203916, -6.5964749423638, 9.3965400878363E-03, 1.157364750534E-07, -2.5858641282073E-05, -4.0644363084799E-09, 6.6456186191635E-08, 8.0670734103027E-11, -9.3477771213947E-13, 5.8265442020601E-15, -1.5020185953503E-17];
Pi = p / 1;
eta = h / 2500;
T = 0;
for i = 1 : 20
T = T + n1[i] * Pi ^ I1[i] * (eta + 1) ^ J1[i];
end
T1_ph = T;
T1_ph
end
function T1_ps(p, s)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#5 Equations for Region 1, Section. 5.1 Basic Equation, 5.2.2 The Backward Equation T ( p, s )
#Eqution 13, Table 8, Page 11
I1 = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4];
J1 = [0, 1, 2, 3, 11, 31, 0, 1, 2, 3, 12, 31, 0, 1, 2, 9, 31, 10, 32, 32];
n1 = [174.78268058307, 34.806930892873, 6.5292584978455, 0.33039981775489, -1.9281382923196E-07, -2.4909197244573E-23, -0.26107636489332, 0.22592965981586, -0.064256463395226, 7.8876289270526E-03, 3.5672110607366E-10, 1.7332496994895E-24, 5.6608900654837E-04, -3.2635483139717E-04, 4.4778286690632E-05, -5.1322156908507E-10, -4.2522657042207E-26, 2.6400441360689E-13, 7.8124600459723E-29, -3.0732199903668E-31];
Pi = p / 1;
Sigma = s / 1;
T = 0;
for i = 1 : 20
T = T + n1[i] * Pi ^ I1[i] * (Sigma + 2) ^ J1[i];
end
T1_ps = T;
T1_ps
end
function p1_hs(h, s)
#Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s) to the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#5 Backward Equation p(h,s) for Region 1
#Eqution 1, Table 2, Page 5
I1 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5];
J1 = [0, 1, 2, 4, 5, 6, 8, 14, 0, 1, 4, 6, 0, 1, 10, 4, 1, 4, 0];
n1 = [-0.691997014660582, -18.361254878756, -9.28332409297335, 65.9639569909906, -16.2060388912024, 450.620017338667, 854.68067822417, 6075.23214001162, 32.6487682621856, -26.9408844582931, -319.9478483343, -928.35430704332, 30.3634537455249, -65.0540422444146, -4309.9131651613, -747.512324096068, 730.000345529245, 1142.84032569021, -436.407041874559];
eta = h / 3400;
Sigma = s / 7.6;
p = 0;
for i = 1 : 19
p = p + n1[i] * (eta + 0.05) ^ I1[i] * (Sigma + 0.05) ^ J1[i];
end
p1_hs = p * 100;
p1_hs
end
function T1_prho(p ,rho)
#Solve by iteration. Observe that for low temperatures this equation has 2 solutions.
#Solve with half interval method
Low_Bound = 273.15;
High_Bound = T4_p(p);
rhos=-1000;
Ts =0.0
while abs(rho - rhos) > 0.00001
Ts = (Low_Bound + High_Bound) / 2;
rhos = 1 / v1_pT(p, Ts);
if rhos < rho
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T1_prho = Ts;
T1_prho
end
#***********************************************************************************************************
#*2.2 functions for region 2
function v2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_pi = 1 / Pi;
gr_pi = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
end
v2_pT = R * T / p * Pi * (g0_pi + gr_pi) / 1000;
v2_pT
end
function h2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tau = 0;
for i = 1 : 9
g0_tau = g0_tau + n0[i] * J0[i] * tau ^ (J0[i] - 1);
end
gr_tau = 0;
for i = 1 : 43
gr_tau = gr_tau + nr[i] * Pi ^ Ir[i] * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
end
h2_pT = R * T * tau * (g0_tau + gr_tau);
h2_pT
end
function u2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_pi = 1 / Pi;
g0_tau = 0;
for i = 1 : 9
g0_tau = g0_tau + n0[i] * J0[i] * tau ^ (J0[i] - 1);
end
gr_pi = 0;
gr_tau = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
gr_tau = gr_tau + nr[i] * Pi ^ Ir[i] * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
end
u2_pT = R * T * (tau * (g0_tau + gr_tau) - Pi * (g0_pi + gr_pi));
u2_pT
end
function s2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0 = log(Pi);
g0_tau = 0;
for i = 1 : 9
g0 = g0 + n0[i] * tau ^ J0[i];
g0_tau = g0_tau + n0[i] * J0[i] * tau ^ (J0[i] - 1);
end
gr = 0;
gr_tau = 0;
for i = 1 : 43
gr = gr + nr[i] * Pi ^ Ir[i] * (tau - 0.5) ^ Jr[i];
gr_tau = gr_tau + nr[i] * Pi ^ Ir[i] * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
end
s2_pT = R * (tau * (g0_tau + gr_tau) - (g0 + gr));
s2_pT
end
function Cp2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tautau = 0;
for i = 1 : 9
g0_tautau = g0_tautau + n0[i] * J0[i] * (J0[i] - 1) * tau ^ (J0[i] - 2);
end
gr_tautau = 0;
for i = 1 : 43
gr_tautau = gr_tautau + nr[i] * Pi ^ Ir[i] * Jr[i] * (Jr[i] - 1) * (tau - 0.5) ^ (Jr[i] - 2);
end
Cp2_pT = -R * tau ^ 2 * (g0_tautau + gr_tautau);
Cp2_pT
end
function Cv2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tautau = 0;
for i = 1 : 9
g0_tautau = g0_tautau + n0[i] * J0[i] * (J0[i] - 1) * tau ^ (J0[i] - 2);
end
gr_pi = 0;
gr_pitau = 0;
gr_pipi = 0;
gr_tautau = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
gr_pipi = gr_pipi + nr[i] * Ir[i] * (Ir[i] - 1) * Pi ^ (Ir[i] - 2) * (tau - 0.5) ^ Jr[i];
gr_pitau = gr_pitau + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
gr_tautau = gr_tautau + nr[i] * Pi ^ Ir[i] * Jr[i] * (Jr[i] - 1) * (tau - 0.5) ^ (Jr[i] - 2);
end
Cv2_pT = R * (-tau ^ 2 * (g0_tautau + gr_tautau) - (1 + Pi * gr_pi - tau * Pi * gr_pitau) ^ 2 / (1 - Pi ^ 2 * gr_pipi));
Cv2_pT
end
function w2_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2, Section. 6.1 Basic Equation
#Table 11 and 12, Page 14 and 15
J0 = [0, 1, -5, -4, -3, -2, -1, 2, 3];
n0 = [-9.6927686500217, 10.086655968018, -0.005608791128302, 0.071452738081455, -0.40710498223928, 1.4240819171444, -4.383951131945, -0.28408632460772, 0.021268463753307];
Ir = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 10, 16, 16, 18, 20, 20, 20, 21, 22, 23, 24, 24, 24];
Jr = [0, 1, 2, 3, 6, 1, 2, 4, 7, 36, 0, 1, 3, 6, 35, 1, 2, 3, 7, 3, 16, 35, 0, 11, 25, 8, 36, 13, 4, 10, 14, 29, 50, 57, 20, 35, 48, 21, 53, 39, 26, 40, 58];
nr = [-1.7731742473213E-03, -0.017834862292358, -0.045996013696365, -0.057581259083432, -0.05032527872793, -3.3032641670203E-05, -1.8948987516315E-04, -3.9392777243355E-03, -0.043797295650573, -2.6674547914087E-05, 2.0481737692309E-08, 4.3870667284435E-07, -3.227767723857E-05, -1.5033924542148E-03, -0.040668253562649, -7.8847309559367E-10, 1.2790717852285E-08, 4.8225372718507E-07, 2.2922076337661E-06, -1.6714766451061E-11, -2.1171472321355E-03, -23.895741934104, -5.905956432427E-18, -1.2621808899101E-06, -0.038946842435739, 1.1256211360459E-11, -8.2311340897998, 1.9809712802088E-08, 1.0406965210174E-19, -1.0234747095929E-13, -1.0018179379511E-09, -8.0882908646985E-11, 0.10693031879409, -0.33662250574171, 8.9185845355421E-25, 3.0629316876232E-13, -4.2002467698208E-06, -5.9056029685639E-26, 3.7826947613457E-06, -1.2768608934681E-15, 7.3087610595061E-29, 5.5414715350778E-17, -9.436970724121E-07];
R = 0.461526; #kJ/(kg K)
Pi = p;
tau = 540 / T;
g0_tautau = 0;
for i = 1 : 9
g0_tautau = g0_tautau + n0[i] * J0[i] * (J0[i] - 1) * tau ^ (J0[i] - 2);
end
gr_pi = 0;
gr_pitau = 0;
gr_pipi = 0;
gr_tautau = 0;
for i = 1 : 43
gr_pi = gr_pi + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * (tau - 0.5) ^ Jr[i];
gr_pipi = gr_pipi + nr[i] * Ir[i] * (Ir[i] - 1) * Pi ^ (Ir[i] - 2) * (tau - 0.5) ^ Jr[i];
gr_pitau = gr_pitau + nr[i] * Ir[i] * Pi ^ (Ir[i] - 1) * Jr[i] * (tau - 0.5) ^ (Jr[i] - 1);
gr_tautau = gr_tautau + nr[i] * Pi ^ Ir[i] * Jr[i] * (Jr[i] - 1) * (tau - 0.5) ^ (Jr[i] - 2);
end
w2_pT = (1000 * R * T * (1 + 2 * Pi * gr_pi + Pi ^ 2 * gr_pi ^ 2) / ((1 - Pi ^ 2 * gr_pipi) + (1 + Pi * gr_pi - tau * Pi * gr_pitau) ^ 2 / (tau ^ 2 * (g0_tautau + gr_tautau)))) ^ 0.5;
w2_pT
end
function T2_ph(p, h)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2,6.3.1 The Backward Equations T( p, h ) for Subregions 2a, 2b, and 2c
if p < 4
sub_reg = 1;
else
if p < (905.84278514723 - 0.67955786399241 * h + 1.2809002730136E-04 * h ^ 2)
sub_reg = 2;
else
sub_reg = 3;
end
end
if sub_reg == 1
#Subregion A
#Table 20, Eq 22, page 22
Ji = [0, 1, 2, 3, 7, 20, 0, 1, 2, 3, 7, 9, 11, 18, 44, 0, 2, 7, 36, 38, 40, 42, 44, 24, 44, 12, 32, 44, 32, 36, 42, 34, 44, 28];
Ii = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7];
ni = [1089.8952318288, 849.51654495535, -107.81748091826, 33.153654801263, -7.4232016790248, 11.765048724356, 1.844574935579, -4.1792700549624, 6.2478196935812, -17.344563108114, -200.58176862096, 271.96065473796, -455.11318285818, 3091.9688604755, 252266.40357872, -6.1707422868339E-03, -0.31078046629583, 11.670873077107, 128127984.04046, -985549096.23276, 2822454697.3002, -3594897141.0703, 1722734991.3197, -13551.334240775, 12848734.66465, 1.3865724283226, 235988.32556514, -13105236.545054, 7399.9835474766, -551966.9703006, 3715408.5996233, 19127.72923966, -415351.64835634, -62.459855192507];
Ts = 0;
hs = h / 2000;
for i = 1 : 34
Ts = Ts + ni[i] * p ^ (Ii[i]) * (hs - 2.1) ^ Ji[i];
end
T2_ph = Ts;
elseif sub_reg == 2
#Subregion B
#Table 21, Eq 23, page 23
Ji = [0, 1, 2, 12, 18, 24, 28, 40, 0, 2, 6, 12, 18, 24, 28, 40, 2, 8, 18, 40, 1, 2, 12, 24, 2, 12, 18, 24, 28, 40, 18, 24, 40, 28, 2, 28, 1, 40];
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 6, 7, 7, 9, 9];
ni = [1489.5041079516, 743.07798314034, -97.708318797837, 2.4742464705674, -0.63281320016026, 1.1385952129658, -0.47811863648625, 8.5208123431544E-03, 0.93747147377932, 3.3593118604916, 3.3809355601454, 0.16844539671904, 0.73875745236695, -0.47128737436186, 0.15020273139707, -0.002176411421975, -0.021810755324761, -0.10829784403677, -0.046333324635812, 7.1280351959551E-05, 1.1032831789999E-04, 1.8955248387902E-04, 3.0891541160537E-03, 1.3555504554949E-03, 2.8640237477456E-07, -1.0779857357512E-05, -7.6462712454814E-05, 1.4052392818316E-05, -3.1083814331434E-05, -1.0302738212103E-06, 2.821728163504E-07, 1.2704902271945E-06, 7.3803353468292E-08, -1.1030139238909E-08, -8.1456365207833E-14, -2.5180545682962E-11, -1.7565233969407E-18, 8.6934156344163E-15];
Ts = 0;
hs = h / 2000;
for i = 1 : 38
Ts = Ts + ni[i] * (p - 2) ^ (Ii[i]) * (hs - 2.6) ^ Ji[i];
end
T2_ph = Ts;
else
#Subregion C
#Table 22, Eq 24, page 24
Ji = [0, 4, 0, 2, 0, 2, 0, 1, 0, 2, 0, 1, 4, 8, 4, 0, 1, 4, 10, 12, 16, 20, 22];
Ii = [-7, -7, -6, -6, -5, -5, -2, -2, -1, -1, 0, 0, 1, 1, 2, 6, 6, 6, 6, 6, 6, 6, 6];
ni = [-3236839855524.2, 7326335090218.1, 358250899454.47, -583401318515.9, -10783068217.47, 20825544563.171, 610747.83564516, 859777.2253558, -25745.72360417, 31081.088422714, 1208.2315865936, 482.19755109255, 3.7966001272486, -10.842984880077, -0.04536417267666, 1.4559115658698E-13, 1.126159740723E-12, -1.7804982240686E-11, 1.2324579690832E-07, -1.1606921130984E-06, 2.7846367088554E-05, -5.9270038474176E-04, 1.2918582991878E-03];
Ts = 0;
hs = h / 2000;
for i = 1 : 23
Ts = Ts + ni[i] * (p + 25) ^ (Ii[i]) * (hs - 1.8) ^ Ji[i];
end
T2_ph = Ts;
end
T2_ph
end
function T2_ps(p, s)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#6 Equations for Region 2,6.3.2 The Backward Equations T( p, s ) for Subregions 2a, 2b, and 2c
#Page 26
if p < 4
sub_reg = 1;
else
if s < 5.85
sub_reg = 3;
else
sub_reg = 2;
end
end
if sub_reg == 1
#Subregion A
#Table 25, Eq 25, page 26
Ii = [-1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.25, -1.25, -1.25, -1, -1, -1, -1, -1, -1, -0.75, -0.75, -0.5, -0.5, -0.5, -0.5, -0.25, -0.25, -0.25, -0.25, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.75, 0.75, 0.75, 0.75, 1, 1, 1.25, 1.25, 1.5, 1.5];
Ji = [-24, -23, -19, -13, -11, -10, -19, -15, -6, -26, -21, -17, -16, -9, -8, -15, -14, -26, -13, -9, -7, -27, -25, -11, -6, 1, 4, 8, 11, 0, 1, 5, 6, 10, 14, 16, 0, 4, 9, 17, 7, 18, 3, 15, 5, 18];
ni = [-392359.83861984, 515265.7382727, 40482.443161048, -321.93790923902, 96.961424218694, -22.867846371773, -449429.14124357, -5011.8336020166, 0.35684463560015, 44235.33584819, -13673.388811708, 421632.60207864, 22516.925837475, 474.42144865646, -149.31130797647, -197811.26320452, -23554.39947076, -19070.616302076, 55375.669883164, 3829.3691437363, -603.91860580567, 1936.3102620331, 4266.064369861, -5978.0638872718, -704.01463926862, 338.36784107553, 20.862786635187, 0.033834172656196, -4.3124428414893E-05, 166.53791356412, -139.86292055898, -0.78849547999872, 0.072132411753872, -5.9754839398283E-03, -1.2141358953904E-05, 2.3227096733871E-07, -10.538463566194, 2.0718925496502, -0.072193155260427, 2.074988708112E-07, -0.018340657911379, 2.9036272348696E-07, 0.21037527893619, 2.5681239729999E-04, -0.012799002933781, -8.2198102652018E-06];
Pi = p;
Sigma = s / 2;
teta = 0;
for i = 1 : 46
teta = teta + ni[i] * Pi ^ Ii[i] * (Sigma - 2) ^ Ji[i];
end
T2_ps = teta;
elseif sub_reg == 2
#Subregion B
#Table 26, Eq 26, page 27
Ii = [-6, -6, -5, -5, -4, -4, -4, -3, -3, -3, -3, -2, -2, -2, -2, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5];
Ji = [0, 11, 0, 11, 0, 1, 11, 0, 1, 11, 12, 0, 1, 6, 10, 0, 1, 5, 8, 9, 0, 1, 2, 4, 5, 6, 9, 0, 1, 2, 3, 7, 8, 0, 1, 5, 0, 1, 3, 0, 1, 0, 1, 2];
ni = [316876.65083497, 20.864175881858, -398593.99803599, -21.816058518877, 223697.85194242, -2784.1703445817, 9.920743607148, -75197.512299157, 2970.8605951158, -3.4406878548526, 0.38815564249115, 17511.29508575, -1423.7112854449, 1.0943803364167, 0.89971619308495, -3375.9740098958, 471.62885818355, -1.9188241993679, 0.41078580492196, -0.33465378172097, 1387.0034777505, -406.63326195838, 41.72734715961, 2.1932549434532, -1.0320050009077, 0.35882943516703, 5.2511453726066E-03, 12.838916450705, -2.8642437219381, 0.56912683664855, -0.099962954584931, -3.2632037778459E-03, 2.3320922576723E-04, -0.1533480985745, 0.029072288239902, 3.7534702741167E-04, 1.7296691702411E-03, -3.8556050844504E-04, -3.5017712292608E-05, -1.4566393631492E-05, 5.6420857267269E-06, 4.1286150074605E-08, -2.0684671118824E-08, 1.6409393674725E-09];
Pi = p;
Sigma = s / 0.7853;
teta = 0;
for i = 1 : 44
teta = teta + ni[i] * Pi ^ Ii[i] * (10 - Sigma) ^ Ji[i];
end
T2_ps = teta;
else
#Subregion C
#Table 27, Eq 27, page 28
Ii = [-2, -2, -1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 7];
Ji = [0, 1, 0, 0, 1, 2, 3, 0, 1, 3, 4, 0, 1, 2, 0, 1, 5, 0, 1, 4, 0, 1, 2, 0, 1, 0, 1, 3, 4, 5];
ni = [909.68501005365, 2404.566708842, -591.6232638713, 541.45404128074, -270.98308411192, 979.76525097926, -469.66772959435, 14.399274604723, -19.104204230429, 5.3299167111971, -21.252975375934, -0.3114733441376, 0.60334840894623, -0.042764839702509, 5.8185597255259E-03, -0.014597008284753, 5.6631175631027E-03, -7.6155864584577E-05, 2.2440342919332E-04, -1.2561095013413E-05, 6.3323132660934E-07, -2.0541989675375E-06, 3.6405370390082E-08, -2.9759897789215E-09, 1.0136618529763E-08, 5.9925719692351E-12, -2.0677870105164E-11, -2.0874278181886E-11, 1.0162166825089E-10, -1.6429828281347E-10];
Pi = p;
Sigma = s / 2.9251;
teta = 0;
for i = 1 : 30
teta = teta + ni[i] * Pi ^ Ii[i] * (2 - Sigma) ^ Ji[i];
end
T2_ps = teta;
end
T2_ps
end
function p2_hs(h, s)
#Supplementary Release on Backward Equations for Pressure as a function of Enthalpy and Entropy p(h,s) to the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#Chapter 6:Backward Equations p(h,s) for Region 2
if h < (-3498.98083432139 + 2575.60716905876 * s - 421.073558227969 * s ^ 2 + 27.6349063799944 * s ^ 3)
sub_reg = 1;
else
if s < 5.85
sub_reg = 3;
else
sub_reg = 2;
end
end
if sub_reg == 1
#Subregion A
#Table 6, Eq 3, page 8
Ii = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 5, 5, 6, 7];
Ji = [1, 3, 6, 16, 20, 22, 0, 1, 2, 3, 5, 6, 10, 16, 20, 22, 3, 16, 20, 0, 2, 3, 6, 16, 16, 3, 16, 3, 1];
ni = [-1.82575361923032E-02, -0.125229548799536, 0.592290437320145, 6.04769706185122, 238.624965444474, -298.639090222922, 0.051225081304075, -0.437266515606486, 0.413336902999504, -5.16468254574773, -5.57014838445711, 12.8555037824478, 11.414410895329, -119.504225652714, -2847.7798596156, 4317.57846408006, 1.1289404080265, 1974.09186206319, 1516.12444706087, 1.41324451421235E-02, 0.585501282219601, -2.97258075863012, 5.94567314847319, -6236.56565798905, 9659.86235133332, 6.81500934948134, -6332.07286824489, -5.5891922446576, 4.00645798472063E-02];
eta = h / 4200;
Sigma = s / 12;
Pi = 0;
for i = 1 : 29
Pi = Pi + ni[i] * (eta - 0.5) ^ Ii[i] * (Sigma - 1.2) ^ Ji[i];
end
p2_hs = Pi ^ 4 * 4;
elseif sub_reg == 2
#Subregion B
#Table 7, Eq 4, page 9
Ii = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 12, 14];
Ji = [0, 1, 2, 4, 8, 0, 1, 2, 3, 5, 12, 1, 6, 18, 0, 1, 7, 12, 1, 16, 1, 12, 1, 8, 18, 1, 16, 1, 3, 14, 18, 10, 16];
ni = [8.01496989929495E-02, -0.543862807146111, 0.337455597421283, 8.9055545115745, 313.840736431485, 0.797367065977789, -1.2161697355624, 8.72803386937477, -16.9769781757602, -186.552827328416, 95115.9274344237, -18.9168510120494, -4334.0703719484, 543212633.012715, 0.144793408386013, 128.024559637516, -67230.9534071268, 33697238.0095287, -586.63419676272, -22140322476.9889, 1716.06668708389, -570817595.806302, -3121.09693178482, -2078413.8463301, 3056059461577.86, 3221.57004314333, 326810259797.295, -1441.04158934487, 410.694867802691, 109077066873.024, -24796465425889.3, 1888019068.65134, -123651009018773];
eta = h / 4100;
Sigma = s / 7.9;
Pi = 0;
for i = 1 : 33
Pi = Pi + ni[i] * (eta - 0.6) ^ Ii[i] * (Sigma - 1.01) ^ Ji[i];
end
p2_hs = Pi ^ 4 * 100;
else
#Subregion C
#Table 8, Eq 5, page 10
Ii = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 10, 12, 16];
Ji = [0, 1, 2, 3, 4, 8, 0, 2, 5, 8, 14, 2, 3, 7, 10, 18, 0, 5, 8, 16, 18, 18, 1, 4, 6, 14, 8, 18, 7, 7, 10];
ni = [0.112225607199012, -3.39005953606712, -32.0503911730094, -197.5973051049, -407.693861553446, 13294.3775222331, 1.70846839774007, 37.3694198142245, 3581.44365815434, 423014.446424664, -751071025.760063, 52.3446127607898, -228.351290812417, -960652.417056937, -80705929.2526074, 1626980172256.69, 0.772465073604171, 46392.9973837746, -13731788.5134128, 1704703926305.12, -25110462818730.8, 31774883083552, 53.8685623675312, -55308.9094625169, -1028615.22421405, 2042494187562.34, 273918446.626977, -2.63963146312685E+15, -1078908541.08088, -29649262098.0124, -1.11754907323424E+15];
eta = h / 3500;
Sigma = s / 5.9;
Pi = 0;
for i = 1 : 31
Pi = Pi + ni[i] * (eta - 0.7) ^ Ii[i] * (Sigma - 1.1) ^ Ji[i];
end
p2_hs = Pi ^ 4 * 100;
end
p2_hs
end
function T2_prho(p,rho)
#Solve by iteration. Observe that fo low temperatures this equation has 2 solutions.
#Solve with half interval method
if p < 16.5292
Low_Bound = T4_p(p);
else
Low_Bound = B23T_p(p);
end
High_Bound = 1073.15;
rhos=-1000;
Ts=0.0
while abs(rho - rhos) > 0.000001
Ts = (Low_Bound + High_Bound) / 2;
rhos = 1 / v2_pT(p, Ts);
if rhos < rho
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T2_prho = Ts;
T2_prho
end
#***********************************************************************************************************
#*2.3 functions for region 3
function p3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fidelta = 0;
for i = 2 : 40
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
end
fidelta = fidelta + ni(1) / delta;
p3_rhoT = rho * R * T * delta * fidelta / 1000;
p3_rhoT
end
function u3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitau = 0;
for i = 2 : 40
fitau = fitau + ni[i] * delta ^ Ii[i] * Ji[i] * tau ^ (Ji[i] - 1);
end
u3_rhoT = R * T * (tau * fitau);
u3_rhoT
end
function h3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fidelta = 0;
fitau = 0;
for i = 2 : 40
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
fitau = fitau + ni[i] * delta ^ Ii[i] * Ji[i] * tau ^ (Ji[i] - 1);
end
fidelta = fidelta + ni(1) / delta;
h3_rhoT = R * T * (tau * fitau + delta * fidelta);
h3_rhoT
end
function s3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fi = 0;
fitau = 0;
for i = 2 : 40
fi = fi + ni[i] * delta ^ Ii[i] * tau ^ Ji[i];
fitau = fitau + ni[i] * delta ^ Ii[i] * Ji[i] * tau ^ (Ji[i] - 1);
end
fi = fi + ni(1) * log(delta);
s3_rhoT = R * (tau * fitau - fi);
s3_rhoT
end
function Cp3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitautau = 0;
fidelta = 0;
fideltatau = 0;
fideltadelta = 0;
for i = 2 : 40
fitautau = fitautau + ni[i] * delta ^ Ii[i] * Ji[i] * (Ji[i] - 1) * tau ^ (Ji[i] - 2);
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
fideltatau = fideltatau + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * Ji[i] * tau ^ (Ji[i] - 1);
fideltadelta = fideltadelta + ni[i] * Ii[i] * (Ii[i] - 1) * delta ^ (Ii[i] - 2) * tau ^ Ji[i];
end
fidelta = fidelta + ni(1) / delta;
fideltadelta = fideltadelta - ni(1) / (delta ^ 2);
Cp3_rhoT = R * (-tau ^ 2 * fitautau + (delta * fidelta - delta * tau * fideltatau) ^ 2 / (2 * delta * fidelta + delta ^ 2 * fideltadelta));
Cp3_rhoT
end
function Cv3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitautau = 0;
for i = 1 : 40
fitautau = fitautau + ni[i] * delta ^ Ii[i] * Ji[i] * (Ji[i] - 1) * tau ^ (Ji[i] - 2);
end
Cv3_rhoT = R * -(tau * tau * fitautau);
Cv3_rhoT
end
function w3_rhoT(rho, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#7 Basic Equation for Region 3, Section. 6.1 Basic Equation
#Table 30 and 31, Page 30 and 31
Ii = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 10, 10, 11];
Ji = [0, 0, 1, 2, 7, 10, 12, 23, 2, 6, 15, 17, 0, 2, 6, 7, 22, 26, 0, 2, 4, 16, 26, 0, 2, 4, 26, 1, 3, 26, 0, 2, 26, 2, 26, 2, 26, 0, 1, 26];
ni = [1.0658070028513, -15.732845290239, 20.944396974307, -7.6867707878716, 2.6185947787954, -2.808078114862, 1.2053369696517, -8.4566812812502E-03, -1.2654315477714, -1.1524407806681, 0.88521043984318, -0.64207765181607, 0.38493460186671, -0.85214708824206, 4.8972281541877, -3.0502617256965, 0.039420536879154, 0.12558408424308, -0.2799932969871, 1.389979956946, -2.018991502357, -8.2147637173963E-03, -0.47596035734923, 0.0439840744735, -0.44476435428739, 0.90572070719733, 0.70522450087967, 0.10770512626332, -0.32913623258954, -0.50871062041158, -0.022175400873096, 0.094260751665092, 0.16436278447961, -0.013503372241348, -0.014834345352472, 5.7922953628084E-04, 3.2308904703711E-03, 8.0964802996215E-05, -1.6557679795037E-04, -4.4923899061815E-05];
R = 0.461526; #kJ/(KgK)
tc = 647.096; #K
pc = 22.064; #MPa
rhoc = 322; #kg/m3
delta = rho / rhoc;
tau = tc / T;
fitautau = 0;
fidelta = 0;
fideltatau = 0;
fideltadelta = 0;
for i = 2 : 40
fitautau = fitautau + ni[i] * delta ^ Ii[i] * Ji[i] * (Ji[i] - 1) * tau ^ (Ji[i] - 2);
fidelta = fidelta + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * tau ^ Ji[i];
fideltatau = fideltatau + ni[i] * Ii[i] * delta ^ (Ii[i] - 1) * Ji[i] * tau ^ (Ji[i] - 1);
fideltadelta = fideltadelta + ni[i] * Ii[i] * (Ii[i] - 1) * delta ^ (Ii[i] - 2) * tau ^ Ji[i];
end
fidelta = fidelta + ni(1) / delta;
fideltadelta = fideltadelta - ni(1) / (delta ^ 2);
w3_rhoT = (1000 * R * T * (2 * delta * fidelta + delta ^ 2 * fideltadelta - (delta * fidelta - delta * tau * fideltatau) ^ 2 / (tau ^ 2 * fitautau))) ^ 0.5;
w3_rhoT
end
function T3_ph(p, h)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#Section 3.3 Backward Equations T(p,h) and v(p,h) for Subregions 3a and 3b
#Boundary equation, Eq 1 Page 5
h3ab = 2014.64004206875 + 3.74696550136983 * p - 2.19921901054187E-02 * p ^ 2 + 8.7513168600995E-05 * p ^ 3;
if h < h3ab
#Subregion 3a
#Eq 2, Table 3, Page 7
Ii = [-12, -12, -12, -12, -12, -12, -12, -12, -10, -10, -10, -8, -8, -8, -8, -5, -3, -2, -2, -2, -1, -1, 0, 0, 1, 3, 3, 4, 4, 10, 12];
Ji = [0, 1, 2, 6, 14, 16, 20, 22, 1, 5, 12, 0, 2, 4, 10, 2, 0, 1, 3, 4, 0, 2, 0, 1, 1, 0, 1, 0, 3, 4, 5];
ni = [-1.33645667811215E-07, 4.55912656802978E-06, -1.46294640700979E-05, 6.3934131297008E-03, 372.783927268847, -7186.54377460447, 573494.7521034, -2675693.29111439, -3.34066283302614E-05, -2.45479214069597E-02, 47.8087847764996, 7.64664131818904E-06, 1.28350627676972E-03, 1.71219081377331E-02, -8.51007304583213, -1.36513461629781E-02, -3.84460997596657E-06, 3.37423807911655E-03, -0.551624873066791, 0.72920227710747, -9.92522757376041E-03, -0.119308831407288, 0.793929190615421, 0.454270731799386, 0.20999859125991, -6.42109823904738E-03, -0.023515586860454, 2.52233108341612E-03, -7.64885133368119E-03, 1.36176427574291E-02, -1.33027883575669E-02];
ps = p / 100;
hs = h / 2300;
Ts = 0;
for i = 1 : 31
Ts = Ts + ni[i] * (ps + 0.24) ^ Ii[i] * (hs - 0.615) ^ Ji[i];
end
T3_ph = Ts * 760;
else
#Subregion 3b
#Eq 3, Table 4, Page 7,8
Ii = [-12, -12, -10, -10, -10, -10, -10, -8, -8, -8, -8, -8, -6, -6, -6, -4, -4, -3, -2, -2, -1, -1, -1, -1, -1, -1, 0, 0, 1, 3, 5, 6, 8];
Ji = [0, 1, 0, 1, 5, 10, 12, 0, 1, 2, 4, 10, 0, 1, 2, 0, 1, 5, 0, 4, 2, 4, 6, 10, 14, 16, 0, 2, 1, 1, 1, 1, 1];
ni = [3.2325457364492E-05, -1.27575556587181E-04, -4.75851877356068E-04, 1.56183014181602E-03, 0.105724860113781, -85.8514221132534, 724.140095480911, 2.96475810273257E-03, -5.92721983365988E-03, -1.26305422818666E-02, -0.115716196364853, 84.9000969739595, -1.08602260086615E-02, 1.54304475328851E-02, 7.50455441524466E-02, 2.52520973612982E-02, -6.02507901232996E-02, -3.07622221350501, -5.74011959864879E-02, 5.03471360939849, -0.925081888584834, 3.91733882917546, -77.314600713019, 9493.08762098587, -1410437.19679409, 8491662.30819026, 0.861095729446704, 0.32334644281172, 0.873281936020439, -0.436653048526683, 0.286596714529479, -0.131778331276228, 6.76682064330275E-03];
hs = h / 2800;
ps = p / 100;
Ts = 0;
for i = 1 : 33
Ts = Ts + ni[i] * (ps + 0.298) ^ Ii[i] * (hs - 0.72) ^ Ji[i];
end
T3_ph = Ts * 860;
end
T3_ph
end
function v3_ph(p, h)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#Section 3.3 Backward Equations T(p,h) and v(p,h) for Subregions 3a and 3b
#Boundary equation, Eq 1 Page 5
h3ab = 2014.64004206875 + 3.74696550136983 * p - 2.19921901054187E-02 * p ^ 2 + 8.7513168600995E-05 * p ^ 3;
if h < h3ab
#Subregion 3a
#Eq 4, Table 6, Page 9
Ii = [-12, -12, -12, -12, -10, -10, -10, -8, -8, -6, -6, -6, -4, -4, -3, -2, -2, -1, -1, -1, -1, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 8];
Ji = [6, 8, 12, 18, 4, 7, 10, 5, 12, 3, 4, 22, 2, 3, 7, 3, 16, 0, 1, 2, 3, 0, 1, 0, 1, 2, 0, 2, 0, 2, 2, 2];
ni = [5.29944062966028E-03, -0.170099690234461, 11.1323814312927, -2178.98123145125, -5.06061827980875E-04, 0.556495239685324, -9.43672726094016, -0.297856807561527, 93.9353943717186, 1.92944939465981E-02, 0.421740664704763, -3689141.2628233, -7.37566847600639E-03, -0.354753242424366, -1.99768169338727, 1.15456297059049, 5683.6687581596, 8.08169540124668E-03, 0.172416341519307, 1.04270175292927, -0.297691372792847, 0.560394465163593, 0.275234661176914, -0.148347894866012, -6.51142513478515E-02, -2.92468715386302, 6.64876096952665E-02, 3.52335014263844, -1.46340792313332E-02, -2.24503486668184, 1.10533464706142, -4.08757344495612E-02];
ps = p / 100;
hs = h / 2100;
vs = 0;
for i = 1 : 32
vs = vs + ni[i] * (ps + 0.128) ^ Ii[i] * (hs - 0.727) ^ Ji[i];
end
v3_ph = vs * 0.0028;
else
#Subregion 3b
#Eq 5, Table 7, Page 9
Ii = [-12, -12, -8, -8, -8, -8, -8, -8, -6, -6, -6, -6, -6, -6, -4, -4, -4, -3, -3, -2, -2, -1, -1, -1, -1, 0, 1, 1, 2, 2];
Ji = [0, 1, 0, 1, 3, 6, 7, 8, 0, 1, 2, 5, 6, 10, 3, 6, 10, 0, 2, 1, 2, 0, 1, 4, 5, 0, 0, 1, 2, 6];
ni = [-2.25196934336318E-09, 1.40674363313486E-08, 2.3378408528056E-06, -3.31833715229001E-05, 1.07956778514318E-03, -0.271382067378863, 1.07202262490333, -0.853821329075382, -2.15214194340526E-05, 7.6965608822273E-04, -4.31136580433864E-03, 0.453342167309331, -0.507749535873652, -100.475154528389, -0.219201924648793, -3.21087965668917, 607.567815637771, 5.57686450685932E-04, 0.18749904002955, 9.05368030448107E-03, 0.285417173048685, 3.29924030996098E-02, 0.239897419685483, 4.82754995951394, -11.8035753702231, 0.169490044091791, -1.79967222507787E-02, 3.71810116332674E-02, -5.36288335065096E-02, 1.6069710109252];
ps = p / 100;
hs = h / 2800;
vs = 0;
for i = 1 : 30
vs = vs + ni[i] * (ps + 0.0661) ^ Ii[i] * (hs - 0.72) ^ Ji[i];
end
v3_ph = vs * 0.0088;
end
v3_ph
end
function T3_ps(p, s)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#3.4 Backward Equations T(p,s) and v(p,s) for Subregions 3a and 3b
#Boundary equation, Eq 6 Page 11
if s <= 4.41202148223476
#Subregion 3a
#Eq 6, Table 10, Page 11
Ii = [-12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -6, -6, -5, -5, -5, -4, -4, -4, -2, -2, -1, -1, 0, 0, 0, 1, 2, 2, 3, 8, 8, 10];
Ji = [28, 32, 4, 10, 12, 14, 5, 7, 8, 28, 2, 6, 32, 0, 14, 32, 6, 10, 36, 1, 4, 1, 6, 0, 1, 4, 0, 0, 3, 2, 0, 1, 2];
ni = [1500420082.63875, -159397258480.424, 5.02181140217975E-04, -67.2057767855466, 1450.58545404456, -8238.8953488889, -0.154852214233853, 11.2305046746695, -29.7000213482822, 43856513263.5495, 1.37837838635464E-03, -2.97478527157462, 9717779473494.13, -5.71527767052398E-05, 28830.794977842, -74442828926270.3, 12.8017324848921, -368.275545889071, 6.64768904779177E+15, 0.044935925195888, -4.22897836099655, -0.240614376434179, -4.74341365254924, 0.72409399912611, 0.923874349695897, 3.99043655281015, 3.84066651868009E-02, -3.59344365571848E-03, -0.735196448821653, 0.188367048396131, 1.41064266818704E-04, -2.57418501496337E-03, 1.23220024851555E-03];
Sigma = s / 4.4;
Pi = p / 100;
teta = 0;
for i = 1 : 33
teta = teta + ni[i] * (Pi + 0.24) ^ Ii[i] * (Sigma - 0.703) ^ Ji[i];
end
T3_ps = teta * 760;
else
#Subregion 3b
#Eq 7, Table 11, Page 11
Ii = [-12, -12, -12, -12, -8, -8, -8, -6, -6, -6, -5, -5, -5, -5, -5, -4, -3, -3, -2, 0, 2, 3, 4, 5, 6, 8, 12, 14];
Ji = [1, 3, 4, 7, 0, 1, 3, 0, 2, 4, 0, 1, 2, 4, 6, 12, 1, 6, 2, 0, 1, 1, 0, 24, 0, 3, 1, 2];
ni = [0.52711170160166, -40.1317830052742, 153.020073134484, -2247.99398218827, -0.193993484669048, -1.40467557893768, 42.6799878114024, 0.752810643416743, 22.6657238616417, -622.873556909932, -0.660823667935396, 0.841267087271658, -25.3717501764397, 485.708963532948, 880.531517490555, 2650155.92794626, -0.359287150025783, -656.991567673753, 2.41768149185367, 0.856873461222588, 0.655143675313458, -0.213535213206406, 5.62974957606348E-03, -316955725450471, -6.99997000152457E-04, 1.19845803210767E-02, 1.93848122022095E-05, -2.15095749182309E-05];
Sigma = s / 5.3;
Pi = p / 100;
teta = 0;
for i = 1 : 28
teta = teta + ni[i] * (Pi + 0.76) ^ Ii[i] * (Sigma - 0.818) ^ Ji[i];
end
T3_ps = teta * 860;
end
T3_ps
end
function v3_ps(p, s)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#2004
#3.4 Backward Equations T(p,s) and v(p,s) for Subregions 3a and 3b
#Boundary equation, Eq 6 Page 11
if s <= 4.41202148223476
#Subregion 3a
#Eq 8, Table 13, Page 14
Ii = [-12, -12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -5, -4, -3, -3, -2, -2, -1, -1, 0, 0, 0, 1, 2, 4, 5, 6];
Ji = [10, 12, 14, 4, 8, 10, 20, 5, 6, 14, 16, 28, 1, 5, 2, 4, 3, 8, 1, 2, 0, 1, 3, 0, 0, 2, 2, 0];
ni = [79.5544074093975, -2382.6124298459, 17681.3100617787, -1.10524727080379E-03, -15.3213833655326, 297.544599376982, -35031520.6871242, 0.277513761062119, -0.523964271036888, -148011.182995403, 1600148.99374266, 1708023226634.27, 2.46866996006494E-04, 1.6532608479798, -0.118008384666987, 2.537986423559, 0.965127704669424, -28.2172420532826, 0.203224612353823, 1.10648186063513, 0.52612794845128, 0.277000018736321, 1.08153340501132, -7.44127885357893E-02, 1.64094443541384E-02, -6.80468275301065E-02, 0.025798857610164, -1.45749861944416E-04];
Pi = p / 100;
Sigma = s / 4.4;
omega = 0;
for i = 1 : 28
omega = omega + ni[i] * (Pi + 0.187) ^ Ii[i] * (Sigma - 0.755) ^ Ji[i];
end
v3_ps = omega * 0.0028;
else
#Subregion 3b
#Eq 9, Table 14, Page 14
Ii = [-12, -12, -12, -12, -12, -12, -10, -10, -10, -10, -8, -5, -5, -5, -4, -4, -4, -4, -3, -2, -2, -2, -2, -2, -2, 0, 0, 0, 1, 1, 2];
Ji = [0, 1, 2, 3, 5, 6, 0, 1, 2, 4, 0, 1, 2, 3, 0, 1, 2, 3, 1, 0, 1, 2, 3, 4, 12, 0, 1, 2, 0, 2, 2];
ni = [5.91599780322238E-05, -1.85465997137856E-03, 1.04190510480013E-02, 5.9864730203859E-03, -0.771391189901699, 1.72549765557036, -4.67076079846526E-04, 1.34533823384439E-02, -8.08094336805495E-02, 0.508139374365767, 1.28584643361683E-03, -1.63899353915435, 5.86938199318063, -2.92466667918613, -6.14076301499537E-03, 5.76199014049172, -12.1613320606788, 1.67637540957944, -7.44135838773463, 3.78168091437659E-02, 4.01432203027688, 16.0279837479185, 3.17848779347728, -3.58362310304853, -1159952.60446827, 0.199256573577909, -0.122270624794624, -19.1449143716586, -1.50448002905284E-02, 14.6407900162154, -3.2747778718823];
Pi = p / 100;
Sigma = s / 5.3;
omega = 0;
for i = 1 : 31
omega = omega + ni[i] * (Pi + 0.298) ^ Ii[i] * (Sigma - 0.816) ^ Ji[i];
end
v3_ps = omega * 0.0088;
end
v3_ps
end
function p3_hs(h, s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Equations as a function of h and s for the Region Boundaries, and an Equation
#( ) sat , T hs for Region 4 of the IAPWS Industrial formulation 1997 for the
#Thermodynamic Properties of Water and Steam
#2004
#Section 3 Backward functions p(h,s), T(h,s), and v(h,s) for Region 3
if s < 4.41202148223476
#Subregion 3a
#Eq 1, Table 3, Page 8
Ii = [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8, 10, 10, 14, 18, 20, 22, 22, 24, 28, 28, 32, 32];
Ji = [0, 1, 5, 0, 3, 4, 8, 14, 6, 16, 0, 2, 3, 0, 1, 4, 5, 28, 28, 24, 1, 32, 36, 22, 28, 36, 16, 28, 36, 16, 36, 10, 28];
ni = [7.70889828326934, -26.0835009128688, 267.416218930389, 17.2221089496844, -293.54233214597, 614.135601882478, -61056.2757725674, -65127225.1118219, 73591.9313521937, -11664650591.4191, 35.5267086434461, -596.144543825955, -475.842430145708, 69.6781965359503, 335.674250377312, 25052.6809130882, 146997.380630766, 5.38069315091534E+19, 1.43619827291346E+21, 3.64985866165994E+19, -2547.41561156775, 2.40120197096563E+27, -3.93847464679496E+29, 1.47073407024852E+24, -4.26391250432059E+31, 1.94509340621077E+38, 6.66212132114896E+23, 7.06777016552858E+33, 1.75563621975576E+41, 1.08408607429124E+28, 7.30872705175151E+43, 1.5914584739887E+24, 3.77121605943324E+40];
Sigma = s / 4.4;
eta = h / 2300;
Pi = 0;
for i = 1 : 33
Pi = Pi + ni[i] * (eta - 1.01) ^ Ii[i] * (Sigma - 0.75) ^ Ji[i];
end
p3_hs = Pi * 99;
else
#Subregion 3b
#Eq 2, Table 4, Page 8
Ii = [-12, -12, -12, -12, -12, -10, -10, -10, -10, -8, -8, -6, -6, -6, -6, -5, -4, -4, -4, -3, -3, -3, -3, -2, -2, -1, 0, 2, 2, 5, 6, 8, 10, 14, 14];
Ji = [2, 10, 12, 14, 20, 2, 10, 14, 18, 2, 8, 2, 6, 7, 8, 10, 4, 5, 8, 1, 3, 5, 6, 0, 1, 0, 3, 0, 1, 0, 1, 1, 1, 3, 7];
ni = [1.25244360717979E-13, -1.26599322553713E-02, 5.06878030140626, 31.7847171154202, -391041.161399932, -9.75733406392044E-11, -18.6312419488279, 510.973543414101, 373847.005822362, 2.99804024666572E-08, 20.0544393820342, -4.98030487662829E-06, -10.230180636003, 55.2819126990325, -206.211367510878, -7940.12232324823, 7.82248472028153, -58.6544326902468, 3550.73647696481, -1.15303107290162E-04, -1.75092403171802, 257.98168774816, -727.048374179467, 1.21644822609198E-04, 3.93137871762692E-02, 7.04181005909296E-03, -82.910820069811, -0.26517881813125, 13.7531682453991, -52.2394090753046, 2405.56298941048, -22736.1631268929, 89074.6343932567, -23923456.5822486, 5687958081.29714];
Sigma = s / 5.3;
eta = h / 2800;
Pi = 0;
for i = 1 : 35
Pi = Pi + ni[i] * (eta - 0.681) ^ Ii[i] * (Sigma - 0.792) ^ Ji[i];
end
p3_hs = 16.6 / Pi;
end
p3_hs
end
function h3_pT(p, T)
#Not avalible with if 97
#Solve function T3_ph-T=0 with half interval method.
#ver2.6 Start corrected bug
if p < 22.06395 #Bellow tripple point
Ts = T4_p(p); #Saturation temperature
if T <= Ts #Liquid side
High_Bound = h4L_p(p); #Max h 鋜 liauid h.
Low_Bound = h1_pT(p, 623.15);
else
Low_Bound = h4V_p(p); #Min h 鋜 Vapour h.
High_Bound = h2_pT(p, B23T_p(p));
end
else #Above tripple point. R3 from R2 till R3.
Low_Bound = h1_pT(p, 623.15);
High_Bound = h2_pT(p, B23T_p(p));
end
#ver2.6 End corrected bug
Ts = T+1;
hs=0.0
while abs(T - Ts) > 0.00001
hs = (Low_Bound + High_Bound) / 2;
Ts = T3_ph(p, hs);
if Ts > T
High_Bound = hs;
else
Low_Bound = hs;
end
end
h3_pT = hs;
h3_pT
end
function T3_prho(p, rho)
#Solve by iteration. Observe that fo low temperatures this equation has 2 solutions.
#Solve with half interval method
Low_Bound = 623.15;
High_Bound = 1073.15;
ps=-1000;
Ts=0.0;
while abs(p - ps) > 0.00000001
Ts = (Low_Bound + High_Bound) / 2;
ps = p3_rhoT(rho, Ts);
if ps > p
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T3_prho = Ts;
T3_prho
end
#***********************************************************************************************************
#*2.4 functions for region 4
function p4_T(T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Section 8.1 The Saturation-Pressure Equation
#Eq 30, Page 33
teta = T - 0.23855557567849 / (T - 650.17534844798);
a = teta ^ 2 + 1167.0521452767 * teta - 724213.16703206;
B = -17.073846940092 * teta ^ 2 + 12020.82470247 * teta - 3232555.0322333;
C = 14.91510861353 * teta ^ 2 - 4823.2657361591 * teta + 405113.40542057;
p4_T = (2 * C / (-B + (B ^ 2 - 4 * a * C) ^ 0.5)) ^ 4;
p4_T
end
function T4_p(p)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Section 8.2 The Saturation-Temperature Equation
#Eq 31, Page 34
beta = p ^ 0.25;
E = beta ^ 2 - 17.073846940092 * beta + 14.91510861353;
f = 1167.0521452767 * beta ^ 2 + 12020.82470247 * beta - 4823.2657361591;
G = -724213.16703206 * beta ^ 2 - 3232555.0322333 * beta + 405113.40542057;
D = 2 * G / (-f - (f ^ 2 - 4 * E * G) ^ 0.5);
T4_p = (650.17534844798 + D - ((650.17534844798 + D) ^ 2 - 4 * (-0.23855557567849 + 650.17534844798 * D)) ^ 0.5) / 2;
T4_p
end
function h4_s(s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,Equations as a function of h and s for the Region Boundaries, and an Equation( ) sat , T hs for Region 4 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#4 Equations for Region Boundaries Given Enthalpy and Entropy
# Se picture page 14
if (s > -0.0001545495919 && s <= 3.77828134)==1
#hL1_s
#Eq 3,Table 9,Page 16
Ii = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 7, 8, 12, 12, 14, 14, 16, 20, 20, 22, 24, 28, 32, 32];
Ji = [14, 36, 3, 16, 0, 5, 4, 36, 4, 16, 24, 18, 24, 1, 4, 2, 4, 1, 22, 10, 12, 28, 8, 3, 0, 6, 8];
ni = [0.332171191705237, 6.11217706323496E-04, -8.82092478906822, -0.45562819254325, -2.63483840850452E-05, -22.3949661148062, -4.28398660164013, -0.616679338856916, -14.682303110404, 284.523138727299, -113.398503195444, 1156.71380760859, 395.551267359325, -1.54891257229285, 19.4486637751291, -3.57915139457043, -3.35369414148819, -0.66442679633246, 32332.1885383934, 3317.66744667084, -22350.1257931087, 5739538.75852936, 173.226193407919, -3.63968822121321E-02, 8.34596332878346E-07, 5.03611916682674, 65.5444787064505];
Sigma = s / 3.8;
eta = 0;
for i = 1 : 27
eta = eta + ni[i] * (Sigma - 1.09) ^ Ii[i] * (Sigma + 0.0000366) ^ Ji[i];
end
h4_s = eta * 1700;
elseif (s > 3.77828134 && s <= 4.41202148223476 )==1
#hL3_s
#Eq 4,Table 10,Page 16
Ii = [0, 0, 0, 0, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7, 10, 10, 10, 32, 32];
Ji = [1, 4, 10, 16, 1, 36, 3, 16, 20, 36, 4, 2, 28, 32, 14, 32, 36, 0, 6];
ni = [0.822673364673336, 0.181977213534479, -0.011200026031362, -7.46778287048033E-04, -0.179046263257381, 4.24220110836657E-02, -0.341355823438768, -2.09881740853565, -8.22477343323596, -4.99684082076008, 0.191413958471069, 5.81062241093136E-02, -1655.05498701029, 1588.70443421201, -85.0623535172818, -31771.4386511207, -94589.0406632871, -1.3927384708869E-06, 0.63105253224098];
Sigma = s / 3.8;
eta = 0;
for i = 1 : 19
eta = eta + ni[i] * (Sigma - 1.09) ^ Ii[i] * (Sigma + 0.0000366) ^ Ji[i];
end
h4_s = eta * 1700;
elseif (s > 4.41202148223476 && s <= 5.85 )==1
#Section 4.4 Equations ( ) 2ab " h s and ( ) 2c3b "h s for the Saturated Vapor Line
#Page 19, Eq 5
#hV2c3b_s(s)
Ii = [0, 0, 0, 1, 1, 5, 6, 7, 8, 8, 12, 16, 22, 22, 24, 36];
Ji = [0, 3, 4, 0, 12, 36, 12, 16, 2, 20, 32, 36, 2, 32, 7, 20];
ni = [1.04351280732769, -2.27807912708513, 1.80535256723202, 0.420440834792042, -105721.24483466, 4.36911607493884E+24, -328032702839.753, -6.7868676080427E+15, 7439.57464645363, -3.56896445355761E+19, 1.67590585186801E+31, -3.55028625419105E+37, 396611982166.538, -4.14716268484468E+40, 3.59080103867382E+18, -1.16994334851995E+40];
Sigma = s / 5.9;
eta = 0;
for i = 1 : 16
eta = eta + ni[i] * (Sigma - 1.02) ^ Ii[i] * (Sigma - 0.726) ^ Ji[i];
end
h4_s = eta ^ 4 * 2800;
elseif (s > 5.85 && s < 9.155759395)==1
#Section 4.4 Equations ( ) 2ab " h s and ( ) 2c3b "h s for the Saturated Vapor Line
#Page 20, Eq 6
Ii = [1, 1, 2, 2, 4, 4, 7, 8, 8, 10, 12, 12, 18, 20, 24, 28, 28, 28, 28, 28, 32, 32, 32, 32, 32, 36, 36, 36, 36, 36];
Ji = [8, 24, 4, 32, 1, 2, 7, 5, 12, 1, 0, 7, 10, 12, 32, 8, 12, 20, 22, 24, 2, 7, 12, 14, 24, 10, 12, 20, 22, 28];
ni = [-524.581170928788, -9269472.18142218, -237.385107491666, 21077015581.2776, -23.9494562010986, 221.802480294197, -5104725.33393438, 1249813.96109147, 2000084369.96201, -815.158509791035, -157.612685637523, -11420042233.2791, 6.62364680776872E+15, -2.27622818296144E+18, -1.71048081348406E+31, 6.60788766938091E+15, 1.66320055886021E+22, -2.18003784381501E+29, -7.87276140295618E+29, 1.51062329700346E+31, 7957321.70300541, 1.31957647355347E+15, -3.2509706829914E+23, -4.18600611419248E+25, 2.97478906557467E+34, -9.53588761745473E+19, 1.66957699620939E+24, -1.75407764869978E+32, 3.47581490626396E+34, -7.10971318427851E+38];
Sigma1 = s / 5.21;
Sigma2 = s / 9.2;
eta = 0;
for i = 1 : 30
eta = eta + ni[i] * (1 / Sigma1 - 0.513) ^ Ii[i] * (Sigma2 - 0.524) ^ Ji[i];
end
h4_s = exp(eta) * 2800;
else
h4_s = -99999;
end
h4_s
end
function p4_s(s)
#Uses h4_s and p_hs for the diffrent regions to determine p4_s
h_sat = h4_s(s);
if (s > -0.0001545495919 && s <= 3.77828134)==1
p4_s = p1_hs(h_sat, s);
elseif (s > 3.77828134 && s <= 5.210887663)==1
p4_s = p3_hs(h_sat, s);
elseif (s > 5.210887663 && s < 9.155759395)==1
p4_s = p2_hs(h_sat, s);
else
p4_s = -99999;
end
p4_s
end
function h4L_p(p)
hs=0.0
if (p > 0.000611657 && p < 22.06395)==1
Ts = T4_p(p);
if p < 16.529
h4L_p = h1_pT(p, Ts);
else
#Iterate to find the the backward solution of p3sat_h
Low_Bound = 1670.858218;
High_Bound = 2087.23500164864;
ps=-1000;
while abs(p - ps) > 0.00001
hs = (Low_Bound + High_Bound) / 2;
ps = p3sat_h(hs);
if ps > p
High_Bound = hs;
else
Low_Bound = hs;
end
end
h4L_p = hs;
end
else
h4L_p = -99999;
end
h4L_p
end
function h4V_p(p)
hs=0.0
if p > 0.000611657 && p < 22.06395
Ts = T4_p(p);
if p < 16.529
h4V_p = h2_pT(p, Ts);
else
#Iterate to find the the backward solution of p3sat_h
Low_Bound = 2087.23500164864;
High_Bound = 2563.592004+5;
ps=-1000;
while abs(p - ps) > 0.000001
hs = (Low_Bound + High_Bound) / 2;
ps = p3sat_h(hs);
if ps < p
High_Bound = hs;
else
Low_Bound = hs;
end
end
h4V_p = hs;
end
else
h4V_p = -99999;
end
h4V_p
end
function x4_ph(p, h)
#Calculate vapour fraction from hL and hV for given p
h4v = h4V_p(p);
h4L = h4L_p(p);
if h > h4v
x4_ph = 1;
elseif h < h4L
x4_ph = 0;
else
x4_ph = (h - h4L) / (h4v - h4L);
end
x4_ph
end
function x4_ps(p, s)
if p < 16.529
ssv = s2_pT(p, T4_p(p));
ssL = s1_pT(p, T4_p(p));
else
ssv = s3_rhoT(1 / (v3_ph(p, h4V_p(p))), T4_p(p));
ssL = s3_rhoT(1 / (v3_ph(p, h4L_p(p))), T4_p(p));
end
if s < ssL
x4_ps = 0;
elseif s > ssv
x4_ps = 1;
else
x4_ps = (s - ssL) / (ssv - ssL);
end
x4_ps
end
function T4_hs(h, s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Chapter 5.3 page 30.
#The if 97 function is only valid for part of region4. Use iteration outsida.
Ii = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 8, 10, 10, 12, 14, 14, 16, 16, 18, 18, 18, 20, 28];
Ji = [0, 3, 12, 0, 1, 2, 5, 0, 5, 8, 0, 2, 3, 4, 0, 1, 1, 2, 4, 16, 6, 8, 22, 1, 20, 36, 24, 1, 28, 12, 32, 14, 22, 36, 24, 36];
ni = [0.179882673606601, -0.267507455199603, 1.162767226126, 0.147545428713616, -0.512871635973248, 0.421333567697984, 0.56374952218987, 0.429274443819153, -3.3570455214214, 10.8890916499278, -0.248483390456012, 0.30415322190639, -0.494819763939905, 1.07551674933261, 7.33888415457688E-02, 1.40170545411085E-02, -0.106110975998808, 1.68324361811875E-02, 1.25028363714877, 1013.16840309509, -1.51791558000712, 52.4277865990866, 23049.5545563912, 2.49459806365456E-02, 2107964.67412137, 366836848.613065, -144814105.365163, -1.7927637300359E-03, 4899556021.00459, 471.262212070518, -82929439019.8652, -1715.45662263191, 3557776.82973575, 586062760258.436, -12988763.5078195, 31724744937.1057];
if (s > 5.210887825 && s < 9.15546555571324)==1
Sigma = s / 9.2;
eta = h / 2800;
teta = 0;
for i = 1 : 36
teta = teta + ni[i] * (eta - 0.119) ^ Ii[i] * (Sigma - 1.07) ^ Ji[i];
end
T4_hs = teta * 550;
else
#function psat_h
if (s > -0.0001545495919 && s <= 3.77828134)==1
Low_Bound = 0.000611;
High_Bound = 165.291642526045;
hL=-1000;
while abs(hL - h) > 0.00001 && abs(High_Bound - Low_Bound) > 0.0001
PL = (Low_Bound + High_Bound) / 2;
Ts = T4_p(PL);
hL = h1_pT(PL, Ts);
if hL > h
High_Bound = PL;
else
Low_Bound = PL;
end
end
elseif s > 3.77828134 && s <= 4.41202148223476
PL = p3sat_h(h);
elseif s > 4.41202148223476 && s <= 5.210887663
PL = p3sat_h(h);
end
Low_Bound = 0.000611;
High_Bound = PL;
sss=-1000;
p=0.0
while (abs(s - sss) > 0.000001 && abs(High_Bound - Low_Bound) > 0.0000001)==1
p = (Low_Bound + High_Bound) / 2;
#Calculate s4_ph
Ts = T4_p(p);
xs = x4_ph(p, h);
if p < 16.529
s4v = s2_pT(p, Ts);
s4L = s1_pT(p, Ts);
else
v4v = v3_ph(p, h4V_p(p));
s4v = s3_rhoT(1 / v4v, Ts);
v4L = v3_ph(p, h4L_p(p));
s4L = s3_rhoT(1 / v4L, Ts);
end
sss = (xs * s4v + (1 - xs) * s4L);
if sss < s
High_Bound = p;
else
Low_Bound = p;
end
end
T4_hs = T4_p(p);
end
T4_hs
end
#***********************************************************************************************************
#*2.5 functions for region 5
function h5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tau = 0;
for i = 1 : 6
gamma0_tau = gamma0_tau + ni0[i] * Ji0[i] * tau ^ (Ji0[i] - 1);
end
gammar_tau = 0;
for i = 1 : 5
gammar_tau = gammar_tau + nir[i] * Pi ^ Iir[i] * Jir[i] * tau ^ (Jir[i] - 1);
end
h5_pT = R * T * tau * (gamma0_tau + gammar_tau);
h5_pT
end
function v5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_pi = 1 / Pi;
gammar_pi = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
end
v5_pT = R * T / p * Pi * (gamma0_pi + gammar_pi) / 1000;
v5_pT
end
function u5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_pi = 1 / Pi;
gamma0_tau = 0;
for i = 1 : 6
gamma0_tau = gamma0_tau + ni0[i] * Ji0[i] * tau ^ (Ji0[i] - 1);
end
gammar_pi = 0;
gammar_tau = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
gammar_tau = gammar_tau + nir[i] * Pi ^ Iir[i] * Jir[i] * tau ^ (Jir[i] - 1);
end
u5_pT = R * T * (tau * (gamma0_tau + gammar_tau) - Pi * (gamma0_pi + gammar_pi));
u5_pT
end
function Cp5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tautau = 0;
for i = 1 : 6
gamma0_tautau = gamma0_tautau + ni0[i] * Ji0[i] * (Ji0[i] - 1) * tau ^ (Ji0[i] - 2);
end
gammar_tautau = 0;
for i = 1 : 5
gammar_tautau = gammar_tautau + nir[i] * Pi ^ Iir[i] * Jir[i] * (Jir[i] - 1) * tau ^ (Jir[i] - 2);
end
Cp5_pT = -R * tau ^ 2 * (gamma0_tautau + gammar_tautau);
Cp5_pT
end
function s5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0 = log(Pi);
gamma0_tau = 0;
for i = 1 : 6
gamma0_tau = gamma0_tau + ni0[i] * Ji0[i] * tau ^ (Ji0[i] - 1);
gamma0 = gamma0 + ni0[i] * tau ^ Ji0[i];
end
gammar = 0;
gammar_tau = 0;
for i = 1 : 5
gammar = gammar + nir[i] * Pi ^ Iir[i] * tau ^ Jir[i];
gammar_tau = gammar_tau + nir[i] * Pi ^ Iir[i] * Jir[i] * tau ^ (Jir[i] - 1);
end
s5_pT = R * (tau * (gamma0_tau + gammar_tau) - (gamma0 + gammar));
s5_pT
end
function Cv5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tautau = 0;
for i = 1 : 6
gamma0_tautau = gamma0_tautau + ni0[i] * (Ji0[i] - 1) * Ji0[i] * tau ^ (Ji0[i] - 2);
end
gammar_pi = 0;
gammar_pitau = 0;
gammar_pipi = 0;
gammar_tautau = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
gammar_pitau = gammar_pitau + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * Jir[i] * tau ^ (Jir[i] - 1);
gammar_pipi = gammar_pipi + nir[i] * Iir[i] * (Iir[i] - 1) * Pi ^ (Iir[i] - 2) * tau ^ Jir[i];
gammar_tautau = gammar_tautau + nir[i] * Pi ^ Iir[i] * Jir[i] * (Jir[i] - 1) * tau ^ (Jir[i] - 2);
end
Cv5_pT = R * (-(tau ^ 2 *(gamma0_tautau + gammar_tautau)) - (1 + Pi * gammar_pi - tau * Pi * gammar_pitau)^2 / (1 - Pi ^ 2 * gammar_pipi));
Cv5_pT
end
function w5_pT(p, T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam, September 1997
#Basic Equation for Region 5
#Eq 32,33, Page 36, Tables 37-41
Ji0 = [0, 1, -3, -2, -1, 2];
ni0 = [-13.179983674201, 6.8540841634434, -0.024805148933466, 0.36901534980333, -3.1161318213925, -0.32961626538917];
Iir = [1, 1, 1, 2, 3];
Jir = [0, 1, 3, 9, 3];
nir = [-1.2563183589592E-04, 2.1774678714571E-03, -0.004594282089991, -3.9724828359569E-06, 1.2919228289784E-07];
R = 0.461526; #kJ/(kg K)
tau = 1000 / T;
Pi = p;
gamma0_tautau = 0;
for i = 1 : 6
gamma0_tautau = gamma0_tautau + ni0[i] * (Ji0[i] - 1) * Ji0[i] * tau ^ (Ji0[i] - 2);
end
gammar_pi = 0;
gammar_pitau = 0;
gammar_pipi = 0;
gammar_tautau = 0;
for i = 1 : 5
gammar_pi = gammar_pi + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * tau ^ Jir[i];
gammar_pitau = gammar_pitau + nir[i] * Iir[i] * Pi ^ (Iir[i] - 1) * Jir[i] * tau ^ (Jir[i] - 1);
gammar_pipi = gammar_pipi + nir[i] * Iir[i] * (Iir[i] - 1) * Pi ^ (Iir[i] - 2) * tau ^ Jir[i];
gammar_tautau = gammar_tautau + nir[i] * Pi ^ Iir[i] * Jir[i] * (Jir[i] - 1) * tau ^ (Jir[i] - 2);
end
w5_pT = (1000 * R * T * (1 + 2 * Pi * gammar_pi + Pi ^ 2 * gammar_pi ^ 2) / ((1 - Pi ^ 2 * gammar_pipi) + (1 + Pi * gammar_pi - tau * Pi * gammar_pitau) ^ 2 / (tau ^ 2 * (gamma0_tautau + gammar_tautau)))) ^ 0.5;
w5_pT
end
function T5_ph(p, h)
#Solve with half interval method
Low_Bound = 1073.15;
High_Bound = 2273.15;
hs=h-1;
Ts=0.0
while abs(h - hs) > 0.00001
Ts = (Low_Bound + High_Bound) / 2;
hs = h5_pT(p, Ts);
if hs > h
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T5_ph = Ts;
T5_ph
end
function T5_ps(p, s)
#Solve with half interval method
Low_Bound = 1073.15;
High_Bound = 2273.15;
ss=s-1;
Ts=0.0
while abs(s - ss) > 0.00001
Ts = (Low_Bound + High_Bound) / 2;
ss = s5_pT(p, Ts);
if ss > s
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T5_ps = Ts;
T5_ps
end
function T5_prho(p,rho)
#Solve by iteration. Observe that fo low temperatures this equation has 2 solutions.
#Solve with half interval method
Ts=0.0
Low_Bound = 1073.15;
High_Bound = 2073.15;
rhos=-1000;
while abs(rho - rhos) > 0.000001
Ts = (Low_Bound + High_Bound) / 2;
rhos = 1 / v2_pT(p, Ts);
if rhos < rho
High_Bound = Ts;
else
Low_Bound = Ts;
end
end
T5_prho = Ts;
T5_prho
end
#***********************************************************************************************************
#*3 Region Selection
#***********************************************************************************************************
#*3.1 Regions as a function of pT
function region_pT(p, T)
if T > 1073.15 && p < 10 && T < 2273.15 && p > 0.000611
region_pT = 5;
elseif T <= 1073.15 && T > 273.15 && p <= 100 && p > 0.000611
if T > 623.15
if p > B23p_T(T)
region_pT = 3;
if T < 647.096
ps = p4_T(T);
if abs(p - ps) < 0.00001
region_pT = 4;
end
end
else
region_pT = 2;
end
else
ps = p4_T(T);
if abs(p - ps) < 0.00001
region_pT = 4;
elseif p > ps
region_pT = 1;
else
region_pT = 2;
end
end
else
region_pT = 0; #**Error, Outside valid area
end
region_pT
end
#***********************************************************************************************************
#*3.2 Regions as a function of ph
function region_ph( p, h)
#Check if outside pressure limits
if p < 0.000611657 || p > 100
region_ph = 0;
return region_ph
end
#Check if outside low h.
if h < 0.963 * p + 2.2 #Linear adaption to h1_pt()+2 to speed up calcualations.
if h < h1_pT(p, 273.15)
region_ph = 0;
return region_ph
end
end
if p < 16.5292 #Bellow region 3,Check region 1,4,2,5
#Check Region 1
Ts = T4_p(p);
hL = 109.6635 * log(p) + 40.3481 * p + 734.58; #Approximate function for hL_p
if abs(h - hL) < 100 #if approximate is not god enough use real function
hL = h1_pT(p, Ts);
end
if h <= hL
region_ph = 1;
return region_ph
end
#Check Region 4
hV = 45.1768 * log(p) - 20.158 * p + 2804.4; #Approximate function for hV_p
if abs(h - hV) < 50 #if approximate is not god enough use real function
hV = h2_pT(p, Ts);
end
if h < hV
region_ph = 4;
return region_ph
end
#Check upper limit of region 2 Quick Test
if h < 4000
region_ph = 2;
return region_ph
end
#Check region 2 (Real value)
h_45 = h2_pT(p, 1073.15);
if h <= h_45
region_ph = 2;
return region_ph
end
#Check region 5
if p > 10
region_ph = 0;
return region_ph
end
h_5u = h5_pT(p, 2273.15);
if h < h_5u
region_ph = 5;
return region_ph
end
region_ph = 0;
return
else #for p>16.5292
#Check if in region1
if h < h1_pT(p, 623.15)
region_ph = 1;
return region_ph
end
#Check if in region 3 or 4 (Bellow Reg 2)
if h < h2_pT(p, B23T_p(p))
#Region 3 or 4
if p > p3sat_h(h)
region_ph = 3;
return region_ph
else
region_ph = 4;
return region_ph
end
end
#Check if region 2
if h < h2_pT(p, 1073.15)
region_ph = 2;
return region_ph
end
end
region_ph = 0;
region_ph
end
#***********************************************************************************************************
#*3.3 Regions as a function of ps
function region_ps( p, s)
if p < 0.000611657 || p > 100 || s < 0 || s > s5_pT(p, 2273.15)
region_ps = 0;
return region_ps
end
#Check region 5
if s > s2_pT(p, 1073.15)
if p <= 10
region_ps = 5;
return region_ps
else
region_ps = 0;
return region_ps
end
end
#Check region 2
if p > 16.529
ss = s2_pT(p, B23T_p(p)); #Between 5.047 & 5.261. Use to speed up!
else
ss = s2_pT(p, T4_p(p));
end
if s > ss
region_ps = 2;
return region_ps
end
#Check region 3
ss = s1_pT(p, 623.15);
if p > 16.529 && s > ss
if p > p3sat_s(s)
region_ps = 3;
return region_ps
else
region_ps = 4;
return region_ps
end
end
#Check region 4 (Not inside region 3)
if p < 16.529 && s > s1_pT(p, T4_p(p))
region_ps = 4;
return region_ps
end
#Check region 1
if p > 0.000611657 && s > s1_pT(p, 273.15)
region_ps = 1;
return region_ps
end
region_ps = 1;
region_ps
end
#***********************************************************************************************************
#*3.4 Regions as a function of hs
function region_hs( h, s)
if s < -0.0001545495919
region_hs = 0;
return region_hs
end
#Check linear adaption to p=0.000611. if bellow region 4.
hMin = (((-0.0415878 - 2500.89262) / (-0.00015455 - 9.155759)) * s);
if s < 9.155759395 && h < hMin
region_hs = 0;
return region_hs
end
#******Kolla 1 eller 4. (+liten bit 鰒er B13)
if s >= -0.0001545495919 && s <= 3.77828134
if h < h4_s(s)
region_hs = 4;
return region_hs
elseif s < 3.397782955 #100MPa line is limiting
TMax = T1_ps(100, s);
hMax = h1_pT(100, TMax);
if h < hMax
region_hs = 1;
return region_hs
else
region_hs = 0;
return region_hs
end
else #The point is either in region 4,1,3. Check B23
hB = hB13_s(s);
if h < hB
region_hs = 1;
return region_hs
end
TMax = T3_ps(100, s);
vmax = v3_ps(100, s);
hMax = h3_rhoT(1 / vmax, TMax);
if h < hMax
region_hs = 3;
return region_hs
else
region_hs = 0;
return region_hs
end
end
end
#******Kolla region 2 eller 4. (講re delen av omr錮e b23-> max)
if s >= 5.260578707 && s <= 11.9212156897728
if s > 9.155759395 #Above region 4
Tmin = T2_ps(0.000611, s);
hMin = h2_pT(0.000611, Tmin);
#function adapted to h(1073.15,s)
hMax = -0.07554022 * s ^ 4 + 3.341571 * s ^ 3 - 55.42151 * s ^ 2 + 408.515 * s + 3031.338;
if h > hMin && h < hMax
region_hs = 2;
return region_hs
else
region_hs = 0;
return region_hs
end
end
hV = h4_s(s);
if h < hV #Region 4. Under region 3.
region_hs = 4;
return region_hs
end
if s < 6.04048367171238
TMax = T2_ps(100., s);
hMax = h2_pT(100., TMax);
else
#function adapted to h(1073.15,s)
hMax = -2.988734 * s ^ 4 + 121.4015 * s ^ 3 - 1805.15 * s ^ 2 + 11720.16 * s - 23998.33;
end
if h < hMax #Region 2. 講er region 4.
region_hs = 2;
return region_hs
else
region_hs = 0;
return region_hs
end
end
#Kolla region 3 eller 4. Under kritiska punkten.
if s >= 3.77828134 && s <= 4.41202148223476
hL = h4_s(s);
if h < hL
region_hs = 4;
return region_hs
end
TMax = T3_ps(100, s);
vmax = v3_ps(100, s);
hMax = h3_rhoT(1 / vmax, TMax);
if h < hMax
region_hs = 3;
return region_hs
else
region_hs = 0;
return region_hs
end
end
#Kolla region 3 eller 4 fr錸 kritiska punkten till 鰒re delen av b23
if s >= 4.41202148223476 && s <= 5.260578707
hV = h4_s(s);
if h < hV
region_hs = 4;
return region_hs
end
#Kolla om vi 鋜 under b23 giltighetsomr錮e.
if s <= 5.048096828
TMax = T3_ps(100, s);
vmax = v3_ps(100, s);
hMax = h3_rhoT(1 / vmax, TMax);
if h < hMax
region_hs = 3;
return region_hs
else
region_hs = 0;
return region_hs
end
else #Inom omr錮et f鰎 B23 i s led.
if (h > 2812.942061) #Ovanf鰎 B23 i h_led
if s > 5.09796573397125
TMax = T2_ps(100, s);
hMax = h2_pT(100, TMax);
if h < hMax
region_hs = 2;
return region_hs
else
region_hs = 0;
return region_hs
end
else
region_hs = 0;
return region_hs
end
end
if (h < 2563.592004) #Nedanf鰎 B23 i h_led men vi har redan kollat ovanf鰎 hV2c3b
region_hs = 3;
return region_hs
end
#Vi 鋜 inom b23 omr錮et i b錮e s och h led.
Tact = TB23_hs(h, s);
pact = p2_hs(h, s);
pBound = B23p_T(Tact);
if pact > pBound
region_hs = 3;
return region_hs
else
region_hs = 2;
return region_hs
end
end
end
region_hs = 0;
region_hs
end
#***********************************************************************************************************
#*3.5 Regions as a function of p and rho
function Region_prho(p,rho)
v = 1 / rho;
if p < 0.000611657 || p > 100
Region_prho = 0;
return
end
if p < 16.5292 #Bellow region 3, Check region 1,4,2
if v < v1_pT(p, 273.15) #Observe that this is not actually min of v. Not valid Water of 4癈 is ligther.
Region_prho = 0;
return Region_prho
end
if v <= v1_pT(p, T4_p(p))
Region_prho = 1;
return Region_prho
end
if v < v2_pT(p, T4_p(p))
Region_prho = 4;
return Region_prho
end
if v <= v2_pT(p, 1073.15)
Region_prho = 2;
return Region_prho
end
if p > 10 #Above region 5
Region_prho = 0;
return Region_prho
end
if v <= v5_pT(p, 2073.15)
Region_prho = 5;
return Region_prho
end
else #Check region 1,3,4,3,2 (Above the lowest point of region 3.)
if v < v1_pT(p, 273.15) #Observe that this is not actually min of v. Not valid Water of 4癈 is ligther.
Region_prho = 0;
return Region_prho
end
if v < v1_pT(p, 623.15)
Region_prho = 1;
return Region_prho
end
#Check if in region 3 or 4 (Bellow Reg 2)
if v < v2_pT(p, B23T_p(p))
#Region 3 or 4
if p > 22.064 #Above region 4
Region_prho = 3;
return Region_prho
end
if v < v3_ph(p, h4L_p(p)) || v > v3_ph(p, h4V_p(p)) #Uses iteration!!
Region_prho = 3;
return Region_prho
else
Region_prho = 4;
return Region_prho
end
end
#Check if region 2
if v < v2_pT(p, 1073.15)
Region_prho = 2;
return Region_prho
end
end
Region_prho = 0;
Region_prho
end
#***********************************************************************************************************
#*4 Region Borders
#***********************************************************************************************************
#***********************************************************************************************************
#*4.1 Boundary between region 2 and 3.
function B23p_T(T)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#1997
#Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3
#Eq 5, Page 5
B23p_T = 348.05185628969 - 1.1671859879975 * T + 1.0192970039326E-03 * T ^ 2;
B23p_T
end
function B23T_p(p)
#Release on the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water and Steam
#1997
#Section 4 Auxiliary Equation for the Boundary between Regions 2 and 3
#Eq 6, Page 6
B23T_p = 572.54459862746 + ((p - 13.91883977887) / 1.0192970039326E-03) ^ 0.5;
B23T_p
end
#***********************************************************************************************************
#*4.2 Region 3. pSat_h & pSat_s
function p3sat_h(h)
#Revised Supplementary Release on Backward Equations for the functions T(p,h), v(p,h) & T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997 for the Thermodynamic Properties of Water & Steam
#2004
#Section 4 Boundary Equations psat(h) & psat(s) for the Saturation Lines of Region 3
#Se pictures Page 17, Eq 10, Table 17, Page 18
Ii = [0, 1, 1, 1, 1, 5, 7, 8, 14, 20, 22, 24, 28, 36];
Ji = [0, 1, 3, 4, 36, 3, 0, 24, 16, 16, 3, 18, 8, 24];
ni = [0.600073641753024, -9.36203654849857, 24.6590798594147, -107.014222858224, -91582131580576.8, -8623.32011700662, -23.5837344740032, 2.52304969384128E+17, -3.89718771997719E+18, -3.33775713645296E+22, 35649946963.6328, -1.48547544720641E+26, 3.30611514838798E+18, 8.13641294467829E+37];
hs = h / 2600;
ps = 0;
for i = 1:14
ps = ps + ni[i] * (hs - 1.02) ^ Ii[i] * (hs - 0.608) ^ Ji[i];
end
p3sat_h = ps * 22;
p3sat_h
end
function p3sat_s(s)
Ii = [0, 1, 1, 4, 12, 12, 16, 24, 28, 32];
Ji = [0, 1, 32, 7, 4, 14, 36, 10, 0, 18];
ni = [0.639767553612785, -12.9727445396014, -2.24595125848403E+15, 1774667.41801846, 7170793495.71538, -3.78829107169011E+17, -9.55586736431328E+34, 1.87269814676188E+23, 119254746466.473, 1.10649277244882E+36];
Sigma = s / 5.2;
Pi = 0;
for i = 1:10
Pi = Pi + ni[i] * (Sigma - 1.03) ^ Ii[i] * (Sigma - 0.699) ^ Ji[i];
end
p3sat_s = Pi * 22;
p3sat_s
end
#***********************************************************************************************************
#4.3 Region boundary 1to3 & 3to2 as a functions of s
function hB13_s(s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Chapter 4.5 page 23.
Ii = [0, 1, 1, 3, 5, 6];
Ji = [0, -2, 2, -12, -4, -3];
ni = [0.913965547600543, -4.30944856041991E-05, 60.3235694765419, 1.17518273082168E-18, 0.220000904781292, -69.0815545851641];
Sigma = s / 3.8;
eta = 0;
for i = 1 : 6
eta = eta + ni[i] * (Sigma - 0.884) ^ Ii[i] * (Sigma - 0.864) ^ Ji[i];
end
hB13_s = eta * 1700;
hB13_s
end
function TB23_hs(h, s)
#Supplementary Release on Backward Equations ( ) , p h s for Region 3,
#Chapter 4.6 page 25.
Ii = [-12, -10, -8, -4, -3, -2, -2, -2, -2, 0, 1, 1, 1, 3, 3, 5, 6, 6, 8, 8, 8, 12, 12, 14, 14];
Ji = [10, 8, 3, 4, 3, -6, 2, 3, 4, 0, -3, -2, 10, -2, -1, -5, -6, -3, -8, -2, -1, -12, -1, -12, 1];
ni = [6.2909626082981E-04, -8.23453502583165E-04, 5.15446951519474E-08, -1.17565945784945, 3.48519684726192, -5.07837382408313E-12, -2.84637670005479, -2.36092263939673, 6.01492324973779, 1.48039650824546, 3.60075182221907E-04, -1.26700045009952E-02, -1221843.32521413, 0.149276502463272, 0.698733471798484, -2.52207040114321E-02, 1.47151930985213E-02, -1.08618917681849, -9.36875039816322E-04, 81.9877897570217, -182.041861521835, 2.61907376402688E-06, -29162.6417025961, 1.40660774926165E-05, 7832370.62349385];
Sigma = s / 5.3;
eta = h / 3000;
teta = 0;
for i = 1 : 25
teta = teta + ni[i] * (eta - 0.727) ^ Ii[i] * (Sigma - 0.864) ^ Ji[i];
end
TB23_hs = teta * 900;
TB23_hs
end
#***********************************************************************************************************
#*5 Transport properties
#***********************************************************************************************************
#*5.1 Viscosity (IAPWS formulation 1985, Revised 2003)
#***********************************************************************************************************
function my_AllRegions_pT( p, T)
h0 = [0.5132047, 0.3205656, 0, 0, -0.7782567, 0.1885447];
h1 = [0.2151778, 0.7317883, 1.241044, 1.476783, 0, 0];
h2 = [-0.2818107, -1.070786, -1.263184, 0, 0, 0];
h3 = [0.1778064, 0.460504, 0.2340379, -0.4924179, 0, 0];
h4 = [-0.0417661, 0, 0, 0.1600435, 0, 0];
h5 = [0, -0.01578386, 0, 0, 0, 0];
h6 = [0, 0, 0, -0.003629481, 0, 0];
#Calcualte density.
region=region_pT(p,T)
if region ==1
rho = 1 / v1_pT(p, T);
elseif region == 2
rho = 1 / v2_pT(p, T);
elseif region == 3
hs = h3_pT(p, T);
rho = 1 / v3_ph(p, hs);
elseif region == 4
rho = NaN;
elseif region == 5
rho = 1 / v5_pT(p, T);
else
my_AllRegions_pT = NaN;
return my_AllRegions_pT
end
rhos = rho / 317.763;
Ts = T / 647.226;
ps = p / 22.115;
#Check valid area
if T > 900 + 273.15 || (T > 600 + 273.15 && p > 300) || (T > 150 + 273.15 && p > 350) || p > 500
my_AllRegions_pT = NaN;
return my_AllRegions_pT
end
my0 = Ts ^ 0.5 / (1 + 0.978197 / Ts + 0.579829 / (Ts ^ 2) - 0.202354 / (Ts ^ 3));
Sum = 0;
for i = 0 : 5
Sum = Sum + h0[i+1] * (1 / Ts - 1) ^ i + h1[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 1 + h2[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 2 + h3[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 3 + h4[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 4 + h5[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 5 + h6[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 6;
end
my1 = exp(rhos * Sum);
mys = my0 * my1;
my_AllRegions_pT = mys * 0.000055071;
my_AllRegions_pT
end
function my_AllRegions_ph(p,h)
h0 = [0.5132047, 0.3205656, 0, 0, -0.7782567, 0.1885447];
h1 = [0.2151778, 0.7317883, 1.241044, 1.476783, 0, 0];
h2 = [-0.2818107, -1.070786, -1.263184, 0, 0, 0];
h3 = [0.1778064, 0.460504, 0.2340379, -0.4924179, 0, 0];
h4 = [-0.0417661, 0, 0, 0.1600435, 0, 0];
h5 = [0, -0.01578386, 0, 0, 0, 0];
h6 = [0, 0, 0, -0.003629481, 0, 0];
#Calcualte density.
region = region_ph(p, h)
if region == 1
Ts = T1_ph(p, h);
T = Ts;
rho = 1 / v1_pT(p, Ts);
elseif region == 2
Ts = T2_ph(p, h);
T = Ts;
rho = 1 / v2_pT(p, Ts);
elseif region == 3
rho = 1 / v3_ph(p, h);
T = T3_ph(p, h);
elseif region == 4
xs = x4_ph(p, h);
if p < 16.529
v4v = v2_pT(p, T4_p(p));
v4L = v1_pT(p, T4_p(p));
else
v4v = v3_ph(p, h4V_p(p));
v4L = v3_ph(p, h4L_p(p));
end
rho = 1 / (xs * v4v + (1 - xs) * v4L);
T = T4_p(p);
elseif region == 5
Ts = T5_ph(p, h);
T = Ts;
rho = 1 / v5_pT(p, Ts);
else
my_AllRegions_ph = NaN;
return my_AllRegions_ph
end
rhos = rho / 317.763;
Ts = T / 647.226;
ps = p / 22.115;
#Check valid area
if T > 900 + 273.15 || (T > 600 + 273.15 && p > 300) || (T > 150 + 273.15 && p > 350) || p > 500
my_AllRegions_ph = NaN;
return my_AllRegions_ph
end
my0 = Ts ^ 0.5 / (1 + 0.978197 / Ts + 0.579829 / (Ts ^ 2) - 0.202354 / (Ts ^ 3));
Sum = 0;
for i = 0 : 5
Sum = Sum + h0[i+1] * (1 / Ts - 1) ^ i + h1[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 1 + h2[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 2 + h3[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 3 + h4[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 4 + h5[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 5 + h6[i+1] * (1 / Ts - 1) ^ i * (rhos - 1) ^ 6;
end
my1 = exp(rhos * Sum);
mys = my0 * my1;
my_AllRegions_ph = mys * 0.000055071;
my_AllRegions_ph
end
#***********************************************************************************************************
#*5.2 Thermal Conductivity (IAPWS formulation 1985)
function tc_ptrho( p, T, rho)
#Revised release on the IAPWS formulation 1985 for the Thermal Conductivity of ordinary water
#IAPWS September 1998
#Page 8
#ver2.6 Start corrected bug
if T < 273.15
tc_ptrho = NaN; #Out of range of validity (para. B4)
return
elseif T < 500 + 273.15
if p > 100
tc_ptrho = NaN; #Out of range of validity (para. B4)
return tc_ptrho
end
elseif T <= 650 + 273.15
if p > 70
tc_ptrho = NaN; #Out of range of validity (para. B4)
return tc_ptrho
end
else T <= 800 + 273.15
if p > 40
tc_ptrho = NaN; #Out of range of validity (para. B4)
return tc_ptrho
end
end
#ver2.6 End corrected bug
T = T / 647.26;
rho = rho / 317.7;
tc0 = T ^ 0.5 * (0.0102811 + 0.0299621 * T + 0.0156146 * T ^ 2 - 0.00422464 * T ^ 3);
tc1 = -0.39707 + 0.400302 * rho + 1.06 * exp(-0.171587 * (rho + 2.39219) ^ 2);
dT = abs(T - 1) + 0.00308976;
Q = 2 + 0.0822994 / dT ^ (3 / 5);
if T >= 1
s = 1 / dT;
else
s = 10.0932 / dT ^ (3 / 5);
end
tc2 = (0.0701309 / T ^ 10 + 0.011852) * rho ^ (9 / 5) * exp(0.642857 * (1 - rho ^ (14 / 5))) + 0.00169937 * s * rho ^ Q * exp((Q / (1 + Q)) * (1 - rho ^ (1 + Q))) - 1.02 * exp(-4.11717 * T ^ (3 / 2) - 6.17937 / rho ^ 5);
tc_ptrho = tc0 + tc1 + tc2;
tc_ptrho
end
#***********************************************************************************************************
#5.3 Surface Tension
function Surface_Tension_T(T)
#IAPWS Release on Surface Tension of Ordinary Water Substance,
#September 1994
tc = 647.096; #K
B = 0.2358; #N/m
bb = -0.625;
my = 1.256;
if T < 0.01 || T > tc
Surface_Tension_T = NaN; #"Out of valid region"
return Surface_Tension_T
end
tau = 1 - T / tc;
Surface_Tension_T = B * tau ^ my * (1 + bb * tau);
Surface_Tension_T
end
#***********************************************************************************************************
#*6 Units *
#***********************************************************************************************************
function toSIunit_p( Ins )
#Translate bar to MPa
toSIunit_p = uconvert(u"MPa", Ins);
ustrip(toSIunit_p)
end
function fromSIunit_p( Ins )
#Translate bar to MPa
Ins*u"MPa"
end
function toSIunit_T( Ins )
#Translate degC to Kelvon
toSIunit_T = uconvert(u"K", Ins)
ustrip(toSIunit_T)
end
function fromSIunit_T( Ins )
#Translate Kelvin to degC
uconvert(u"°C",Ins*K);
end
function toSIunit_h( Ins )
utrip(uconvert(u"kJ/kg", Ins))
end
function fromSIunit_h( Ins )
Ins*u"kJ/kg"
end
function toSIunit_v( Ins )
ustrip(uconvert(u"m^3/kg", Ins))
end
function fromSIunit_v( Ins )
Ins*u"m^3/kg"
end
function toSIunit_s( Ins )
ustrip(uconvert(u"kJ/(kg*K)", Ins))
end
function fromSIunit_s( Ins )
Ins * u"kJ / (kg * K)"
end
function toSIunit_u( Ins )
ustrip(uconvert(u"kJ/kg", Ins))
end
function fromSIunit_u( Ins )
Ins * u"kJ/kg"
end
function toSIunit_Cp( Ins )
ustrip(uconvert(u"kJ/(kg*K)", Ins))
end
function fromSIunit_Cp( Ins )
Ins * u"kJ/(kg*K)"
end
function toSIunit_Cv( Ins )
ustrip(uconvert(u"kJ/(kg*K)", Ins))
end
function fromSIunit_Cv( Ins )
Ins * u"kJ/(kg*K)"
end
function toSIunit_w( Ins )
ustrip(uconvert(u"m/s", Ins))
end
function fromSIunit_w( Ins )
Ins * u"m/s"
end
function toSIunit_tc( Ins )
ustrip(uconvert(u"W/(m*K)",Ins))
end
function fromSIunit_tc( Ins )
Ins * u"W/(m*K)"
end
function toSIunit_st( Ins )
ustrip(uconvert(u"N/m", Ins))
end
function fromSIunit_st( Ins )
Ins * u"N/m"
end
function toSIunit_x( Ins )
toSIunit_x = Ins;
toSIunit_x
end
function fromSIunit_x( Ins )
fromSIunit_x = Ins;
fromSIunit_x
end
function toSIunit_vx( Ins )
toSIunit_vx = Ins;
toSIunit_vx
end
function fromSIunit_vx( Ins )
fromSIunit_vx = Ins;
fromSIunit_vx
end
function toSIunit_my( Ins )
ustrip(uconvert(u"Pa*s", Ins))
end
function fromSIunit_my( Ins )
Ins * u"Pa * s"
end
#***********************************************************************************************************
#*7 Verification *
#***********************************************************************************************************
function check()
err=0;
#*********************************************************************************************************
#* 7.1 Verifiy region 1
#IF-97 Table 5, Page 9
p=[30/10,800/10,30/10];
T=[300,300,500];
Fun=[:v1_pT,:h1_pT,:u1_pT,:s1_pT,:Cp1_pT,:w1_pT];
IF97=[0.00100215168 0.000971180894 0.001202418;
115.331273 184.142828 975.542239;
112.324818 106.448356 971.934985;
0.392294792 0.368563852 2.58041912;
4.17301218 4.01008987 4.65580682;
1507.73921 1634.69054 1240.71337];
R1=zeros(6,3);
for i=1:3
for j=1:6
ex=:($(Fun(j))(p[$i],T[$i]))
R1[j,i]=eval(ex);
end
end
Region1_error=abs((R1-IF97)./IF97)
err=err+sum(sum(Region1_error>1E-8))
#IF-97 Table 7, Page 11
p=[30/10,800/10,800/10];
h=[500,500,1500];
IF97=[391.798509,378.108626,611.041229];
R1=zeros(1,3);
for i=1:3
R1[i]=T1_ph(p[i],h[i]);
end
T1_ph_error=abs((R1-IF97)./IF97)
err=err+sum(sum(T1_ph_error>1E-8))
#IF-97 Table 9, Page 12
p=[30/10,800/10,800/10];
s=[0.5,0.5,3];
IF97=[307.842258,309.979785,565.899909];
R1=zeros(1,3);
for i=1:3
R1[i]=T1_ps(p[i],s[i]);
end
T1_ps_error=abs((R1-IF97)./IF97)
err=err+sum(sum(T1_ps_error>1E-8))
#Supplementary Release on Backward Equations
#for Pressure as a Function of Enthalpy and Entropy p(h,s)
#Table 3, Page 6
h=[0.001,90,1500];
s=[0,0,3.4];
IF97=[0.0009800980612,91.929547272,58.68294423];
R1=zeros(1,3);
for i=1:3
R1[i]=p1_hs(h[i],s[i]);
end
p1_hs_error=abs((R1-IF97)./IF97)
err=err+sum(sum(p1_hs_error>1E-8))
#*********************************************************************************************************
#* 7.2 Verifiy region 2
# IF-97 Table 15, Page 17
p=[0.035/10,0.035/10,300/10];
T=[300,700,700];
Fun=[:v2_pT,:h2_pT,:u2_pT,:s2_pT,:Cp2_pT,:w2_pT];
IF97=[39.4913866 92.3015898 0.00542946619;
2549.91145 3335.68375 2631.49474;
2411.6916 3012.62819 2468.61076;
8.52238967 10.1749996 5.17540298;
1.91300162 2.08141274 10.3505092;
427.920172 644.289068 480.386523];
R2=zeros(6,3);
for i=1:3
for j=1:6
ex=:($(Fun(i))(p[$i],T[$i]))
R2[j,i]=eval(ex);
end
end
Region2_error=abs((R2-IF97)./IF97)
err=err+sum(sum(Region2_error>1E-8))
#IF-97 Table 24, Page 25
p=[0.01/10,30/10,30/10,50/10,50/10,250/10,400/10,600/10,600/10];
h=[3000,3000,4000,3500,4000,3500,2700,2700,3200];
IF97=[534.433241,575.37337,1010.77577,801.299102,1015.31583,875.279054,743.056411,791.137067,882.75686];
R2=zeros(1,9);
for i=1:9
R2[i]=T2_ph(p[i],h[i]);
end
T2_ph_error=abs((R2-IF97)./IF97)
err=err+sum(sum(T2_ph_error>1E-8))
#IF-97 Table 29, Page 29
p=[1/10,1/10,25/10,80/10,80/10,900/10,200/10,800/10,800/10];
s=[7.5,8,8,6,7.5,6,5.75,5.25,5.75];
IF97=[399.517097,514.127081,1039.84917,600.48404,1064.95556,1038.01126,697.992849,854.011484,949.017998];
R2=zeros(1,9);
for i=1:9
R2[i]=T2_ps(p[i],s[i]);
end
T2_ps_error=abs((R2-IF97)./IF97)
err=err+sum(sum(T2_ps_error>1E-8))
#Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s)
#Table 3, Page 6
h=[2800,2800,4100,2800,3600,3600,2800,2800,3400];
s=[6.5,9.5,9.5,6,6,7,5.1,5.8,5.8];
IF97=[1.371012767,0.001879743844,0.1024788997,4.793911442,83.95519209,7.527161441,94.3920206,8.414574124,83.76903879];
R2=zeros(1,9);
for i=1:9
R2[i]=p2_hs(h[i],s[i]);
end
p2_hs_error=abs((R2-IF97)./IF97)
err=err+sum(sum(p2_hs_error>1E-8))
#*********************************************************************************************************
#* 7.3 Verifiy region 3
# IF-97 Table 33, Page 32
T=[650,650,750];
rho=[500,200,500];
Fun=[:p3_rhoT,:h3_rhoT,:u3_rhoT,:s3_rhoT,:Cp3_rhoT,:w3_rhoT];
IF97=[25.5837018 22.2930643 78.3095639;
1863.43019 2375.12401 2258.68845;
1812.26279 2263.65868 2102.06932;
4.05427273 4.85438792 4.46971906;
13.8935717 44.6579342 6.34165359;
502.005554 383.444594 760.696041];
R3=zeros(6,3);
for i=1:3
for j=1:6
R3[j,i]=eval(:($(Fun(i))(rho[$i],T[$i])));
end
end
Region3_error=abs((R3-IF97)./IF97)
err=err+sum(sum(Region3_error>1E-8))
#T3_ph
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
h=[1700,2000,2100,2500,2400,2700];
IF97=[629.3083892,690.5718338,733.6163014,641.8418053,735.1848618,842.0460876];
R3=zeros(1,6);
for i=1:6
R3[i]=T3_ph(p[i],h[i]);
end
T3_ph_error=abs((R3-IF97)./IF97)
err=err+sum(sum(T3_ph_error>1E-8))
#v3_ph
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
h=[1700,2000,2100,2500,2400,2700];
IF97=[0.001749903962,0.001908139035,0.001676229776,0.006670547043,0.0028012445,0.002404234998];
R3=zeros(1,6);
for i=1:6
R3[i]=v3_ph(p[i],h[i]);
end
v3_ph_error=abs((R3-IF97)./IF97)
err=err+sum(sum(v3_ph_error>1E-7))
#T3_ps
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
s=[3.7,3.5,4,5,4.5,5];
IF97=[620.8841563,618.1549029,705.6880237,640.1176443,716.3687517,847.4332825];
R3=zeros(1,6);
for i=1:6
R3[i]=T3_ps(p[i],s[i]);
end
T3_ps_error=abs((R3-IF97)./IF97)
err=err+sum(sum(T3_ps_error>1E-8))
#v3_ps
p=[200/10,500/10,1000/10,200/10,500/10,1000/10];
s=[3.7,3.5,4,5,4.5,5];
IF97=[0.001639890984,0.001423030205,0.001555893131,0.006262101987,0.002332634294,0.002449610757];
R3=zeros(1,6);
for i=1:6
R3[i]=v3_ps(p[i],s[i]);
end
v3_ps_error=abs((R3-IF97)./IF97)
err=err+sum(sum(v3_ps_error>1E-8))
#p3_hs
h=[1700,2000,2100,2500,2400,2700];
s=[3.8,4.2,4.3,5.1,4.7,5];
IF97=[25.55703246,45.40873468,60.7812334,17.20612413,63.63924887,88.39043281];
R3=zeros(1,6);
for i=1:6
R3[i]=p3_hs(h[i],s[i]);
end
p3_hs_error=abs((R3-IF97)./IF97)
err=err+sum(sum(p3_hs_error>1E-8))
#h3_pT (Iteration)
p=[255.83702,222.93064,783.09564]./10;
T=[650,650,750];
IF97=[1863.271389,2375.696155,2258.626582];
R3=zeros(1,3);
for i=1:3
R3[i]=h3_pT(p[i],T[i]);
end
h3_pT_error=abs((R3-IF97)./IF97)
err=err+sum(sum(h3_pT_error>1E-6)) #Decimals in IF97
#*********************************************************************************************************
#* 7.4 Verifiy region 4
#Saturation pressure, If97, Table 35, Page 34
T=[300,500,600];
IF97=[0.0353658941, 26.3889776, 123.443146]/10;
R3=zeros(1,3);
for i=1:3
R3[i]=p4_T(T[i]);
end
p4_t_error=abs((R3-IF97)./IF97)
err=err+sum(sum( p4_t_error>1E-7))
T=[1,10,100]/10;
IF97=[372.755919,453.035632,584.149488];
R3=zeros(1,3);
for i=1:3
R3[i]=T4_p(T[i]);
end
T4_p_error=abs((R3-IF97)./IF97)
err=err+sum(sum( T4_p_error>1E-7))
s=[1,2,3,3.8,4,4.2,7,8,9,5.5,5,4.5];
IF97=[308.5509647,700.6304472,1198.359754,1685.025565,1816.891476,1949.352563,2723.729985,2599.04721,2511.861477,2687.69385,2451.623609,2144.360448];
R3=zeros(1,12);
for i=1:12
R3[i]=h4_s(s[i]);
end
h4_s_error=abs((R3-IF97)./IF97)
err=err+sum(sum( h4_s_error>1E-7))
#*********************************************************************************************************
#* 7.5 Verifiy region 5
# IF-97 Table 42, Page 39
T=[1500,1500,2000];
p=[5,80,80]/10;
Fun=[:v5_pT,:h5_pT,:u5_pT,:s5_pT,:Cp5_pT,:w5_pT];
IF97=[1.38455354 0.0865156616 0.115743146;
5219.76332 5206.09634 6583.80291;
4527.48654 4513.97105 5657.85774;
9.65408431 8.36546724 9.15671044;
2.61610228 2.64453866 2.8530675;
917.071933 919.708859 1054.35806];
R5=zeros(6,3);
for i=1:3
for j=1:6
R5[j,i]=eval(:($(Fun(j))(p[$i],T[$i])));
end
end
Region5_error=abs((R5-IF97)./IF97)
err=err+sum(sum(Region5_error>1E-8))
#T5_ph (Iteration)
p=[0.5,8,8];
h=[5219.76331549428,5206.09634477373,6583.80290533381];
IF97=[1500,1500,2000];
R5=zeros(1,3);
for i=1:3
R5[i]=T5_ph(p[i],h[i]);
end
T5_ph_error=abs((R5-IF97)./IF97)
err=err+sum(sum(T5_ph_error>1E-7)) #Decimals in IF97
#T5_ps (Iteration)
p=[0.5,8,8];
s=[9.65408430982588,8.36546724495503,9.15671044273249];
IF97=[1500,1500,2000];
R5=zeros(1,3);
for i=1:3
R5[i]=T5_ps(p[i],s[i]);
end
T5_ps_error=abs((R5-IF97)./IF97)
err=err+sum(sum(T5_ps_error>1E-4)) #Decimals in IF97
end
#*********************************************************************************************************
#* 7.6 Verifiy calling funtions
#
#fun=["Tsat_p","T_ph","T_ps","T_hs","psat_T","p_hs","hV_p","hL_p","hV_T","hL_T","h_pT","h_ps","h_px","h_prho","h_Tx","vV_p","vL_p","vV_T","vL_T","v_pT","v_ph","v_ps","rhoV_p","rhoL_p","rhoV_T","rhoL_T","rho_pT","rho_ph","rho_ps","sV_p","sL_p","sV_T","sL_T","s_pT","s_ph","uV_p","uL_p","uV_T","uL_T","u_pT","u_ph","u_ps","CpV_p","CpL_p","CpV_T","CpL_T","Cp_pT","Cp_ph","Cp_ps","CvV_p","CvL_p","CvV_T","CvL_T","Cv_pT","Cv_ph","Cv_ps","wV_p","wL_p","wV_T","wL_T","w_pT","w_ph","w_ps","my_pT","my_ph","my_ps","tcL_p","tcV_p","tcL_T","tcV_T","tc_pT","tc_ph","tc_hs","st_T","st_p","x_ph","x_ps","vx_ph","vx_ps"];
#In1=["1","1","1","100","100","84","1","1","100","100","1","1","1","1","100","1","1","100","100","1","1","1","1","1","100","100","1","1","1","0.006117","0.0061171","0.0001","100","1","1","1","1","100","100","1","1","1","1","1","100","100","1","1","1","1","1","100","100","1","1","1","1","1","100","100","1","1","1","1","1","1","1","1","25","25","1","1","100","100","1","1","1","1","1"];
#In2=["0","100","1","0.2","0","0.296","0","0","0","0","20","1","0.5","2","0.5","0","0","0","0","100","1000","5","0","0","0","0","100","1000","1","0","0","0","0","20","84.01181117","0","0","0","0","100","1000","1","0","0","0","0","100","200","1","0","0","0","0","100","200","1","0","0","0","0","100","200","1","100","100","1","0","0","0","0","25","100","0.34","0","0","1000","4","418","4"];
#Control=["99.60591861","23.84481908","73.70859421","13.84933511","1.014179779","2.295498269","2674.949641","417.4364858","2675.572029","419.099155","84.01181117","308.6107171","1546.193063","1082.773391","1547.33559210927","1.694022523","0.001043148","1.671860601","0.001043455","1.695959407","0.437925658","1.03463539","0.590310924","958.6368897","0.598135993","958.3542773","0.589636754","2.283492601","975.6236788","9.155465556","1.8359E-05","9.155756716","1.307014328","0.296482921","0.296813845","2505.547389","417.332171","2506.015308","418.9933299","2506.171426","956.2074342","308.5082185","2.075938025","4.216149431","2.077491868","4.216645119","2.074108555","4.17913573168802","4.190607038","1.552696979","3.769699683","1.553698696","3.76770022","1.551397249","4.035176364","3.902919468","472.0541571","1545.451948","472.2559492","1545.092249","472.3375235","1542.682475","1557.8585","1.22704E-05","0.000914003770302108","0.000384222","0.677593822","0.024753668","0.607458162","0.018326723","0.607509806","0.605710062","0.606283124","0.0589118685876641","0.058987784","0.258055424","0.445397961","0.288493093","0.999233827"];
#
#for i=1:length(fun)
#
# T=:($(fun[i])(parse(Float64,$(In1[i])),parse(Float64,$(In2[i]))));
# Res=eval(T);
# Error=(Res-(parse(Float64,Control[i])))/parse(Float64,Control[i]);
# #Check=[T,"=",num2str(Res)," - (Control)",char(Control[i]),"=",num2str(Error)]
# if Error>1E-5
# err=err+1;
# error("To large error")
# end
#end
phc(p,h)=Cp_ph(p,h)
phg(p,h)=Cp_ph(p,h)/Cv_ph(p,h)
phq(p,h)=x_ph(p,h)
phs(p,h)=s_ph(p,h)
pht(p,h)=T_ph(p,h)
phv(p,h)=v_ph(p,h)
phw(p,h)=w_ph(p,h)
phm(p,h)=my_ph(p,h)
pqc(p,q)=(1.0-q)*CpL_p(p)+q*CpV_p(p)
pqh(p,q)=(1.0-q)*hL_p(p)+q*hV_p(p)
pqk(p,q)=(1.0-q)*tcL_p(p)+q*tcV_p(p)
pqg(p,q)=(1.0-q)*CpL_p(p)/CvL_p(p)+q*CpV_p(p)/CvV_p(p)
pqs(p,q)=(1.0-q)*sL_p(p)+q*sV_p(p)
pqv(p,q)=(1.0-q)*vL_p(p)+q*vV_p(p)
pqw(p,q)=(1.0-q)*wL_p(p)+q*wV_p(p)
pqm(p,q)=(1.0-q)*my_ph(p,hL_p(p))+q*my_ph(p,hV_p(p))
psc(p,s)=Cp_ps(p,s)
psg(p,s)=Cp_ps(p,s)/Cv_ps(p,s)
psh(p,s)=h_ps(p,s)
psq(p,s)=x_ps(p,s)
pst(p,s)=T_ps(p,s)
psv(p,s)=v_ps(p,s)
psw(p,s)=w_ps(p,s)
psm(p,s)=my_ps(p,s)
pt(p)=Tsat_p(p)
ptc(p,t)=Cp_pT(p,t)
ptg(p,t)=Cp_pT(p,t)/Cv_pT(p,t)
pth(p,t)=h_pT(p,t)
ptk(p,t)=tc_pT(p,t)
ptm(p,t)=my_pT(p,t)
pts(p,t)=s_pT(p,t)
ptv(p,t)=v_pT(p,t)
ptw(p,t)=w_pT(p,t)
tp(t)=psat_T(t)
tqc(t,q)=(1.0-q)*CpL_T(t)+q*CpV_T(t)
tqg(t,q)=(1.0-q)*CpL_T(t)/CvL_T(t)+q*CpV_T(t)/CvV_T(t)
tqh(t,q)=(1.0-q)*hL_T(t)+q*hV_T(t)
tqk(t,q)=(1.0-q)*tcL_T(t)+q*tcV_T(t)
tqs(t,q)=(1.0-q)*sL_T(t)+q*sV_T(t)
tqv(t,q)=(1.0-q)*vL_T(t)+q*vV_T(t)
tqw(t,q)=(1.0-q)*wL_T(t)+q*wV_T(t)
hst(h,s)=T_hs(h,s)
hsp(h,s)=p_hs(h,s)
pqu(p,q)=(1.0-q)*uL_p(p)+q*uV_p(p)
tqu(t,q)=(1.0-q)*uL_T(t)+q*uV_T(t)
ptu(p,t)=u_pT(p,t)
phu(p,h)=u_ph(p,h)
psu(p,h)=s_ph(p,h)
hsk(h,s)=tc_hs(h,s)
pvh(p,v)=h_prho(p,1/v)
hvp(h,v)=p_hrho(h,1/v)
export phc,phg,phq,phs,pht,phv,phw,phm,pqc,pqh,pqk,pqg,pqs,pqv,pqw,pqm,psc,psg,psh,psq,pst,psv,psw,psm
export pt,ptc,ptg,pth,ptk,ptm,pts,ptv,ptw,tp,tqc,tqg,tqh,tqk,tqs,tqv,tqw,hst,pqu,tqu,ptu,phu,psu,hsk,pvh,hvp
export Tsat_p,T_ph,T_ps,T_hs,psat_T,p_hs,hV_p,hL_p,hV_T,hL_T,h_pT,h_ps,h_px,h_prho,h_Tx,vV_p,vL_p,vV_T,vL_T,v_pT,v_ph,v_ps
export rhoV_p,rhoL_p,rhoV_T,rhoL_T,rho_pT,rho_ph,rho_ps,sV_p,sL_p,sV_T,sL_T,s_pT,s_ph,uV_p,uL_p,uV_T,uL_T,u_pT,u_ph,u_ps,CpV_p
export CpL_p,CpV_T,CpL_T,Cp_pT,Cp_ph,Cp_ps,CvV_p,CvL_p,CvV_T,CvL_T,Cv_pT,Cv_ph,Cv_ps,wV_p,wL_p,wV_T,wL_T,w_pT,w_ph,w_ps,my_pT,my_ph,my_ps
export tcL_p,tcV_p,tcL_T,tcV_T,tc_pT,tc_ph,tc_hs,st_T,st_p,x_ph,x_ps,vx_ph,vx_ps;
end
| XSteamUnits | https://github.com/hzgzh/XSteamUnits.jl.git |
|
[
"MPL-2.0"
] | 0.1.0 | fac1b8e5051146e12819eebda2f8e1d19bd1c1ea | code | 95 | using XSteamUnits
using Test
@testset "XSteamUnits.jl" begin
# Write your tests here.
end
| XSteamUnits | https://github.com/hzgzh/XSteamUnits.jl.git |
|
[
"MPL-2.0"
] | 0.1.0 | fac1b8e5051146e12819eebda2f8e1d19bd1c1ea | docs | 9173 | ## XSteamUnits for julia
XSteam with Unitful
Immigrate By hzgzh Date: 2019-9-29
X Steam for julia is a implementation of the IAPWS IF97 standard formulation immigrate from XSteam for matlab By Magnus Holmgren, www.x-eng.com
The steam tables are free and provided as is.
We take no responsibilities for any errors in the code or damage thereby.
You are free to use, modify and distribute the code as long as authorship is properly acknowledged.
Please notify me at [email protected] if the code is used in commercial applications. It
provides accurate data for water and steam and mixtures of water and steam properties from
0 - 1000 bar and from 0 - 2000 deg C.
The initial units of XSteam are SI units as denoted in this document. All functions however
call unit conversion functions so the units can be easily changed. A text file with unit
conversion functions for English units are enclosed with the file.
### Usage
The XSteam code are used in the following way:
* Example: rho_pT(1,200) returns the density at 1 bar and 200°C.
* winsteam syntax pth(1,200) returns the entalpy at 1bar and 200°C
### Introduction
X Steam for matlab is a implementation of the IAPWS IF97 standard formulation. It
provides accurate thermo hydraulic data for water and steam and mixtures of water and
steam in the region:
* 0°C < temperature < 2000°C for
* 0.00611 bar a < pressure < 100 bar a
* 0°C < temperature < 1000°C for
* 0.00611 bar a < pressure < 1000 bar a
For accuracy and further information on IAPWS IF97 formulation, se homepage of the
international association for properties of water and steam (www.iapws.org).
### Unit
|Notation|Quantity|Unit|
|-|-|-|
|T|Temperature|°C|
|p|Pressure|bar|
|h|Enthalpy|kJ/kg|
|v|Specific volume|$m^3/kg$|
|rho|Density|$kg/m^3$|
|s|Specific entropy|kJ/(kg °C)|
|u|Specific internal energy|kJ/kg|
|Cp|Specific isobaric heat capacity|kJ/(kg °C)|
|Cv|Specific isochoric heat capacity|kJ/(kg °C)|
|w|Speed of sound|m/s|
|my|Viscosity|Pa s|
|tc|Thermal Conductivity|W/(m °C)|
|st|Surface Tension|N/m|
|x or q|Vapour fraction (0-1)|-|
|vx|Vapour Volume Fraction (0-1)|-|
## XSteam functions
### Temperature
|Function|In1|In2|Out|
|-|-|-|-|
|Tsat_p or pt|p||Saturation temperature|
|T_ph or pht|p|H|Temperture as a function of pressure and enthalpy|
|T_ps or pst|p|S|Temperture as a function of pressure and entropy|
|T_hs or hst|h|S|Temperture as a function of enthalpy and entropy|
### Pressure
|Function|In1|In2|Out|
|-|-|-|-|
|psat_T or tp|T||Saturation pressure|
|p_hs or hsp|h|s|Pressure as a function of h and s.|
|p_hrho or hvp|h|rho|Pressure as a function of h and rho (density) or Specific volume .Very unaccurate for solid water region since it's almost incompressible!|
### Enthalpy
|Function|In1|In2|Out|
|-|-|-|-|
|hV_p or pqh(p,1)|p||Saturated vapour enthalpy|
|hL_p or pqh(p,0)|p||Saturated liquid enthalpy|
|hV_T or tqh(t,1)|T||Saturated vapour enthalpy|
|hL_T or tqh(t,0)|T||Saturated liquid enthalpy|
|h_pT or pth| p| T| Entalpy as a function of pressure and temperature.|
|h_ps or psh| p| s| Entalpy as a function of pressure and entropy.|
|h_px or pqh| p| x| Entalpy as a function of pressure and vapour fraction|
|h_Tx or tqh| T| X| Entalpy as a function of temperature and vapour fraction|
|h_prho or pvh| p| rho|Entalpy as a function of pressure and density or Specific volume. Observe for low temperatures (liquid) this equation has 2 solutions.(Not valid!!)|
### Specific volume
|Function|In1|In2|Out|
|-|-|-|-|
|vV_p or pqv(p,1)| p|| Saturated vapour volume|
|vL_p or pqv(p,0)| p|| Saturated liquid volume|
|vV_T or tqv(p,1)| T|| Saturated vapour volume|
|vL_T or tqv(p,0)| T|| Saturated liquid volume|
|v_pT or ptv| p| T|Specific volume as a function of pressure and temperature.|
|v_ph or phv| p| h| Specific volume as a function of pressure and enthalpy|
|v_ps or psv| p| s| Specific volume as a function of pressure and entropy.|
### Density
|Function|In1|In2|Out|
|-|-|-|-|
|rhoV_p or 1/pqv(p,1)| p|| Saturated vapour density|
|rhoL_p or 1/pqv(p,0)| p|| Saturated liquid density|
|rhoV_T or 1/tqv(t,1)| T|| Saturated vapour density|
|rhoL_T or 1/tqv(t,0)| T|| Saturated liquid density|
|rho_pT or 1/ptv| p| T| Density as a function of pressure and temperature.|
|rho_ph or 1/phv| p| h| Density as a function of pressure and enthalpy|
|rho_ps or 1/psv| p| s| Density as a function of pressure and entropy.|
### Specific entropy
|Function|In1|In2|Out|
|-|-|-|-|
|sV_p or pqs(p,1)| p|| Saturated vapour entropy|
|sL_p or pqs(p,0)| p|| Saturated liquid entropy|
|sV_T or tqs(p,1)| T|| Saturated vapour entropy|
|sL_T or tqs(p,0)| T|| Saturated liquid entropy|
|s_pT or pts|p| T|Specific entropy as a function of pressure and temperature(Returns saturated vapour entalpy if mixture.)|
|s_ph or phs| p| h|Specific entropy as a function of pressure and enthalpy|
### Specific internal energy
|Function|In1|In2|Out|
|-|-|-|-|
|uV_p or pqu(p,1)| p|| Saturated vapour internal energy|
|uL_p or pqu(p,0)| p|| Saturated liquid internal energy|
|uV_T or tqu(t,1)| T|| Saturated vapour internal energy|
|uL_T or tqu(t,0)| T|| Saturated liquid internal energy|
|u_pT or ptu|p| T|Specific internal energy as a function of pressure and temperature.|
|u_ph or phu|p| h|Specific internal energy as a function of pressure and enthalpy|
|u_ps or psu|p| s|Specific internal energy as a function of pressure and entropy.|
### Specific isobaric heat capacity
|Function|In1|In2|Out|
|-|-|-|-|
|CpV_p or pqc(p,1)| p||Saturated vapour heat capacity|
|CpL_p or pqc(p,0)| p|| Saturated liquid heat capacity|
|CpV_T or tqc(t,1)| T|| Saturated vapour heat capacity|
|CpL_T or tqc(t,0)| T|| Saturated liquid heat capacity|
|Cp_pT or ptc|p| T|Specific isobaric heat capacity as a function of pressure and temperature.|
|Cp_ph or phc|p| h|Specific isobaric heat capacity as a function of pressure and enthalpy|
|Cp_ps or psc|p| s|Specific isobaric heat capacity as a function of pressure and entropy.|
### Specific isochoric heat capacity
|Function|In1|In2|Out|
|-|-|-|-|
|CvV_p| p|| Saturated vapour isochoric heat capacity|
|CvL_p| p|| Saturated liquid isochoric heat capacity|
|CvV_T| T|| Saturated vapour isochoric heat capacity|
|CvL_T| T|| Saturated liquid isochoric heat capacity|
|Cv_pT|p| T|Specific isochoric heat capacity as a function of pressure and temperature.|
|Cv_ph|p| h|Specific isochoric heat capacity as a function of pressure and enthalpy|
|Cv_ps|p| s|Specific isochoric heat capacity as a function of pressure and entropy.|
### Speed of sound
|Function|In1|In2|Out|
|-|-|-|-|
|wV_p or pqw(p,1)| p|| Saturated vapour speed of sound|
|wL_p or pqw(p,0)| p|| Saturated liquid speed of sound|
|wV_T or tqw(t,1)| T|| Saturated vapour speed of sound|
|wL_T or tqw(t,0)| T|| Saturated liquid speed of sound|
|w_pT or ptw|p| T|Speed of sound as a function of pressure and temperature.|
|w_ph or phw| p| h| Speed of sound as a function of pressure and enthalpy|
|w_ps or psw| p| s| Speed of sound as a function of pressure and entropy.|
### Viscosity
Viscosity is not part of IAPWS Steam IF97. Equations from "Revised Release on the
IAPWS Formulation 1985 for the Viscosity of Ordinary Water Substance", 2003 are used.
Viscosity in the mixed region (4) is interpolated according to the density. This is not true
since it will be two fases.
|Function|In1|In2|Out|
|-|-|-|-|
|my_pT or ptm| p| T| Viscosity as a function of pressure and temperature.|
|my_ph or phm| p| h| Viscosity as a function of pressure and enthalpy|
|my_ps or psm| p| s| Viscosity as a function of pressure and entropy.|
|pqm|p|q| Viscosity as a function of pressure and quality.|
### Thermal Conductivity
Revised release on the IAPS Formulation 1985 for the Thermal Conductivity of ordinary water substance (IAPWS 1998)
|Function|In1|In2|Out|
|-|-|-|-|
|tcL_p or pqk(p,1)| p|| Saturated vapour thermal conductivity|
|tcV_p or pqk(p,0)| p|| Saturated liquid thermal conductivity|
|tcL_T or tqk(t,1)| T||Saturated vapour thermal conductivity|
|tcV_T or tqk(t,0)| T|| Saturated liquid thermal conductivity|
|tc_pT or ptk|p| T|Thermal conductivity as a function of pressure and temperature.|
|tc_ph or phk|p| h|Thermal conductivity as a function of pressure and enthalpy|
|tc_hs or hsk|h| s| Thermal conductivity as a function of enthalpy and entropy|
### Surface Tension
IAPWS Release on Surface Tension of Ordinary Water Substance,September 1994
|Function|In1|In2|Out|
|-|-|-|-|
|st_T|T||Surface tension for two phase water/steam as a function of T|
|st_p|p||Surface tension for two phase water/steam as a function of T|
### Vapour fraction
|Function|In1|In2|Out|
|-|-|-|-|
|x_ph or phq|p| h|Vapour fraction for two phase water/steam as a function of T|
|x_ps or psq|p| s|Vapour fraction for two phase water/steam as a function of T|
### Vapour Volume Fraction
Observe that vapour volume fraction is very sensitive. Vapour volume is about 1000 times greater than liquid volume and therefore vapour volume fraction gets close to the accurancy of IAPWS IF-97
|Function|In1|In2|Out|
|-|-|-|-|
|vx_ph|p| h|Vapour volume fraction as a function of pressure and enthalpy|
|vx_ps|p| s|Vapour volume fraction as a function of pressure and entropy.|
| XSteamUnits | https://github.com/hzgzh/XSteamUnits.jl.git |
|
[
"MPL-2.0"
] | 0.1.0 | fac1b8e5051146e12819eebda2f8e1d19bd1c1ea | docs | 113 | ```@meta
CurrentModule = XSteamUnits
```
# XSteamUnits
```@index
```
```@autodocs
Modules = [XSteamUnits]
```
| XSteamUnits | https://github.com/hzgzh/XSteamUnits.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 627 | using LLMCheatsheets
using Documenter
DocMeta.setdocmeta!(
LLMCheatsheets, :DocTestSetup, :(using LLMCheatsheets); recursive = true)
makedocs(;
modules = [LLMCheatsheets],
authors = "J S <[email protected]> and contributors",
sitename = "LLMCheatsheets.jl",
format = Documenter.HTML(;
canonical = "https://svilupp.github.io/LLMCheatsheets.jl",
edit_link = "main",
assets = String[]
),
pages = [
"Home" => "index.md",
"API" => "api.md"
]
)
deploydocs(;
repo = "github.com/svilupp/LLMCheatsheets.jl",
devbranch = "main"
)
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 624 | # # Example 2: Create a cheatsheet for the LLMCheatsheets.jl package
using LLMCheatsheets
# Note: if you're hitting Github's rate limits, make sure to set the `GITHUB_API_KEY` environment variable.
# # High-level example: Create a cheatsheet in two lines
repo = GitHubRepo("https://github.com/svilupp/LLMCheatsheets.jl")
cheatsheet = create_cheatsheet(repo; save_path = true)
# will auto-save the cheatsheet in a file called `llm-cheatsheets/LLMCheatsheets_Cheatsheet.md`
# Specify your own path, by setting `save_path` to a string representing the file path.
# # Grab all the files in the repo
files_str = collect(repo) | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 1727 | # This script creates cheatsheets for a list of popular Julia packages.
using LLMCheatsheets
repos = [
GitHubRepo("https://github.com/svilupp/LLMCheatsheets.jl"),
GitHubRepo("https://github.com/svilupp/AIHelpMe.jl"),
GitHubRepo("https://github.com/JuliaData/DataFrames.jl"),
GitHubRepo("https://github.com/JuliaData/DataFramesMeta.jl"),
GitHubRepo("https://github.com/JuliaData/CSV.jl"),
GitHubRepo("https://github.com/JuliaWeb/HTTP.jl"),
GitHubRepo("https://github.com/JuliaAI/MLFlowClient.jl"),
GitHubRepo("https://github.com/GenieFramework/Genie.jl"),
# GitHubRepo("https://github.com/GenieFramework/Stipple.jl"),
GitHubRepo("https://github.com/GenieFramework/StippleUI.jl"),
GitHubRepo("https://github.com/JuliaAI/MLJ.jl"),
GitHubRepo("https://github.com/JuliaPlots/StatsPlots.jl"; paths = ["src", "README.md"]),
GitHubRepo(
"https://github.com/MakieOrg/Makie.jl"; paths = ["docs/src", "README.md"]),
GitHubRepo("https://github.com/MakieOrg/AlgebraOfGraphics.jl")
]
for url in repos
repo = GitHubRepo(url)
@info "Repo: $(repo.owner)/$(repo.name)"
create_cheatsheet(repo; save_path = true, model = "gpt4o")
end;
repo = GitHubRepo("https://github.com/GenieFramework/Stipple.jl")
create_cheatsheet(repo; save_path = true, model = "gpt4o",
special_instructions = """
Focus on a lot of practical examples with `@app` macro. Include examples of handlers with `@in`,`@out`,`@onchange`, `@onclick`, `@page` and more.
Include as much actual examples as possible, but they must be faithful to the user inputs.
Add a few practical examples of creating a ui.
You are not allowed to use any content not directly provided in the source materials.
""") | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 3096 | # # Example 1: Create a cheatsheet for the PromptingTools.jl package
using LLMCheatsheets
# Note: if you're hitting Github's rate limits, make sure to set the `GITHUB_API_KEY` environment variable.
# # High-level example: Create a cheatsheet in two lines
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl")
cheatsheet = create_cheatsheet(repo; save_path = true)
# will auto-save the cheatsheet in a file called `llm-cheatsheets/PromptingTools_Cheatsheet.md`
# Specify your own path, by setting `save_path` to a string representing the file path.
# # Detailed step-by-step example
# Step 1: Define the GitHub repository, paths to scan, and file types to summarize
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl";
paths = ["src", "docs/src", "README.md"], file_types = [".jl", ".md"])
# Step 2: Initialize the model and a cost tracker (optional, but useful for monitoring API usage)
model = "gpt4o" # or "gpt4om"
cost_tracker = Threads.Atomic{Float64}(0.0)
save_path = joinpath(@__DIR__, "My_PromptingTools_Cheatsheet.md")
# Step 3: Scan the repository and summarize files
all_file_summaries = Dict{Symbol, AbstractString}[]
## You can add a lot of custom detail to the summary by adding special instructions.
special_instructions = """When relevant, add a lot of detail for `create_template` to show how easy it is to create re-usable prompt templates.
Add some basic points on what a good prompt should have: Clear task description, guidelines/instructions, desired output format.
All that should be in the `system` prompt, the `user` prompt should have just the placeholders for the inputs in double curly braces, eg, `{{input}}`.
Cool trick people don't know --> you can use `AIGenerate` for effortless multi-turn conversations with the LLM. Use it as a functor, ie, use it as a function.
In addition, deep dive on all aspect of RAGTools - airag, retrieve, generate!, etc.
All of the above should be in ADDITION to all the other cool features of PromptingTools.
""" # Use to customize the output
for path in repo.paths
# Scan each path in the repository
files = scan_github_path(repo, path)
# Process each file asynchronously
asyncmap(files) do file
try
# Summarize the file content
summary = summarize_file(
file;
cost_tracker,
model,
special_instructions,
verbose = false
)
push!(all_file_summaries, summary)
catch e
@warn "Error processing $(file[:name]): $e"
end
end
end
# Step 4: Create the cheatsheet
cheatsheet = create_cheatsheet(
repo,
all_file_summaries;
model,
special_instructions,
cost_tracker,
verbose = true,
save_path # This will save the cheatsheet to the file path specified in `save_path`
)
# Print some statistics
@info "Cheatsheet created! Total cost: \$$(round(cost_tracker[], digits=2))"
@info "Cheatsheet saved to: $(save_path)"
# You can now use the `cheatsheet` variable or read the saved markdown file
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 12558 | using PromptingTools
const PT = PromptingTools
# Create templates for prompts
script_summary = PT.create_template(;
system = """You will be provided a file containing Julia code.
Your task is to analyze the file and extract key user-facing elements and any practical information about them.
Your answer will be used to create a comprehensive cheatsheet for a newcomer on how to use the code, ensuring they have all the information they might need without visiting the repository.
### Guidelines
- Thoroughly review the provided file, considering all modules, sub-modules, and their contents.
- Identify and include key user-facing elements such as functions, types (structs), constants, and macros that are relevant to end-users.
- Consider elements that have docstrings, are exported from the module, or are marked with the prefix "public" as user-facing.
- Include elements exported using the `export` keyword, even if they lack docstrings or the "public" prefix.
- Start the summary with the full name of the module/sub-module, if relevant, to make it easier to specify the correct import strategy.
- Be very descriptive in how to use the functions, types, and concepts to enable junior developers to get started effectively.
- Pay special attention to variable and argument types, and prefer keyword arguments over positional arguments for clarity in examples.
- Include code examples where appropriate, demonstrating typical usage patterns.
- Highlight key tips and best practices if they are mentioned in the docstrings or comments and are not obvious.
- If there are no user-facing elements in this file (functions, types, constants, or macros), state that there are no user-facing elements.
- Summarize general information or conceptual explanations if the file contains them, especially if practical information is lacking.
- Handle files with multiple or nested modules by summarizing each relevant module separately, starting with the module's name.
- If the file contains syntax errors, incomplete code, or is not valid Julia code, mention that the file may be incomplete or contains errors.
- Exclude internal or private functions, types, or variables unless they are essential for understanding the user-facing elements.
- First and foremost, attend to any user-provided SPECIAL INSTRUCTIONS. If they are empty, use the default guidelines above.
""",
user = """FILE TO SUMMARIZE:
```julia
{{content}}
```
SPECIAL INSTRUCTIONS:
{{special_instructions}}
Start the summary with the name of the module/sub-module, if relevant, to make it easier to specify the correct import strategy.
""", load_as = :FileSumarizerJuliaScript)
filename = joinpath(@__DIR__,
"..",
"templates",
"FileSumarizerJuliaScript.json")
PT.save_template(filename,
script_summary;
version = "1.0",
description = "Creates a Julia script-focused summary of a file provided. Provide special instructions if necessary, otherwise set to `none`. Placeholders: `content`, `special_instructions`")
markdown_summary = PT.create_template(;
system = """You will be provided a file containing Markdown documentation.
Your task is to analyze the file and extract the most important information that the developer highlighted.
Your answer will be used to create a comprehensive cheatsheet for a newcomer on how to use the code, ensuring they have all the information they might need without visiting the repository.
### Guidelines
- Thoroughly review the provided file, considering all sections, subsections, and any embedded code examples.
- Identify and include key concepts, their explanations, practical tips, best practices, important caveats, and warnings.
- Be very descriptive in how to use the functions and concepts to enable junior developers to get started effectively.
- Pay special attention to variable types, function arguments, and usage patterns; prefer keyword arguments over positional arguments for clarity.
- Include code examples where appropriate, ensuring they are clear, well-commented, and demonstrate typical usage scenarios.
- Add comments to code examples to highlight non-obvious concepts and best practices.
- Highlight tips, tricks, hacks, and nuanced explanations that can aid understanding or prevent common pitfalls.
- Organize the summary hierarchically, starting with the most important information and breaking down topics into logical sections.
- Start the summary with the name of the key information or main topic to provide immediate context.
- If the documentation includes diagrams or visual aids, describe them briefly if they contribute to understanding key concepts.
- Exclude irrelevant or redundant information that does not contribute to a newcomer's understanding of how to use the code.
- Handle any special Markdown features (like tables, lists, or links) appropriately to preserve the information's clarity.
- First and foremost, attend to any user-provided SPECIAL INSTRUCTIONS. If they are empty, use the default guidelines above.
""",
user = """FILE TO SUMMARIZE:
<markdown>
{{content}}
</markdown>
SPECIAL INSTRUCTIONS:
{{special_instructions}}
Start the summary with the name of key information. Be very hierarchical and organized.
""", load_as = :FileSumarizerMarkdown)
filename = joinpath(@__DIR__,
"..",
"templates",
"FileSumarizerMarkdown.json")
PT.save_template(filename,
markdown_summary;
version = "1.0",
description = "Creates a markdown-focused summary of a file provided. Provide special instructions if necessary, otherwise set to `none`. Placeholders: `content`, `special_instructions`")
general_summary = PT.create_template(;
system = """You will be provided a file from a GitHub repository.
Your task is to analyze the file and extract key information that would be useful for a newcomer to understand the repository, its purpose, and functionality.
Your answer will be used to create a comprehensive cheatsheet for a newcomer on how to use the repository, ensuring they have all the information they might need without visiting the repository.
### Guidelines
- Thoroughly review the provided file, regardless of its format (e.g., JSON, HTML, text, configuration files, scripts).
- Identify and include key concepts, functionalities, configurations, or any critical information highlighted by the developer that would aid a newcomer.
- Focus on the most important information that would be useful for a newcomer to know.
- Extract key concepts, their explanations, practical tips, best practices, important caveats, and warnings.
- If there are code examples, snippets, or configurations, include the most illustrative ones, ensuring they are clear and well-commented.
- Be very descriptive in how to use the functions, features, or configurations to enable junior developers to get started effectively.
- Include key tips and best practices, highlighting non-obvious concepts and practices.
- Organize the summary hierarchically, starting with the name of the module/sub-module or main topic to provide immediate context.
- If the file contains configuration settings (e.g., JSON, YAML), explain the purpose of key settings and how they affect the repository's behavior.
- If the file is a script or executable code (e.g., shell scripts, batch files), describe what it does and how to use it.
- For HTML or other documentation files, extract key information that provides insights into the repository's usage or functionality.
- Exclude irrelevant or redundant information that does not contribute to a newcomer's understanding of how to use the repository.
- Handle any special formats appropriately to preserve the clarity and usefulness of the information.
- First and foremost, attend to any user-provided SPECIAL INSTRUCTIONS. If they are empty, use the default guidelines above.
""",
user = """FILE TO SUMMARIZE:
<file>
{{content}}
</file>
SPECIAL INSTRUCTIONS:
{{special_instructions}}
""", load_as = :FileSumarizerGeneral)
filename = joinpath(@__DIR__,
"..",
"templates",
"FileSumarizerGeneral.json")
PT.save_template(filename,
general_summary;
version = "1.0",
description = "Creates a code-focused summary of a file provided. Provide special instructions if necessary, otherwise set to `none`. Placeholders: `content`, `special_instructions`")
cheatsheet_prompt = PT.create_template(;
system = """You will be provided the contents of a GitHub repository.
Your task is to create a comprehensive cheatsheet for a newcomer on how to use the repository, ensuring they have all the information they might need without visiting the repository.
It must be so comprehensive that a junior developer could start coding without any additional training or instructions.
### Guidelines
- Thoroughly review the provided files, considering all modules, sub-modules, and their contents.
- **Lead with practical information**, such as:
- How to install the package, including any dependencies or prerequisites.
- How to import or include the package in a project.
- Any initial setup or configuration required.
- **Explain the purpose of the package**, providing context and the problems it solves.
- **List the main functions, types, constants, and macros**, including brief descriptions of what they do.
- **Provide detailed examples for all relevant functionality**, ensuring:
- Examples are clear, well-commented, and demonstrate typical usage scenarios.
- Comments highlight key concepts, important details, and any non-obvious aspects.
- Clarity, simplicity, and diversity are prioritized in code examples.
- Use an informal and approachable tone, as if explaining to a junior developer who is eager to learn and start coding.
- Highlight key concepts and any sharp edges or potential pitfalls the developer should be aware of.
- Include key tips, best practices, and important caveats or warnings.
- Organize the cheatsheet logically and hierarchically, making it easy to understand and follow.
- Avoid leaving out any important information, but also avoid repetition.
- Format the cheatsheet in Markdown for easy readability, using appropriate headings, lists, code blocks, and emphasis where necessary.
- **Pay special attention to `README.md` and any `index.md` files**, as they often contain the most important information.
- If there are multiple modules or components, organize the cheatsheet to reflect this structure, providing clear sections for each.
- Include installation instructions and any necessary setup steps, ensuring no steps are assumed or skipped.
- First and foremost, attend to any user-provided SPECIAL INSTRUCTIONS. If they are empty, use the default guidelines above.
Please structure the cheatsheet to cover:
1. **Package Name**: Include the full name of the package.
2. **URL**: Provide the repository or documentation URL.
3. **Purpose**: A brief description of what the package does and the problems it solves.
4. **Installation**: Step-by-step instructions on how to install and set up the package.
5. **Usage Overview**: General information on how to use the package, including import statements and basic examples.
6. **Main Features and Functions**:
- List of main functions, types, constants, and macros.
- For each, provide:
- A brief description.
- Detailed examples with comments.
7. **Detailed Examples**:
- For all relevant functionality, provide code examples that are clear and well-commented.
- Highlight key concepts, best practices, and any non-obvious details.
8. **Tips and Best Practices**:
- Include practical advice, common pitfalls to avoid, and optimal usage patterns.
9. **Additional Resources**:
- Link to any relevant documentation, tutorials, or guides if necessary.
""",
user = """ Please create a comprehensive cheatsheet for the provided repository based on the following information:
Package Name: {{name}}
URL: {{url}}
Files or File Summaries:
{{files}}
Special Instructions: {{special_instructions}}""", load_as = :CheatsheetCreator)
filename = joinpath(@__DIR__,
"..",
"templates",
"CheatsheetCreator.json")
PT.save_template(filename,
cheatsheet_prompt;
version = "1.0",
description = "Creates a cheatsheet for a repository provided. Provide special instructions if necessary, otherwise set to `none`. Placeholders: `name`, `url`, `files`, `special_instructions`")
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 648 | module LLMCheatsheets
using HTTP
using JSON3
using Mocking
using PromptingTools
using PromptingTools: aigenerate, pprint, last_output, last_message
const PT = PromptingTools
global GITHUB_API_KEY::String = ""
export GitHubRepo, scan_github_path
include("github.jl")
export summarize_file, collate_files
include("file_processing.jl")
export create_cheatsheet
include("cheatsheet_creation.jl")
function __init__()
global GITHUB_API_KEY
GITHUB_API_KEY = get(ENV, "GITHUB_API_KEY", "")
## Load extra templates
PT.load_templates!(joinpath(@__DIR__, "..", "templates"); remember_path = true) # add our custom ones
end
end # module
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 8676 | """
create_cheatsheet(
repo::GitHubRepo, file_contents::AbstractVector{<:AbstractDict};
model = "gpt4o", special_instructions::AbstractString = "None.\n",
template::Symbol = :CheatsheetCreator,
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = nothing,
verbose::Bool = true, save_path::Union{Nothing, String, Bool} = nothing,
http_kwargs::NamedTuple = NamedTuple())
create_cheatsheet(repo::GitHubRepo;
model = "gpt4o", cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = Threads.Atomic{Float64}(0.0),
special_instructions::AbstractString = "None.\n",
template::Symbol = :CheatsheetCreator,
verbose::Bool = true, save_path::Union{Nothing, String} = nothing,
ntasks::Int = 0,
http_kwargs::NamedTuple = NamedTuple())
Creates a cheatsheet for the given GitHub repository and file summaries.
Note: If you're getting rate limited by GitHub API, request a personal access token and set it as `ENV["GITHUB_API_KEY"]` (raised your limit to 5000 requests per hour).
# Arguments
- `repo::GitHubRepo`: The repository to create a cheatsheet for.
- `file_contents::AbstractVector{<:AbstractDict}`: The file contents or the summaries of the files in the repository. If not provided, the repository is scanned and the file summaries are created.
- `model::String`: The model to use for the LLM call.
- `special_instructions::AbstractString`: Special instructions for the AI to tweak the output.
- `template::Symbol`: The template to use for the cheatsheet creation.
- `cost_tracker::Union{Nothing, Threads.Atomic{<:Real}}`: A tracker to record the cost of the LLM calls.
- `verbose::Bool`: Whether to print verbose output.
- `save_path::Union{Nothing, String, Bool}`: The path to save the cheatsheet to. If `true`, the cheatsheet is auto-saved to a subdirectory called `llm-cheatsheets` in the current working directory.
- `http_kwargs::NamedTuple`: Additional keyword arguments to pass to the `github_api` function influencing the HTTP requests.
- `ntasks::Int`: The number of tasks to use for the asynchronous processing. If `0`, the number of tasks is set to the `asyncmap` default.
# Returns
- `String`: The content of the cheatsheet.
"""
function create_cheatsheet(
repo::GitHubRepo, file_contents::AbstractVector{<:AbstractDict};
model = "gpt4o", special_instructions::AbstractString = "None.\n",
template::Symbol = :CheatsheetCreator,
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = nothing,
verbose::Bool = true, save_path::Union{Nothing, String, Bool} = nothing,
http_kwargs::NamedTuple = NamedTuple())
##
verbose && @info "Creating cheatsheet for $(repo.owner)/$(repo.name)"
collated_summaries = collate_files(file_contents)
response = aigenerate(template; url = repo.url, name = repo.name,
files = collated_summaries, special_instructions, model = model, verbose)
!isnothing(cost_tracker) && Threads.atomic_add!(cost_tracker, response.cost)
if !isnothing(save_path)
if save_path === true
## Save to pwd subdirectory
save_path = joinpath(
pwd(), "llm-cheatsheets", "$(replace(repo.name, ".jl"=>""))_Cheatsheet.md")
end
## Create the directory if it doesn't exist
mkpath(dirname(save_path))
## Write the cheatsheet to the file
open(save_path, "w") do io
write(io, response.content)
end
end
return response.content
end
function create_cheatsheet(
repo::GitHubRepo;
model = "gpt4o", special_instructions::AbstractString = "None.\n",
template::Symbol = :CheatsheetCreator,
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = Threads.Atomic{Float64}(0.0),
verbose::Bool = true, save_path::Union{Nothing, String, Bool} = nothing,
ntasks::Int = 0,
http_kwargs::NamedTuple = NamedTuple())
start_time = time()
all_file_summaries = Dict{Symbol, AbstractString}[]
verbose &&
@info "Will scan the following paths: $(join(repo.paths, ", ")) and file types: $(join(repo.file_types, ", "))"
for path in repo.paths
files = scan_github_path(repo, path; verbose, http_kwargs)
if isempty(files)
@warn "No files found in path: $path"
continue
end
asyncmap(files; ntasks) do file
try
summary = summarize_file(
file; cost_tracker, model, verbose = false, http_kwargs,
special_instructions)
push!(all_file_summaries, summary)
catch e
@warn "Error processing $(file[:name]): $e"
end
end
end
if isempty(all_file_summaries)
error("No files were successfully processed in any folder. Validate the paths and file types (Paths: $(join(repo.paths, ", ")), File types: $(join(repo.file_types, ", ")))")
end
## Cheatsheet creation
verbose && @info "Creating cheatsheet for $(repo.owner)/$(repo.name)"
cheatsheet = create_cheatsheet(
repo, all_file_summaries; model, special_instructions,
cost_tracker, verbose = false, save_path, http_kwargs, template)
verbose &&
@info "Cheatsheet created and saved to $save_path. Duration: $(round(time() - start_time, digits = 1)) seconds. Total cost: \$$(round(cost_tracker[], digits = 3)) dollars."
return cheatsheet
end
"""
Base.collect(
repo::GitHubRepo;
verbose::Bool = true,
save_path::Union{Nothing, String, Bool} = nothing,
ntasks::Int = 0,
http_kwargs::NamedTuple = NamedTuple())
Scans a GitHub repository, downloads all the file contents, and combines them into a single large text document.
This function differs from `create_cheatsheet` in that it doesn't summarize or process the content into a cheatsheet,
but instead concatenates the raw content of all files that match the specified criteria.
Note: If you're getting rate limited by GitHub API, request a personal access token and set it as `ENV["GITHUB_API_KEY"]` (raised your limit to 5000 requests per hour).
# Arguments
- `repo::GitHubRepo`: The repository to scan.
- `verbose::Bool`: Whether to print verbose output.
- `save_path`: If provided, saves the collated content to this file path. If `true`, the content is saved to a subdirectory called `llm-cheatsheets` in the current working directory.
- `http_kwargs::NamedTuple`: Additional keyword arguments to pass to the `github_api` function influencing the HTTP requests.
- `ntasks::Int`: The number of tasks to use for the asynchronous processing. If `0`, the number of tasks is set to the `asyncmap` default.
# Returns
- `String`: The collated content of all scanned files and their contents in the repository.
"""
function Base.collect(
repo::GitHubRepo;
verbose::Bool = true,
save_path::Union{Nothing, String, Bool} = nothing,
ntasks::Int = 0,
http_kwargs::NamedTuple = NamedTuple()
)
start_time = time()
all_file_contents = Dict{Symbol, AbstractString}[]
verbose &&
@info "Scanning the following paths: $(join(repo.paths, ", ")) and file types: $(join(repo.file_types, ", "))"
for path in repo.paths
files = scan_github_path(repo, path; verbose, http_kwargs)
if isempty(files)
@warn "No files found in path: $path"
continue
end
asyncmap(files; ntasks) do file
try
response = github_api(file[:download_url]; http_kwargs...)
content = String(response.body)
push!(all_file_contents,
Dict(:name => file[:name], :content => content, :type => "FILE"))
catch e
@warn "Error processing $(file[:name]): $e"
end
end
end
if isempty(all_file_contents)
error("No files were successfully processed in any folder. Validate the paths and file types (Paths: $(join(repo.paths, ", ")), File types: $(join(repo.file_types, ", ")))")
end
collated_content = collate_files(all_file_contents)
if save_path !== nothing
if save_path === true
save_path = "collection_$(replace(repo.name, ".jl"=>"")).txt"
end
mkpath(dirname(save_path))
open(save_path, "w") do io
write(io, collated_content)
end
verbose && @info "Collated content saved to $save_path"
end
verbose &&
@info "Repository content collated. Duration: $(round(time() - start_time, digits = 1)) seconds."
return collated_content
end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 2840 |
"""
summarize_file(file_info::AbstractDict; model = "gpt4o",
special_instructions::AbstractString = "None.\n",
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = nothing,
verbose::Bool = true, http_kwargs::NamedTuple = NamedTuple())
Summarizes the content of a file in a GitHub repository.
# Arguments
- `file_info::AbstractDict`: The file information from the GitHub API. Requires `:name` and `:download_url` fields.
- `model::String`: The model to use for the LLM call.
- `special_instructions::AbstractString`: Special instructions for the AI to tweak the output.
- `cost_tracker::Union{Nothing, Threads.Atomic{<:Real}}`: A tracker to record the cost of the LLM calls.
- `verbose::Bool`: Whether to print verbose output.
- `http_kwargs::NamedTuple`: Additional keyword arguments to pass to the `github_api` function.
# Returns
- `Dict`: A dictionary with the file name (`:name` field), the content (`:content` field), and the type (`:type` field).
"""
function summarize_file(file_info::AbstractDict; model = "gpt4o",
special_instructions::AbstractString = "None.\n",
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = nothing,
verbose::Bool = true, http_kwargs::NamedTuple = NamedTuple())
@assert !isempty(get(file_info, :name, "")) "File name is empty for item: $(file_info)"
@assert !isempty(get(file_info, :download_url, "")) "Download URL is empty for $(file_info[:name])"
##
resp = github_api(file_info[:download_url]; http_kwargs...)
body = String(resp.body)
template = if endswith(file_info[:name], ".jl")
:FileSumarizerJuliaScript
elseif endswith(file_info[:name], ".md")
:FileSumarizerMarkdown
else
:FileSumarizerGeneral
end
## Run the LLM call to summarize the file
response = aigenerate(
template; content = body, model = model, verbose, special_instructions)
!isnothing(cost_tracker) && Threads.atomic_add!(cost_tracker, response.cost)
return Dict(:name => file_info[:name], :content => response.content, :type => "SUMMARY")
end
"""
collate_files(file_contents::AbstractVector{<:AbstractDict})
Collates the file contents into a single string.
# Arguments
- `file_contents::AbstractVector{<:AbstractDict}`: The contents of the files in the repository. Requires `:name` and `:content` fields.
# Returns
- `String`: A string with the concatenated file names and contents.
"""
function collate_files(file_contents::AbstractVector{<:AbstractDict})
@assert !isempty(file_contents) "No files provided"
@assert all(haskey(file, :name) && haskey(file, :content) for file in file_contents) "File contents must have :name and :content fields"
return join(["""<file name="$(file[:name])">
$(file[:content])
</file>""" for file in file_contents], "\n\n")
end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 5995 |
"""
GitHubRepo(url::String; paths = ["src", "docs/src", "README.md"],
file_types = [".jl", ".md"])
Creates a `GitHubRepo` object to represent a target GitHub repository.
# Arguments
- `url::String`: The URL of the GitHub repository.
- `paths::Vector{String}`: The folders and files to scan.
- `file_types::Vector{String}`: The file types to accept in the scan.
# Fields
- `owner::String`: The owner of the repository.
- `name::String`: The name of the repository.
- `url::String`: The URL of the repository.
- `paths::Vector{String}`: The folders and files to scan.
- `file_types::Vector{String}`: The file types to accept in the scan.
Note: Files and folders are scanned recursively.
Key methods: `scan_github_path`, `create_cheatsheet`, `collect`.
- `scan_github_path` is used to scan the repository and get the list of all relevant files.
- `create_cheatsheet` is used to create a cheatsheet from the repository.
- `collect` is used to collect the repository content into a single string (no summarization).
# Example
```julia
repo = GitHubRepo("https://github.com/username/repository")
files = scan_github_path(repo)
```
Let's create a cheatsheet and auto-save it to a file:
```julia
repo = GitHubRepo("https://github.com/username/repository")
cheatsheet = create_cheatsheet(repo; save_path = true)
```
Let's collect all the files in the repository (eg, for LLM calls):
```julia
repo = GitHubRepo("https://github.com/username/repository")
collated = collect(repo)
```
"""
struct GitHubRepo
owner::String
name::String
url::String
paths::Vector{String}
file_types::Vector{String}
function GitHubRepo(url::String; paths = ["src", "docs/src", "README.md"],
file_types = [".jl", ".md"])
parts = split(rstrip(url, '/'), '/')
if length(parts) < 5 || parts[3] != "github.com"
throw(ArgumentError("Invalid GitHub URL"))
end
new(parts[4], parts[5], url, paths, file_types)
end
end
"""
github_api(url::String; api_key::String=GITHUB_API_KEY, retries::Int=10)
Makes a GET request to the GitHub API with the specified URL.
# Arguments
- `url::String`: The GitHub API endpoint URL.
- `api_key::String`: The GitHub API key. Defaults to the global GITHUB_API_KEY.
- `retries::Int`: The number of retry attempts for the request. Defaults to 10.
- `kwargs`: Additional keyword arguments to pass to `HTTP.get`.
# Returns
- `HTTP.Response`: The response from the GitHub API.
- `JSON3.Object`: The parsed JSON response body.
# Throws
- `HTTP.ExceptionRequest.StatusError`: If the request fails after all retries.
"""
function github_api(
url::String; api_key::String = GITHUB_API_KEY, retries::Int = 10, kwargs...)
headers = [
"X-GitHub-Api-Version" => "2022-11-28"
]
if !isempty(api_key)
push!(headers, "Authorization" => "Bearer $api_key")
end
response = HTTP.get(url; headers = headers, retries = retries, kwargs...)
if response.status != 200
error("Failed to fetch data in $url: HTTP $(response.status)")
end
return response
end
"""
scan_github_path(repo::GitHubRepo, path::String; verbose = true,
http_kwargs::NamedTuple = NamedTuple())
scan_github_path(repo::GitHubRepo; verbose = true,
http_kwargs::NamedTuple = NamedTuple())
Scans a specific path in a GitHub repository and returns a list of files it contains that meet the criteria in `repo`.
Scans any nested folders recursively.
Note: If you're getting rate limited by GitHub, set the API key in `ENV["GITHUB_API_KEY"]`.
# Arguments
- `repo::GitHubRepo`: The repository to scan.
- `path::String`: The path to scan in the repository. If path is not provided, it will scan all paths in the repo object.
- `verbose::Bool`: Whether to print verbose output.
- `http_kwargs::NamedTuple`: Additional keyword arguments to pass to `github_api`.
# Returns
- `Vector{JSON3.Object}`: A list of files and folders in the specified path.
"""
function scan_github_path(repo::GitHubRepo, path::String; verbose = true,
http_kwargs::NamedTuple = NamedTuple())
## Make API call
url = "https://api.github.com/repos/$(repo.owner)/$(repo.name)/contents/$path"
resp = github_api(url; http_kwargs...)
body = JSON3.read(resp.body)
## Parse the response
files = JSON3.Object[]
folders = String[]
if body isa AbstractDict
body[:type] == "file" && push!(files, body)
else
for item in body
if item[:type] == "file"
push!(files, item)
elseif item[:type] == "dir"
push!(folders, path * "/" * item[:name])
end
end
end
## Filter out files that are not in the file_types
if !isempty(repo.file_types)
filter!(
file -> any(haskey(file, :name) && endswith(file[:name], ext)
for ext in repo.file_types), files)
end
verbose && @info "Found $(length(files)) files and $(length(folders)) folders in $path"
## Recursively scan sub-folders
while !isempty(folders)
folder = pop!(folders)
files_ = scan_github_path(repo, folder; verbose, http_kwargs)
append!(files, files_)
end
return files
end
function scan_github_path(repo::GitHubRepo; verbose = true,
http_kwargs::NamedTuple = NamedTuple())
start_time = time()
verbose && @info "Scanning all files in $(repo.owner)/$(repo.name)"
all_files = JSON3.Object[]
verbose &&
@info "Will scan the following paths: $(join(repo.paths, ", ")) and file types: $(join(repo.file_types, ", "))"
for path in repo.paths
files = scan_github_path(repo, path; verbose, http_kwargs)
if isempty(files)
@warn "No files found in path: $path"
continue
end
append!(all_files, files)
end
verbose &&
@info "Scanned $(length(all_files)) files in $(round(time() - start_time, digits = 1)) seconds."
return all_files
end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 2099 | # Requires mocking
# @testset "create_cheatsheet" begin
# # Test create_cheatsheet with mock data
# repo = GitHubRepo("https://github.com/username/repository")
# mock_file_contents = [
# Dict(:name => "file1.jl", :content => "# File 1 content"),
# Dict(:name => "file2.md", :content => "# File 2 content")
# ]
# # Test without saving
# cheatsheet = create_cheatsheet(repo, mock_file_contents)
# @test typeof(cheatsheet) == String
# @test !isempty(cheatsheet)
# # Test with saving (using a temporary directory)
# temp_dir = mktempdir()
# save_path = joinpath(temp_dir, "test_cheatsheet.md")
# cheatsheet_saved = create_cheatsheet(repo, mock_file_contents; save_path = save_path)
# @test isfile(save_path)
# @test read(save_path, String) == cheatsheet_saved
# end
# Requires mocking
# @testset "collect" begin
# # Test collect function
# repo = GitHubRepo("https://github.com/username/repository")
# # Mock the scan_github_path and github_api functions
# function mock_scan_github_path(repo, path; kwargs...)
# [Dict(:name => "file1.jl", :download_url => "https://example.com/file1.jl")]
# end
# function mock_github_api(url; kwargs...)
# (body = "File content")
# end
# # Apply the mocks
# original_scan = LLMCheatsheets.scan_github_path
# original_api = LLMCheatsheets.github_api
# LLMCheatsheets.scan_github_path = mock_scan_github_path
# LLMCheatsheets.github_api = mock_github_api
# # Test collection
# collected_content = collect(repo)
# @test contains(collected_content, "file1.jl")
# @test contains(collected_content, "File content")
# # Test saving collected content
# temp_dir = mktempdir()
# save_path = joinpath(temp_dir, "test_collection.txt")
# collect(repo; save_path = save_path)
# @test isfile(save_path)
# @test read(save_path, String) == collected_content
# # Restore original functions
# LLMCheatsheets.scan_github_path = original_scan
# LLMCheatsheets.github_api = original_api
# end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 1935 | using LLMCheatsheets
# @testset "summarize_file" begin
# # Test summarize_file function
# mock_file_info = Dict(
# :name => "test_file.jl",
# :download_url => "https://example.com/test_file.jl"
# )
# # Mock the github_api and aigenerate functions
# function mock_github_api(url; kwargs...)
# "Mock file content"
# end
# function mock_aigenerate(template; kwargs...)
# (content = "Summarized content", cost = 0.1)
# end
# # Apply the mocks
# original_api = LLMCheatsheets.github_api
# original_aigenerate = LLMCheatsheets.aigenerate
# LLMCheatsheets.github_api = mock_github_api
# LLMCheatsheets.aigenerate = mock_aigenerate
# # Test summarization
# summary = summarize_file(mock_file_info)
# @test summary[:file] == "test_file.jl"
# @test summary[:content] == "Summarized content"
# @test summary[:type] == "SUMMARY"
# # Test cost tracking
# cost_tracker = Threads.Atomic{Float64}(0.0)
# summarize_file(mock_file_info; cost_tracker = cost_tracker)
# @test cost_tracker[] ≈ 0.1
# # Restore original functions
# LLMCheatsheets.github_api = original_api
# LLMCheatsheets.aigenerate = original_aigenerate
# end
@testset "collate_files" begin
# Test collate_files function
mock_file_contents = [
Dict(:name => "file1.jl", :content => "Content of file 1"),
Dict(:name => "file2.md", :content => "Content of file 2")
]
collated = collate_files(mock_file_contents)
@test contains(collated, "<file name=\"file1.jl\">")
@test contains(collated, "<file name=\"file2.md\">")
@test contains(collated, "Content of file 1")
@test contains(collated, "Content of file 2")
# Test with empty input
@test_throws AssertionError collate_files(Dict[])
# Test with invalid input
@test_throws AssertionError collate_files([Dict(:invalid => "data")])
end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 1972 | using LLMCheatsheets: GitHubRepo, github_api, scan_github_path
@testset "GitHubRepo" begin
# Test GitHubRepo constructor
@test_throws ArgumentError GitHubRepo("https://invalid-url.com")
repo = GitHubRepo("https://github.com/username/repository")
@test repo.owner == "username"
@test repo.name == "repository"
@test repo.url == "https://github.com/username/repository"
@test repo.paths == ["src", "docs/src", "README.md"]
@test repo.file_types == [".jl", ".md"]
# Test with custom paths and file types
repo_custom = GitHubRepo("https://github.com/username/repository";
paths = ["custom_path"],
file_types = [".txt"])
@test repo_custom.paths == ["custom_path"]
@test repo_custom.file_types == [".txt"]
end
@testset "github_api" begin
# Test successful API call
response = github_api("https://api.github.com/repos/octocat/Hello-World/contents/README")
@test response.status == 200
body = JSON3.read(response.body)
@test haskey(body, :name)
# Test API call with invalid URL
@test_throws Exception github_api("https://api.github.com/invalid")
end
@testset "scan_github_path" begin
# Test scanning a valid path
repo = GitHubRepo("https://github.com/octocat/Hello-World"; file_types = [])
files = scan_github_path(repo, "README")
@test length(files) > 0
@test all(file -> haskey(file, :name), files)
@test all(file -> haskey(file, :download_url), files)
# Test scanning with invalid file types filter
repo = GitHubRepo("https://github.com/octocat/Hello-World"; file_types = [".md"])
@test isempty(scan_github_path(repo, ""))
# Scan all paths in the repo
repo = GitHubRepo(
"https://github.com/octocat/Hello-World"; file_types = [], paths = ["README"])
files = scan_github_path(repo)
@test length(files) > 0
@test all(file -> haskey(file, :name), files)
@test all(file -> haskey(file, :download_url), files)
end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | code | 359 | using Test, JSON3
using LLMCheatsheets
using Mocking
using PromptingTools
const PT = PromptingTools
using Aqua
Mocking.activate()
@testset "LLMCheatsheets.jl" begin
@testset "Code quality (Aqua.jl)" begin
Aqua.test_all(LLMCheatsheets)
end
include("github.jl")
include("cheatsheet_creation.jl")
include("file_processing.jl")
end
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 319 | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
### Fixed
## [0.1.0]
Initial release. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 6609 | # LLMCheatsheets.jl
[](https://svilupp.github.io/LLMCheatsheets.jl/stable/)
[](https://svilupp.github.io/LLMCheatsheets.jl/dev/)
[](https://github.com/svilupp/LLMCheatsheets.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/svilupp/LLMCheatsheets.jl)
[](https://github.com/JuliaTesting/Aqua.jl)
**LLMCheatsheets.jl** is a Julia package that makes it easy and instant to teach AI models about new packages and repositories by creating cheatsheets from GitHub repositories. This tool bridges the gap between human-readable documentation and AI-friendly knowledge representation, allowing for seamless integration with language models and AI assistants.
By default, we take a subset of the folders and files in the provided repository and summarize them using an LLM into a single cheatsheet.
## Features
- **Instant cheatsheet generation** from GitHub repositories.
- **AI-friendly knowledge representation** by summarizing code and documentation (or just collate all the raw files into a single string).
- **Easy integration** with language models and AI assistants (just copy the cheatsheet into your prompt).
- **Support for any package** and easier to start than Retrieval Augmented Generation (RAG).
## Installation
To install LLMCheatsheets.jl, use the Julia package manager and the repo URL (it's not registered yet):
```julia
using Pkg
Pkg.add(url = "https://github.com/svilupp/LLMCheatsheets.jl")
```
> [!TIP]
> If you encounter rate limits when accessing the GitHub API, you can set up a personal access token and set it as an environment variable `GITHUB_API_KEY` to increase your request limit to 5000 per hour.
## Quick Start
Here's a basic example of how to use LLMCheatsheets.jl to create a cheatsheet for a GitHub repository.
```julia
using LLMCheatsheets
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl")
create_cheatsheet(repo; save_path = true);
```
With `save_path = true`, the cheatsheet will be saved to folder `llm-cheatsheets` in the current working directory.
**What happens behind the scenes:**
1. **Scanning the Repository:** The repository is scanned to find all relevant files that match `repo.paths` and `repo.file_types`.
2. **Summarizing Files:** Each file is summarized using an LLM.
3. **Generating Cheatsheet:** The summaries are combined to generate a comprehensive cheatsheet.
For a low-level interface to generate the files individually and process them yourself, see `examples/create_for_promptingtools.jl`.
Sometimes you might want to just download the files without summarizing them. You can do that with `collect` function.
```julia
files_str = collect(repo)
```
`files_str` will be a string with all scanned files concatenated together.
To use it in ChatGPT or Claude.ai, use `clipboard` functionality to copy it to clipboard - `files_str|>clipboard`.
By default, the files scanned and downloaded are `repo.paths` and `repo.file_types`, respectively.
## Advanced Usage
### Customizing scanned paths and file types
By default, `repo.paths` includes `["src", "docs/src", "README.md"]`, and `repo.file_types` includes `[".jl", ".md"]`. You can customize these when creating the `GitHubRepo` object:
Eg, adding a folder `examples` and `.txt` files to customize what we will summarize:
```julia
repo = GitHubRepo("https://github.com/username/repository"; paths = ["examples", "README.md"], file_types = [".jl", ".md", ".txt"])
```
### Using a different LLM
You can use a different LLM by passing the `model` argument to the functions.
```julia
create_cheatsheet(repo; save_path = true, model = "gpt4om")
```
### Adding Special Instructions
You can provide special instructions to guide the AI in generating the cheatsheet:
```julia
create_cheatsheet(repo; special_instructions = "Focus on the data structures and their interactions.")
```
### Using PromptingTools.jl to Ask Questions
You can simply export also ai* functions from PromptingTools.jl to use them with LLMCheatsheets.jl.
```julia
using LLMCheatsheets
# Re-export aigenerate, pprint from PromptingTools
using LLMCheatsheets: aigenerate, pprint
# Or import PromptingTools directly
# using PromptingTools
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl"; paths = ["docs/src", "README.md"])
files_str = collect(repo)
msg = aigenerate("Read through these files: $(files_str)\n\nAnswer the question: What is the function for creating prompt templates?")
pprint(msg)
```
````plaintext
The function for creating prompt templates in the `PromptingTools.jl` package is `create_template`. This function allows you to define a prompt with placeholders and save it for later use. The syntax is:
```julia
create_template(; user=<user prompt>,
system=<system prompt>, load_as=<template name>)
```
This function generates a vector of messages, which you can use directly in the `ai*` functions. If you provide the `load_as` argument, it will also register the template in the template store,
allowing you to access it later using its name.
````
## Frequently Asked Questions
### I am getting rate-limited by LLM providers
If you are getting rate-limited by LLM providers, you can decrease the number of concurrent summarization tasks in `create_cheatsheet` by setting a lower number like `ntasks=5` or `ntasks=2` (depends on your API tier).
### I am getting rate-limited by GitHub API
Set up a personal access token and set it as `ENV["GITHUB_API_KEY"]`.
It will be automatically loaded into a variable `LLMCheatsheets.GITHUB_API_KEY`.
### How do I set up a personal access token for GitHub API?
You can set up a personal access token for GitHub API by following these steps:
1. Go to your [GitHub settings](https://github.com/settings/tokens).
2. Click on "Personal access tokens".
3. Click on "Generate new token".
Then you can set it as `ENV["GITHUB_API_KEY"]` or `LLMCheatsheets.GITHUB_API_KEY`.
## Documentation
For more information about using LLMCheatsheets.jl, please refer to the [documentation](https://svilupp.github.io/LLMCheatsheets.jl/dev/).
## Issues and Support
If you encounter any issues or have questions, please [open an issue](https://github.com/svilupp/LLMCheatsheets.jl/issues) on the GitHub repository. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 204 | ```@meta
CurrentModule = LLMCheatsheets
```
# API Reference
API reference for [LLMCheatsheets](https://github.com/svilupp/LLMCheatsheets.jl).
```@index
```
```@autodocs
Modules = [LLMCheatsheets]
```
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5603 | # LLMCheatsheets.jl Documentation
**LLMCheatsheets.jl** is a Julia package that makes it easy and instant to teach AI models about new packages and repositories by creating cheatsheets from GitHub repositories. This tool bridges the gap between human-readable documentation and AI-friendly knowledge representation, allowing for seamless integration with language models and AI assistants.
By default, we take a subset of the folders and files in the provided repository and summarize them using an LLM into a single cheatsheet.
## Features
- **Instant cheatsheet generation** from GitHub repositories.
- **AI-friendly knowledge representation** by summarizing code and documentation (or just collate all the raw files into a single string).
- **Easy integration** with language models and AI assistants (just copy the cheatsheet into your prompt).
- **Support for any package** and easier to start than Retrieval Augmented Generation (RAG).
## Installation
To install LLMCheatsheets.jl, use the Julia package manager and the repo URL (it's not registered yet):
```julia
using Pkg
Pkg.add(url = "https://github.com/svilupp/LLMCheatsheets.jl")
```
> [!TIP]
> If you encounter rate limits when accessing the GitHub API, you can set up a personal access token and set it as an environment variable `GITHUB_API_KEY` to increase your request limit to 5000 per hour.
## Quick Start
Here's a basic example of how to use LLMCheatsheets.jl to create a cheatsheet for a GitHub repository.
```julia
using LLMCheatsheets
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl")
create_cheatsheet(repo; save_path = true);
```
With `save_path = true`, the cheatsheet will be saved to folder `llm-cheatsheets` in the current working directory.
**What happens behind the scenes:**
1. **Scanning the Repository:** The repository is scanned to find all relevant files that match `repo.paths` and `repo.file_types`.
2. **Summarizing Files:** Each file is summarized using an LLM.
3. **Generating Cheatsheet:** The summaries are combined to generate a comprehensive cheatsheet.
For a low-level interface to generate the files individually and process them yourself, see `examples/create_for_promptingtools.jl`.
Sometimes you might want to just download the files without summarizing them. You can do that with `collect` function.
```julia
files_str = collect(repo)
```
`files_str` will be a string with all scanned files concatenated together.
To use it in ChatGPT or Claude.ai, use `clipboard` functionality to copy it to clipboard - `files_str|>clipboard`.
By default, the files scanned and downloaded are `repo.paths` and `repo.file_types`, respectively.
## Advanced Usage
### Customizing scanned paths and file types
By default, `repo.paths` includes `["src", "docs/src", "README.md"]`, and `repo.file_types` includes `[".jl", ".md"]`. You can customize these when creating the `GitHubRepo` object:
Eg, adding a folder `examples` and `.txt` files to customize what we will summarize:
```julia
repo = GitHubRepo("https://github.com/username/repository"; paths = ["examples", "README.md"], file_types = [".jl", ".md", ".txt"])
```
### Using a different LLM
You can use a different LLM by passing the `model` argument to the functions.
```julia
create_cheatsheet(repo; save_path = true, model = "gpt4om")
```
### Adding Special Instructions
You can provide special instructions to guide the AI in generating the cheatsheet:
```julia
create_cheatsheet(repo; special_instructions = "Focus on the data structures and their interactions.")
```
### Using PromptingTools.jl to Ask Questions
You can simply export also ai* functions from PromptingTools.jl to use them with LLMCheatsheets.jl.
```julia
using LLMCheatsheets
# Re-export aigenerate, pprint from PromptingTools
using LLMCheatsheets: aigenerate, pprint
# Or import PromptingTools directly
# using PromptingTools
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl"; paths = ["docs/src", "README.md"])
files_str = collect(repo)
msg = aigenerate("Read through these files: $(files_str)\n\nAnswer the question: What is the function for creating prompt templates?")
pprint(msg)
```
````plaintext
The function for creating prompt templates in the `PromptingTools.jl` package is `create_template`. This function allows you to define a prompt with placeholders and save it for later use. The syntax is:
```julia
create_template(; user=<user prompt>,
system=<system prompt>, load_as=<template name>)
```
This function generates a vector of messages, which you can use directly in the `ai*` functions. If you provide the `load_as` argument, it will also register the template in the template store,
allowing you to access it later using its name.
````
## Frequently Asked Questions
### I am getting rate-limited by LLM providers
If you are getting rate-limited by LLM providers, you can decrease the number of concurrent summarization tasks in `create_cheatsheet` by setting a lower number like `ntasks=5` or `ntasks=2` (depends on your API tier).
### I am getting rate-limited by GitHub API
Set up a personal access token and set it as `ENV["GITHUB_API_KEY"]`.
It will be automatically loaded into a variable `LLMCheatsheets.GITHUB_API_KEY`.
### How do I set up a personal access token for GitHub API?
You can set up a personal access token for GitHub API by following these steps:
1. Go to your [GitHub settings](https://github.com/settings/tokens).
2. Click on "Personal access tokens".
3. Click on "Generate new token".
Then you can set it as `ENV["GITHUB_API_KEY"]` or `LLMCheatsheets.GITHUB_API_KEY`.
| LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5713 | # **AIHelpMe.jl Cheatsheet**
## **Package Name**: AIHelpMe.jl
## **URL**: [AIHelpMe.jl GitHub Repository](https://github.com/svilupp/AIHelpMe.jl)
---
## **Purpose**
**AIHelpMe.jl** integrates advanced AI models with Julia's extensive documentation to provide tailored coding guidance. It enhances productivity by offering context-aware answers directly within the Julia environment.
---
## **Installation**
To install AIHelpMe.jl, open your Julia REPL and run:
```julia
using Pkg
Pkg.add("AIHelpMe")
```
**Prerequisites:**
- Julia 1.10 or later.
- OpenAI API Key (set as an environment variable `OPENAI_API_KEY`).
- Cohere API Key and Tavily API Key for additional functionalities.
---
## **Usage Overview**
### **Basic Usage**
To start using AIHelpMe, import the package:
```julia
using AIHelpMe
```
Ask a question:
```julia
aihelp("How do I implement quicksort in Julia?")
```
Pretty-print the response:
```julia
using AIHelpMe: pprint
result = aihelp("How do I implement quicksort in Julia?", return_all=true)
pprint(result)
```
### **Using the Macro**
```julia
aihelp"how to implement quicksort in Julia?"
```
### **Follow-up Questions**
```julia
aihelp!"Can you elaborate on the `sort` function?"
```
Use the `!` for follow-up questions.
---
## **Main Features and Functions**
### **1. aihelp**
Generates a response for a given question using RAG approach.
#### **Usage with Explicit RAG Config and Chunk Index:**
```julia
using AIHelpMe: aihelp, pprint, build_index
# Create an index that contains Makie.jl documentation
index = build_index(...)
# Define the question
question = "How to make a barplot in Makie.jl?"
# Get the response
msg = aihelp(index, question)
println(msg)
# Optionally, get detailed response and pretty-print
result = aihelp(index, question; return_all = true)
pprint(result)
```
#### **Usage with Pre-loaded Knowledge Pack:**
```julia
using AIHelpMe: aihelp, pprint
# Load Makie knowledge pack
AIHelpMe.load_index!(:makie)
# Define the question
question = "How to make a barplot in Makie.jl?"
# Get the response without providing the index explicitly
msg = aihelp(question)
println(msg)
# Optionally, get detailed response and pretty-print
result = aihelp(question; return_all = true)
pprint(result)
```
#### **Advanced Usage with Web Search and Reranking:**
```julia
using AIHelpMe: aihelp, pprint
# Define the question
question = "How to make a barplot in Makie.jl?"
# Use search and rerank functionalities and pretty-print the result
result = aihelp(question; search = true, rerank = true, return_all = true)
pprint(result)
```
---
### **2. Macros:**
#### **@aihelp_str**
```julia
using AIHelpMe
# Example usage
@aihelp_str "Give me an example of using the aihelp function"
```
#### **@aihelp!_str**
```julia
using AIHelpMe
# Example usage
@aihelp!_str "Show the AIHelpMe usage instructions"
```
---
### **3. Functions from Included Files:**
#### **From `utils.jl`:**
- `remove_pkgdir(filepath::AbstractString, mod::Module)`: Cleans up the package directory from the file path.
#### **From `user_preferences.jl`:**
- `set_preferences!(pairs::Pair{String, <:Any}...)`: Sets user preferences.
- `get_preferences(key::String)`: Fetches the current setting for a given preference key.
---
### **4. Managing Preferences:**
#### **Setting Preferences:**
```julia
AIHelpMe.set_preferences!("MODEL_CHAT" => "llama3", "MODEL_EMBEDDING" => "nomic-embed-text", "EMBEDDING_DIMENSION" => 0)
```
#### **Getting Preferences:**
```julia
println(AIHelpMe.get_preferences("MODEL_CHAT"))
```
---
### **5. Handling Indices:**
#### **Load Index:**
```julia
AIHelpMe.load_index!(file_path::AbstractString) # From file path
AIHelpMe.load_index!(index::RT.AbstractChunkIndex) # From an index object
AIHelpMe.load_index!([:julia, :makie]) # From predefined artifacts
```
#### **Update Index:**
```julia
AIHelpMe.update_index() |> AIH.load_index!
# Or for an explicit index
index = AIHelpMe.update_index(index)
```
#### **Build Index:**
```julia
index = AIHelpMe.build_index([Module1, Module2], verbose=2)
```
---
## **Detailed Examples:**
### **Generating a Response:**
1. **Basic Example:**
```julia
using AIHelpMe: aihelp
response = aihelp("What is a DataFrame?")
println(response)
```
2. **Using a Macro:**
```julia
using AIHelpMe
aihelp"How to implement a quicksort in Julia?"
```
3. **Advanced Use with Web Search:**
```julia
using AIHelpMe: aihelp, pprint
# Use advanced features
question = "How to create a heatmap in Makie.jl?"
result = aihelp(question; search = true, rerank = true, return_all = true)
pprint(result)
```
---
## **Tips and Best Practices:**
1. **Environment Setup:**
- Set `OPENAI_API_KEY` environment variable.
2. **Function Arguments:**
- Prefer keyword arguments for clarity.
3. **Customize RAG Pipelines:**
- To include specific knowledge from loaded packages or additional context.
- `update_pipeline!(:bronze)` initializes a basic pipeline.
4. **Debugging and Context Inspection:**
- Use `pprint(last_result())` to debug the AI responses and context provided.
5. **Local Model Support:**
- For local models, such as Ollama models, refer to the specific usage guides.
---
## **Additional Resources:**
For further reading, refer to the following resources:
- [AIHelpMe.jl Documentation](https://github.com/svilupp/AIHelpMe.jl)
- [PromptingTools.jl RAG Tools](https://svilupp.github.io/PromptingTools.jl/dev/extra_tools/rag_tools_intro)
- [Julia Documentation](https://docs.julialang.org/)
---
This cheatsheet provides a comprehensive guide for newcomers to start using AIHelpMe.jl effectively. Happy coding! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 3829 | # AlgebraOfGraphics.jl Cheatsheet
## Package Name
**AlgebraOfGraphics.jl**
## URL
[AlgebraOfGraphics.jl GitHub Repository](https://github.com/MakieOrg/AlgebraOfGraphics.jl)
## Purpose
AlgebraOfGraphics is a Julia package designed to create visualizations using an algebraic approach to the grammar of graphics. Inspired by R's `ggplot2`, it lets you build complex plots using simple algebraic combinations of data, mappings, and visual elements. The package integrates seamlessly with Makie for high-customization capabilities.
## Installation
### Prerequisites
Ensure you have Julia installed. Then, in your Julia REPL, run:
```julia
using Pkg
Pkg.add(["AlgebraOfGraphics", "CairoMakie", "PalmerPenguins", "DataFrames"])
```
## Getting Started
### Basic Usage Overview
#### Loading and Preparing Data
Load and clean your dataset:
```julia
using AlgebraOfGraphics, CairoMakie, PalmerPenguins, DataFrames
penguins = dropmissing(DataFrame(PalmerPenguins.load()))
```
#### Setting Themes
Customize the theme for your plots:
```julia
set_aog_theme!()
update_theme!(Axis = (; width = 150, height = 150))
```
#### Creating Basic Plots
##### Scatter Plot
```julia
spec = data(penguins) * mapping(:bill_length_mm, :bill_depth_mm)
draw(spec)
```
##### Adding Color by Species
```julia
by_color = spec * mapping(color = :species)
draw(by_color)
```
##### Adding Regression Lines
```julia
with_regression = by_color * (linear() + visual(alpha = 0.3))
draw(with_regression)
```
##### Facetted Plots
Facet the plot by the `sex` of penguins:
```julia
facetted = with_regression * mapping(col = :sex)
draw(facetted)
```
##### Customizing Color Palette
```julia
draw(facetted, scales(Color = (; palette = :Set1_3)))
```
## Main Features and Functions
### Data Preparation
#### `data`
Wraps a dataset for visualization.
**Usage:**
```julia
df = (x = 1:10, y = rand(10))
data(df)
```
### Mapping Variables to Plot Attributes
#### `mapping`
Associates data columns to plot aesthetics.
**Usage:**
```julia
mapping(:x, :y, color = :group)
```
### Visual Adjustments
#### `visual`
Defines visual characteristics for the plot.
**Usage:**
```julia
visual(Scatter, alpha = 0.5)
```
### Statistical Analyses
#### Histograms
**Function:** `histogram`
```julia
df = (x = randn(5000))
specs = data(df) * mapping(:x) * histogram(bins = 15)
draw(specs)
```
#### Density Plots
**Function:** `density`
```julia
df = (x = randn(5000), y = randn(5000))
specs = data(df) * mapping(:x, :y) * density(npoints = 50)
draw(specs)
```
#### Linear Regression
**Function:** `linear`
```julia
df = (x = 1:100, y = 2 * (1:100) .+ randn(100))
specs = data(df) * mapping(:x, :y) * (linear() + visual(Scatter))
draw(specs)
```
### Combining Layers
Use `*` to combine different data, mappings, and visuals into cohesive layers.
#### Example
```julia
df = (x = 1:10, y = rand(10))
layer1 = data(df) * mapping(:x, :y)
layer2 = visual(Scatter, color = :red)
combined_layer = layer1 * layer2
draw(combined_layer)
```
## Tips and Best Practices
1. **Modular Design**: Break down complex plots into simpler components using `data`, `mapping`, and `visual`.
2. **Debugging**: Verify each component individually before combining them.
3. **Consistent Themes**: Use `set_aog_theme!` and `update_theme!` to maintain visual consistency across plots.
## Additional Resources
- **Makie Documentation**: [Makie Documentation](https://docs.makie.org/stable/)
- **PalmerPenguins Documentation**: [PalmerPenguins.jl](https://github.com/mfalt/palmerpenguins.jl)
- **DataFrames.jl Documentation**: [DataFrames.jl](https://dataframes.juliadata.org/stable/)
By following this comprehensive cheatsheet, you should be well-equipped to start your journey with AlgebraOfGraphics and create effective and informative visualizations using Julia. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 4777 | # CSV.jl Cheatsheet
## Package Name
**CSV.jl**
## URL
[GitHub Repository](https://github.com/JuliaData/CSV.jl)
## Purpose
CSV.jl is a Julia package for handling delimited text data, such as CSV or TSV files. It provides high-performance functionalities for reading, writing, and manipulating CSV files with both ease and efficiency.
## Installation
To install CSV.jl, use the following command in the Julia REPL:
```julia
] add CSV
```
## Documentation
- **Stable Documentation**: [Stable](https://JuliaData.github.io/CSV.jl/stable)
- **Latest Documentation**: [Latest](https://JuliaData.github.io/CSV.jl/latest)
## Basic Usage
### Reading CSV Files
#### 1. Using `CSV.File`
Reads an entire delimited data input and returns a `CSV.File` object.
```julia
using CSV
# Reading from a file
file = CSV.File("path/to/file.csv")
for row in file
println(row)
end
# Access column data
first_row = file[1]
value = first_row[:col1] # Access column :col1 in first row
```
**Keyword Arguments:**
- `header`: Specifies how to determine column names.
- `delim`: Specifies the delimiter used to separate columns.
- `types`: Defines column types.
- `pool`: Controls whether columns are stored as `PooledArray`s.
#### 2. Using `CSV.read`
Reads and directly passes parsed data to sinks like DataFrames.
```julia
using CSV, DataFrames
# Reading into a DataFrame
df = CSV.read("path/to/file.csv", DataFrame)
```
#### 3. Using `CSV.Rows`
Consumes delimited data row by row with minimal memory footprint.
```julia
using CSV
rows = CSV.Rows("path/to/file.csv")
for row in rows
println(row[:col1])
end
```
#### 4. Using `CSV.Chunks`
Processes extremely large files in manageable chunks.
```julia
using CSV
chunks = CSV.Chunks("largefile.csv", ntasks=4)
for chunk in chunks
println(chunk.names)
end
```
#### 5. Handling Non-UTF-8 Character Encodings
```julia
using CSV, StringEncodings
# Read ISO-8859-1 encoded file
file = CSV.File(open("iso8859_encoded_file.csv", enc"ISO-8859-1"))
```
### Writing CSV Files
#### Using `CSV.write`
Writes data to a CSV file.
```julia
using CSV, DataFrames
df = DataFrame(Name=["Alice", "Bob"], Age=[25, 30])
CSV.write("output.csv", df)
```
**Keyword Arguments:**
- `delim`: Specifies the delimiter.
- `quote`: Determines quoting behavior.
- `dateformat`: Custom date format.
- `header`: Column names or boolean indicating whether to write column names.
#### Using `CSV.RowWriter`
Iteratively writes rows to an output.
```julia
using CSV, Tables
# Define schema
schema = Tables.Schema([:Name, :Age], [String, Int])
# Create an IO stream
io = open("output.csv", "w")
# Create RowWriter object
row_writer = CSV.RowWriter(io, schema)
# Write rows
write(row_writer, ("Alice", 25))
write(row_writer, ("Bob", 30))
# Close the stream
close(io)
```
## Advanced Usage
### Concatenating Multiple Inputs
```julia
using CSV
data = [
"a,b,c\n1,2,3\n4,5,6\n",
"a,b,c\n7,8,9\n10,11,12\n",
"a,b,c\n13,14,15\n16,17,18"
]
file = CSV.File(map(IOBuffer, data))
```
### Customizing Headers
```julia
# Custom header row
file = CSV.File("data.csv", header=2)
# Manually providing column names
file = CSV.File("data.csv", header=["a", "b", "c"])
# Multi-row headers
file = CSV.File("data.csv", header=[1, 2])
```
### Handling Specific Row and Column Requirements
```julia
# Skip to specific row
file = CSV.File("data.csv", skipto=4)
# Include/Exclude columns
file = CSV.File("data.csv", select=["name", "age"])
file = CSV.File("data.csv", drop=[2, 3])
# Limit number of rows
file = CSV.File("data.csv", limit=100)
```
### Parsing Delimited Data in a String
```julia
data = """
a,b,c
1,2,3
4,5,6
"""
file = CSV.File(IOBuffer(data))
```
### Handling Specific Data Types
```julia
# Custom missing strings
file = CSV.File("data.csv", missingstring=["NA", "NULL"])
# Specify column types
file = CSV.File("data.csv", types=Dict(1 => Float64, 2 => String))
```
## Tips and Best Practices
1. **Memory Efficiency:** Use `CSV.Rows` for iteration over large files to minimize memory usage.
2. **Multithreading:** Enable multithreading for large data files to improve parsing speed.
3. **Custom Delimiters:** Define custom delimiters, quote characters, and date formats using appropriate keyword arguments.
4. **Debugging:** Enable debugging during parsing for detailed information about the process (`debug=true`).
## Contributing and Questions
- **Contributions:** Contributions, feature requests, and suggestions are welcome.
- **Issue Reporting:** Open an issue on the [GitHub repository](https://github.com/JuliaData/CSV.jl/issues).
By following this cheatsheet, you can effectively use CSV.jl for various CSV file operations in Julia. For comprehensive examples and further details, refer to the official documentation linked above. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5250 | # DataFramesMeta.jl Cheatsheet
## Package Name:
**DataFramesMeta.jl**
## URL:
[DataFramesMeta.jl GitHub Repository](https://github.com/JuliaData/DataFramesMeta.jl)
---
## Purpose
**DataFramesMeta.jl** provides a suite of macros to streamline common data manipulation tasks on DataFrames in Julia. It simplifies operations like filtering, transforming, and summarizing data into more readable and convenient macro-based syntax, similar to R's `dplyr` and C#'s `LINQ`.
---
## Installation
You can install `DataFramesMeta.jl` using Julia's package manager:
1. Using Julia REPL:
```julia
import Pkg; Pkg.add("DataFramesMeta")
```
2. Using `Pkg` REPL mode (type `]` to enter):
```julia
add DataFramesMeta
```
---
## Usage Overview
To start using `DataFramesMeta.jl`, first ensure you have the necessary libraries:
```julia
using DataFrames
using DataFramesMeta
```
### Basic Example
```julia
df = DataFrame(a = [1, 2, 3], b = [4, 5, 6])
@select df c = :a + :b # This creates a new column `c` which is the sum of `a` and `b`.
```
---
## Main Features and Functions
### Macros Overview
1. **@with**
- **Purpose**: Simplifies DataFrame column manipulations within a block scope.
- **Usage**:
```julia
@with(df, :y .+ 1)
```
2. **@select**
- **Purpose**: Selects and possibly transforms columns.
- **Usage**:
```julia
@select df :x :y
@select df new_col = 2 * :x
```
3. **@transform**
- **Purpose**: Adds or modifies columns in a DataFrame.
- **Usage**:
```julia
@transform df :new_col = :x * 2
@transform! df :new_col = :x * 2 # In-place version.
```
4. **@subset**
- **Purpose**: Filters rows based on conditions.
- **Usage**:
```julia
@subset df :x .> 1
@rsubset df :x .> 1 # Keeps rows that do not satisfy the condition.
@subset! df :x .> 1 # In-place version.
```
5. **@orderby**
- **Purpose**: Sorts rows by specified columns.
- **Usage**:
```julia
@orderby df :x
```
6. **@combine**
- **Purpose**: Aggregates data by groups and summarizes.
- **Usage**:
```julia
@combine df avg_x = mean(:x)
```
7. **@groupby**
- **Purpose**: Groups DataFrame by specified columns.
- **Usage**:
```julia
@groupby df :a
```
8. **@eachrow**
- **Purpose**: Applies operations to each row.
- **Usage**:
```julia
df2 = @eachrow df begin
:new_col = :A + :B
end
@eachrow! df begin
:A = :A * 2
end # In-place version.
```
9. **@rename**
- **Purpose**: Renames columns.
- **Usage**:
```julia
@rename df :new_name = :old_name
@rename! df :new_name = :old_name # In-place version.
```
10. **@label! and @note!**
- **Purpose**: Attaches labels and notes to columns.
- **Usage**:
```julia
@label! df :wage = "Hourly wage (2015 USD)"
printlabels(df)
@note! df :wage = "Data source description"
printnotes(df)
```
### Handling Missing Values
- **@passmissing**
- **Purpose**: Ensures missing values are propagated through functions.
- **Usage**:
```julia
@transform df @passmissing @byrow :new_col = parse(Int, :x_str)
```
---
## Detailed Examples
### Chain Operations with `@chain`
Using `@chain` to pipeline multiple operations:
```julia
@chain df begin
@transform(:y = 10 * :x)
@subset(:a .> 2)
@groupby(:b)
@combine(:mean_x = mean(:x), :mean_y = mean(:y))
@orderby(:mean_x)
@select(:mean_x, :mean_y)
end
```
### Adding Metadata
Attach labels and notes to DataFrame columns:
```julia
@label! df :wage = "Hourly wage (2015 USD)"
@note! df :wage = """
Wage per hour in 2014 USD taken from ACS data.
"""
printlabels(df) # Pretty prints the labels.
printnotes(df) # Pretty prints the notes.
```
### Complex Operations
Combining multiple macros for advanced operations:
```julia
@groupby df :category begin
@transform :new_col = :original_col * 2
@combine :mean_val = mean(:new_col)
end
```
---
## Tips and Best Practices
1. **Use Macros for Readability**: Macros like `@select`, `@transform`, and `@subset` make the code more concise and easier to read.
2. **Chain Multiple Operations**: Use `@chain` to combine multiple DataFrame operations in a clean and readable format.
3. **Handle Missing Data**: Use `@passmissing` to ensure missing values do not cause errors in transformations.
4. **Label and Annotate**: Attach labels and notes to DataFrame columns to maintain data documentation and clarity.
---
## Additional Resources
- **Full Documentation**:
- [Stable Version](https://JuliaData.github.io/DataFramesMeta.jl/stable)
- [Development Version](https://JuliaData.github.io/DataFramesMeta.jl/dev)
- **DataFrames.jl**: The foundational package for DataFrames in Julia.
- **DataFramesMeta.jl GitHub Repository**: [DataFramesMeta.jl](https://github.com/JuliaData/DataFramesMeta.jl)
---
By following this cheatsheet, you should be well-equipped to start using DataFramesMeta.jl effectively for manipulating DataFrames in Julia. This tool will help you write cleaner and more efficient data transformation code. Enjoy your data manipulation with Julia! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5747 | # DataFrames.jl Cheatsheet
## Package Name
**DataFrames.jl**
## URL
[DataFrames.jl on GitHub](https://github.com/JuliaData/DataFrames.jl)
## Purpose
DataFrames.jl provides flexible and high-performance data manipulation capabilities akin to R's data.frames or Python's pandas, ideal for handling tabular data in Julia.
## Installation
```julia
using Pkg
Pkg.add("DataFrames")
```
### Check Installation
```julia
using DataFrames
Pkg.status("DataFrames")
```
### Testing Installation (Optional)
```julia
Pkg.test("DataFrames") # Warning: This can take more than 30 minutes.
```
## Usages Overview
To use DataFrames.jl, load the package after installation:
```julia
using DataFrames
```
## Creating DataFrames
### Constructors
#### Empty DataFrame:
```julia
df = DataFrame()
```
#### DataFrame with Columns:
```julia
df = DataFrame(a=1:3, b=["A", "B", "C"], c=1.0)
```
#### DataFrame from Named Tuple:
```julia
df = DataFrame((x=[1, 2, 3], y=[4, 5, 6]))
```
#### DataFrame from Dictionary:
```julia
datadict = Dict("Name" => ["John", "Jane"], "Age" => [23, 35])
df = DataFrame(datadict)
```
#### DataFrame from Matrix:
```julia
mat = [1 2 3; 4 5 6; 7 8 9]
df = DataFrame(mat, :auto)
```
### Basic Operations on DataFrames
#### Extract Columns
```julia
df[:Name] # Extract a column by name
df[:, :Name] # Extract column (return Vector)
df[!, :Name] # Extract column without copying
```
#### Get Column Names
```julia
names(df) # Returns column names as symbols
propertynames(df) # Alternative
```
#### Size and Description
```julia
size(df) # (nrow, ncol)
describe(df) # Descriptive statistics
first(df, 6) # First 6 rows
last(df, 6) # Last 6 rows
show(df, allrows=true) # Show all rows
```
### Modifying DataFrames
#### Add/Modify Columns
```julia
df.NewCol = [1, 2, 3] # Add a new column
df[:, :Name] = ["Jane", "John"] # Modify existing column by name
df[!, :Age] .= [30, 40, 50] # Modify in-place
```
#### Insert Columns
```julia
insertcols!(df, 2, :Middle => ["M", "N", "O"]) # Insert at position with scalar value
```
#### Remove Columns
```julia
select!(df, Not(:Middle)) # Remove column :Middle
```
### Filtering Rows
#### Basic Filtering
```julia
df[df.Age .> 30, :] # Rows where Age > 30
subset(df, :Age => x -> x .> 30) # Using subset function
```
#### Handling Missing Values
```julia
dropmissing(df) # Drop rows with any missing value
allowmissing!(df) # Allow missing in all columns
disallowmissing!(df) # Disallow missing in all columns
```
### Grouping and Combining
#### Grouping
```julia
grouped_df = groupby(df, :Gender)
```
#### Combining
```julia
combine(grouped_df, :Salary => mean => :AvgSalary) # Aggregation
transform(grouped_df, :Salary => mean => :AvgSalary) # Adding new columns
select(grouped_df, :Salary => mean => :AvgSalary) # Selecting columns
```
### Joins
#### Common Joins
```julia
df1 = DataFrame(ID=[1, 2], Name=["A", "B"])
df2 = DataFrame(ID=[2, 3], Age=[20, 30])
innerjoin(df1, df2, on=:ID) # Inner Join
leftjoin(df1, df2, on=:ID) # Left Join
rightjoin(df1, df2, on=:ID) # Right Join
outerjoin(df1, df2, on=:ID) # Outer Join
```
#### Adding Columns from a Join
```julia
leftjoin!(df1, DataFrame(ID=[1, 3], Info=["X", "Y"]), on=:ID) # In-place left join
```
### Reshaping Data
#### Wide to Long
```julia
stack(df, [:SepalLength, :SepalWidth])
```
#### Long to Wide
```julia
unstack(stacked_df, :id, :variable, :value)
```
## I/O Operations
### CSV Files
#### Reading CSV
```julia
using CSV
path = "path/to/file.csv"
df = CSV.read(path, DataFrame)
```
#### Writing CSV
```julia
CSV.write("output.csv", df)
```
### Handling Other Formats
Refer to packages like Arrow.jl, Feather.jl, Avro.jl, JSONTables.jl for other formats.
## Using Categorical Data
### CategoricalVector
```julia
using CategoricalArrays
v = ["A", "B", "A"]
cv = categorical(v)
```
### Levels and Reordering
```julia
levels(cv)
levels!(cv, ["B", "A"])
```
### Memory Optimization
```julia
compress(cv)
```
## Metadata Handling
### Table-Level Metadata
```julia
metadata!(df, "caption", "Table of Salaries")
metadata(df, "caption")
metadatakeys(df)
deletemetadata!(df, "caption")
emptymetadata!(df)
```
### Column-Level Metadata
```julia
colmetadata!(df, :Name, "description", "First Name")
colmetadata(df, :Name, "description")
colmetadatakeys(df, :Name)
deletecolmetadata!(df, :Name, "description")
emptycolmetadata!(df, :Name)
```
## Parallel Operations
### Multithreading
```julia
Pkg.test("DataFrames") # to ensure everything is set up
# Enable threading with "threads=true" in relevant functions
combine(groupby(df, :Gender), :Salary => mean => :AvgSalary, threads=true)
```
## Integration with Other Julia Packages
### Plotting
- **Plots.jl**
```julia
using Plots
plot(df.Salary)
```
- **Gadfly.jl**
```julia
using Gadfly
plot(df, x=:Age, y=:Salary, Geom.point)
```
### Machine Learning
- **MLJ.jl** for machine learning models integration.
```julia
using MLJ
# Example
model = @load DecisionTreeClassifier
```
## Additional Resources
### Tutorials
- [Julia Academy DataFrames.jl Course](https://juliaacademy.com/p/introduction-to-dataframes-jl)
- [DataFrames.jl Tutorial](https://github.com/bkamins/Julia-DataFrames-Tutorial)
- [DataFrames.jl Documentation](http://dataframes.juliadata.org/stable/)
### Community
- **Discourse**: [JuliaLang Discourse](https://discourse.julialang.org/)
- **GitHub Issues**: [Submit Issues](https://github.com/JuliaData/DataFrames.jl/issues)
This detailed cheatsheet outlines how to use DataFrames.jl effectively for data manipulation in Julia, helping new users start working with data frames quickly and efficiently. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5146 | # Genie.jl Cheat Sheet
## Package Name
**Genie.jl**
## URL
[Genie.jl GitHub Repository](https://github.com/GenieFramework/Genie.jl)
## Purpose
Genie.jl is a full-stack web framework for building modern web applications in Julia. It streamlines development by leveraging Julia's high performance, simplicity, and productivity features. Users can create, configure, and manage web applications efficiently using the provided modules, tools, and APIs.
## Installation
### Step-by-Step Instructions
1. **Enter Julia's package mode** by pressing `]` in the Julia REPL.
2. **Install Genie** by running:
```julia
pkg> add Genie
```
## Usage Overview
### Starting a New Application
1. **Create a new Genie application**:
```julia
using Genie
Genie.Generator.newapp("MyGenieApp")
```
2. **Navigate to the project directory** and start the server:
```sh
$ cd MyGenieApp
$ julia -e 'using Genie; up()'
```
3. **Visit** `http://127.0.0.1:8000` to see the Genie welcome page.
### Imports and Dependencies
Make sure to include necessary modules in your projects, such as:
```julia
using Genie, SearchLight, SearchLightSQLite
```
## Main Features and Functions
### HTTP Routing
Define routes and their handlers.
#### Example:
```julia
using Genie
route("/") do
"Hello, Genie!"
end
route("/json") do
Genie.Renderer.Json.json(Dict("message" => "Welcome to Genie!"))
end
up(8000)
```
### Templating
Render HTML, JSON, Markdown, and JavaScript templates.
#### HTML Example:
```julia
using Genie.Renderer.Html
route("/html") do
html("""
<html>
<head><title>Genie</title></head>
<body><h1>Hello, Genie!</h1></body>
</html>
""")
end
```
### Web Sockets
Enabling real-time communication with clients.
#### Example:
```julia
using Genie, Genie.Router
Genie.config.websockets_server = true
channel("/ws") do
@info "WebSocket message received"
end
up() # Start the server
```
## Database Integration
### SearchLight ORM
### Example:
Connect to SQLite and perform queries.
#### Configuring Connection
```yaml
# db/connection.yml
env: ENV["GENIE_ENV"]
dev:
adapter: SQLite
database: db/dev.sqlite
```
#### Defining Models
```julia
module MyModel
using SearchLight
@kwdef mutable struct User <: AbstractModel
id::DbId = DbId()
name::String
email::String
end
SearchLight.Model.metadata!(User)
end
```
#### Performing ORM Operations
```julia
using MyModel
user = User(name = "John Doe", email = "[email protected]")
save(user)
found_user = find(User, id = user.id)
println(found_user.name) # Output: John Doe
```
## Handling JSON Payloads
Parse JSON payloads in routes.
#### Example:
```julia
using Genie, Genie.Requests, Genie.Renderer.Json
route("/post", method = POST) do
data = jsonpayload()
json(:message => "Received", :data => data)
end
up(8000)
```
## File Uploads
Support for handling file uploads.
#### HTML Form for File Upload
```html
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>
```
#### Handling File Upload in Route
```julia
route("/upload", method = POST) do
if haspayloadfile(:file)
file = payloadfile(:file)
write("uploads/" * file.filename, file.data)
"File uploaded successfully!"
else
"No file uploaded."
end
end
```
## Authentication
Using `GenieAuthentication` for managing user authentication.
#### Example:
```julia
using GenieAuthentication
GenieAuthentication.install(@__DIR__)
route("/login") do
GenieAuthentication.login_page()
end
route("/logout") do
GenieAuthentication.logout()
end
up(8000)
```
## Tips and Best Practices
- **Use Secure Tokens:** Always set up secure tokens using `Genie.Secrets` for encryption, session management, and other security functionalities.
- **Modularity:** Keep your routes, controllers, and models modular to ensure maintainability and readability.
- **Environment Configuration:** Use different configuration files for development (`config/env/dev.jl`), testing (`config/env/test.jl`), and production (`config/env/prod.jl`) environments.
- **Automatic Reloading:** Utilize `Revise.jl` for automatic reloading during development to speed up the iteration process.
## Troubleshooting and Debugging
- **Use Logging:** Enable Genie logging to aid in debugging:
```julia
import Genie.Logger
Logger.initialize_logging("logfile.log", "info")
```
- **Check Configurations:** Ensure all database and server configurations are correct, especially when deploying to different environments.
- **Community Support:** Join the [Genie Discord Community](https://discord.com/invite/9zyZbD6J7H) for help and support.
## Additional Resources
- **Official Documentation:** [Genie Documentation](https://genieframework.github.io/Genie.jl/dev/)
- **Example Applications:** [Genie Example Apps](https://learn.genieframework.com/app-gallery)
This comprehensive cheatsheet provides the essential information for starting and developing applications using the Genie.jl web framework. For detailed guidance, refer to the official documentation and community resources. Happy coding! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 4619 | # HTTP.jl Cheatsheet
Welcome to the comprehensive guide on using the HTTP.jl package! This cheatsheet covers everything you need to know to get up and running with HTTP.jl, from basic client requests to advanced server configurations. Designed to be beginner-friendly, this guide ensures you can start coding without additional instructions.
## 1. Package Name
**HTTP.jl**
## 2. URL
[GitHub Repository](https://github.com/JuliaWeb/HTTP.jl)
## 3. Purpose
HTTP.jl provides extensive HTTP client and server functionality for Julia, including support for requests, responses, headers, cookies, WebSockets, and more. It's suitable for building robust web applications and services.
## 4. Installation
To install HTTP.jl, use Julia's package manager:
- REPL mode:
```julia
pkg> add HTTP
```
- Programmatically:
```julia
julia> using Pkg; Pkg.add("HTTP")
```
## 5. Usage Overview
### Client Requests
#### Basic Request
```julia
using HTTP
resp = HTTP.request("GET", "http://httpbin.org/ip")
println(resp.status) # Print status code
println(String(resp.body)) # Print response body
```
#### Convenience Functions
```julia
resp = HTTP.get("http://httpbin.org/ip")
resp = HTTP.post("http://httpbin.org/post", [], "sample body")
```
### Server Implementation
#### Simple Server
```julia
using HTTP
function my_handler(req::HTTP.Request)
return HTTP.Response(200, "Hello, World!")
end
HTTP.serve(my_handler, "127.0.0.1", 8080)
```
### WebSocket Client
#### Simple Client
```julia
using HTTP.WebSockets
WebSockets.open("ws://websocket.org") do ws
for msg in ws
println("Received: ", msg)
send(ws, "Echo: $msg")
end
end
```
## 6. Main Features and Functions
### Status Codes and Messages
**`statustext(statuscode::Int) -> String`**
- Converts HTTP status codes to their respective string messages.
```julia
statustext(200) # Returns "OK"
statustext(404) # Returns "Not Found"
```
### HTTP Requests and Responses
#### Basic Client Functions
- **`HTTP.get(url, headers=[], body=nothing)`**: Performs a GET request.
- **`HTTP.post(url, headers=[], body=nothing)`**: Performs a POST request.
- **`HTTP.request(method, url, headers=[], body=nothing; kwargs...)`**: General request function.
#### Server Functions
- **`HTTP.serve(handler, host="0.0.0.0", port=8080; kwargs...)`**: Starts a blocking server.
- **`HTTP.serve!(handler, host="0.0.0.0", port=8080; kwargs...)`**: Starts a non-blocking server.
### WebSockets
- **`WebSockets.open(url) do ws`**: Opens a WebSocket client connection.
- **`WebSockets.listen(host, port) do ws`**: Opens a WebSocket server.
## 7. Detailed Examples
### Client - GET Request
```julia
using HTTP
resp = HTTP.get("http://httpbin.org/ip")
println("Status: ", resp.status)
println("Response Body: ", String(resp.body))
```
### Client - POST Request with JSON
```julia
using HTTP
using JSON
headers = ["Content-Type" => "application/json"]
body = JSON.json(Dict("key" => "value"))
resp = HTTP.post("http://httpbin.org/post", headers, body)
println("Status: ", resp.status)
println("Response Body: ", String(resp.body))
```
### Server - Basic HTTP Server
```julia
using HTTP
function handler(req::HTTP.Request)
return HTTP.Response(200, "Hello, HTTP.jl!")
end
HTTP.serve(handler, "127.0.0.1", 8080)
```
### Server - Echo WebSocket Server
```julia
using HTTP.WebSockets
HTTP.WebSockets.listen("0.0.0.0", 8080) do ws
for msg in ws
send(ws, "Echo: $msg")
end
end
```
### WebSocket Client
```julia
using HTTP.WebSockets
WebSockets.open("ws://localhost:8080") do ws
send(ws, "Hello from client")
msg = receive(ws)
println("Received: $msg")
end
```
## 8. Tips and Best Practices
- **Verbose Logging**: Use `verbose` keyword argument in requests for detailed logging.
- **Error Handling**: Handle exceptions like `HTTP.TimeoutError` and `HTTP.StatusError` for robust applications.
- **SSL Verification**: Use `sslconfig` to customize SSL settings and ensure secure connections.
- **Session Management**: Utilize `Cookies` and `CookieJar` to manage sessions.
- **Custom Middleware**: Create middleware layers to extend functionality.
## 9. Additional Resources
- [Documentation](https://github.com/JuliaWeb/HTTP.jl)
- [Examples](https://github.com/JuliaWeb/HTTP.jl/tree/master/examples)
- [FAQs and Issues](https://github.com/JuliaWeb/HTTP.jl/issues)
By following this comprehensive cheatsheet, a junior developer can effectively use HTTP.jl to perform HTTP operations, manage server-client interactions, and handle WebSocket communications without needing additional guidance. Happy coding! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 6470 | # LLMCheatsheets.jl Cheatsheet
## Package Name
LLMCheatsheets.jl
## URL
[LLMCheatsheets.jl GitHub Repository](https://github.com/svilupp/LLMCheatsheets.jl)
## Purpose
LLMCheatsheets.jl is designed to generate AI-friendly documentation cheatsheets by summarizing the content of GitHub repositories. It facilitates seamless integration with language models and AI assistants for quick and comprehensive documentation.
## Installation
To install LLMCheatsheets.jl, use the Julia package manager with the repository URL:
```julia
using Pkg
Pkg.add(url = "https://github.com/svilupp/LLMCheatsheets.jl")
```
> **Tip**: Set up a personal access token with `ENV["GITHUB_API_KEY"]` to avoid GitHub API rate limits.
## Usage Overview
Import the package and initialize it for use:
```julia
using LLMCheatsheets
```
### Example: Create a Cheatsheet for a GitHub Repository
```julia
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl")
create_cheatsheet(repo; save_path = true)
```
## Main Features and Functions
### `GitHubRepo`
Represents a GitHub repository and contains configuration for scanning files.
**Constructor:**
```julia
GitHubRepo(url::String; paths = ["src", "docs/src", "README.md"], file_types = [".jl", ".md"])
```
**Fields:**
- `owner::String`: Repository owner.
- `name::String`: Repository name.
- `url::String`: Repository URL.
- `paths::Vector{String}`: Folders and files to scan.
- `file_types::Vector{String}`: Accepted file types in the scan.
**Example:**
```julia
repo = GitHubRepo("https://github.com/username/repository")
```
### `summarize_file`
Summarizes the content of a file in a GitHub repository.
**Function Signature:**
```julia
summarize_file(file_info::AbstractDict;
model = "gpt4o",
special_instructions::AbstractString = "None.\n",
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = nothing,
verbose::Bool = true,
http_kwargs::NamedTuple = NamedTuple())
```
**Arguments:**
- `file_info::AbstractDict`: Dictionary with `:name` and `:download_url`.
- `model::String`: AI model.
- `special_instructions::AbstractString`: Instructions for AI's output.
- `cost_tracker::Union{Nothing, Threads.Atomic{<:Real}}`: Optional cost tracker.
- `verbose::Bool`: Enables verbose output.
- `http_kwargs::NamedTuple`: Additional HTTP arguments.
**Returns:**
- `Dict`: Contains file name, summarized content, and type.
**Example:**
```julia
file_info = Dict(:name => "example.jl", :download_url => "https://github.com/user/repo/raw/main/example.jl")
result = summarize_file(file_info)
println(result[:content])
```
### `collate_files`
Collates multiple file contents into a single string.
**Function Signature:**
```julia
collate_files(file_contents::AbstractVector{<:AbstractDict})
```
**Arguments:**
- `file_contents::AbstractVector{<:AbstractDict}`: Vector of dictionaries containing file names and contents.
**Returns:**
- `String`: Concatenated names and contents of files.
**Example:**
```julia
file_contents = [
Dict(:name => "file1.jl", :content => "Content of file 1"),
Dict(:name => "file2.jl", :content => "Content of file 2")
]
collated_content = collate_files(file_contents)
println(collated_content)
```
### `create_cheatsheet`
Generates a cheatsheet for a GitHub repository and its file summaries.
**Function Signature:**
```julia
create_cheatsheet(repo::GitHubRepo,
file_contents::AbstractVector{<:AbstractDict};
model = "gpt4o",
special_instructions::AbstractString = "None.\n",
template::Symbol = :CheatsheetCreator,
cost_tracker::Union{Nothing, Threads.Atomic{<:Real}} = nothing,
verbose::Bool = true,
save_path::Union{Nothing, String, Bool} = nothing,
http_kwargs::NamedTuple = NamedTuple()) -> String
```
**Arguments:**
- `repo::GitHubRepo`: GitHub repository.
- `file_contents::AbstractVector{<:AbstractDict}`: File summaries.
- `model::String`: LLM model.
- `special_instructions::AbstractString`: AI output instructions.
- `template::Symbol`: Template for cheatsheet.
- `cost_tracker::Union{Nothing, Threads.Atomic{<:Real}}`: Cost tracker.
- `verbose::Bool`: Verbose output.
- `save_path::Union{Nothing, String, Bool}`: Path to save the cheatsheet.
- `http_kwargs::NamedTuple`: Extra HTTP arguments.
**Returns:**
- `String`: Cheatsheet content.
**Example:**
```julia
repo = GitHubRepo("https://github.com/svilupp/PromptingTools.jl")
cheatsheet_content = create_cheatsheet(repo)
println(cheatsheet_content)
```
### `Base.collect`
Scans a GitHub repository, downloads all file contents, and collates them into a single document.
**Function Signature:**
```julia
Base.collect(repo::GitHubRepo;
verbose::Bool = true,
save_path::Union{Nothing, String, Bool} = nothing,
ntasks::Int = 0,
http_kwargs::NamedTuple = NamedTuple()) -> String
```
**Arguments:**
- `repo::GitHubRepo`: Repository to scan.
- `verbose::Bool`: Verbose output.
- `save_path::Union{Nothing, String, Bool}`: Path to save collated content.
- `ntasks::Int`: Number of tasks for asynchronous processing.
- `http_kwargs::NamedTuple`: Extra HTTP arguments.
**Returns:**
- `String`: Collated file contents.
**Example:**
```julia
repo = GitHubRepo("https://github.com/username/repository")
collated_content = Base.collect(repo)
println(collated_content)
```
## Tips and Best Practices
- **API Rate Limits**: Configure a GitHub personal access token as `ENV["GITHUB_API_KEY"]` to enhance API rate limits.
- **Verbose Mode**: Use `verbose = true` for detailed output during operations.
- **Special Instructions**: Tailor the AI output by providing specific `special_instructions`.
- **Cost Tracking**: Utilize `cost_tracker` to monitor the cost if making multiple AI calls.
- **Custom Paths and File Types**: Customize `paths` and `file_types` in `GitHubRepo` to focus scans on relevant files.
## Additional Resources
- **Documentation**: [LLMCheatsheets.jl Documentation](https://svilupp.github.io/LLMCheatsheets.jl/dev/)
- **GitHub Issues**: [LLMCheatsheets.jl Issues](https://github.com/svilupp/LLMCheatsheets.jl/issues) for support and bug reports.
By following this cheatsheet, you will be able to effectively use LLMCheatsheets.jl to generate comprehensive, AI-friendly documentation from GitHub repositories. Happy coding! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 7797 | ```markdown
# MLFlowClient Julia Package - Cheatsheet
## Package Name
MLFlowClient.jl
## URL
[MLFlowClient.jl Repository](https://github.com/JuliaAI/MLFlowClient.jl)
## Purpose
MLFlowClient.jl is a Julia client for interfacing with [MLFlow](https://www.mlflow.org/), a popular open-source platform for managing machine learning lifecycle processes, including experimentation, reproducibility, and deployment.
## Installation
To utilize the MLFlowClient package in your Julia environment, follow these steps:
1. **Start a Julia Session**: Open your Julia REPL.
2. **Add the MLFlowClient Package**:
- Using the `Pkg` module:
```julia
import Pkg
Pkg.add("MLFlowClient")
```
- Alternatively, using the package mode (activated by `]` in the REPL):
```julia
] add MLFlowClient
```
## Usage Overview
To start using MLFlowClient, import the package in your Julia script:
```julia
using MLFlowClient
```
## Examples
### Basic Example
Here’s a minimal example to demonstrate setting up an MLFlow experiment, logging some parameters and metrics, and managing runs.
```julia
# Import the MLFlowClient package
using MLFlowClient
# Initialize MLFlow client
mlf = MLFlow()
# Create a new experiment
experiment_id = createexperiment(mlf; name="MyExperiment")
# Start a new run in the experiment
run = createrun(mlf, experiment_id)
# Log parameters and metrics
logparam(mlf, run, "param_key", "param_value")
logmetric(mlf, run, "accuracy", 0.95)
# Complete the run
updaterun(mlf, run, "FINISHED")
```
## Main Features and Functions
### Types and Constants
- **MLFlow**: Main type representing the MLFlow client.
- **MLFlowExperiment**: Represents an MLFlow Experiment.
- **MLFlowRun**: Represents an MLFlow Run.
- **MLFlowRunStatus**: Indicates the status of a run.
- **MLFlowRunInfo**: Metadata about a run.
- **MLFlowRunDataMetric**: Represents metrics logged during a run.
- **MLFlowRunDataParam**: Represents parameters logged during a run.
- **MLFlowArtifactFileInfo**: Describes file artifacts produced during a run.
- **MLFlowArtifactDirInfo**: Describes directory artifacts produced during a run.
### Experiment Management
- **createexperiment(mlf::MLFlow; name=missing, artifact_location=missing, tags=missing)**: Creates a new experiment.
```julia
experiment = createexperiment(mlf, name="My Experiment", artifact_location="/path/to/artifacts")
```
- **getexperiment(mlf::MLFlow, experiment_id::Integer)**: Fetches an experiment by its ID.
```julia
experiment = getexperiment(mlf, 123)
```
- **getorcreateexperiment(mlf::MLFlow, experiment_name::String; artifact_location=missing, tags=missing)**: Retrieves or creates an experiment.
```julia
experiment = getorcreateexperiment(mlf, "My Experiment", artifact_location="/path/to/artifacts")
```
- **deleteexperiment(mlf::MLFlow, experiment_id::Integer)**: Deletes an experiment.
```julia
success = deleteexperiment(mlf, 123)
```
- **restoreexperiment(mlf::MLFlow, experiment_id::Integer)**: Restores a deleted experiment.
```julia
success = restoreexperiment(mlf, 123)
```
- **searchexperiments(mlf::MLFlow; filter::String="", filter_attributes::AbstractDict{K,V}=Dict{}(), run_view_type::String="ACTIVE_ONLY", max_results::Int64=50000, order_by::AbstractVector{<:String}=["attribute.last_update_time"], page_token::String="")**: Searches for experiments.
```julia
experiments = searchexperiments(mlf, filter="tags.status = 'active'")
```
### Run Management
- **createrun(mlf::MLFlow, experiment_id::String, run_name=missing, start_time=missing, tags=missing)**: Creates a run.
```julia
run = createrun(mlf, 123, run_name="Test Run", start_time=1633072800000, tags=Dict("env" => "production"))
```
- **getrun(mlf::MLFlow, run_id::String)**: Retrieves a run.
```julia
run_info = getrun(mlf, "12345")
```
- **updaterun(mlf::MLFlow, run, status; run_name=missing, end_time=missing)**: Updates a run.
```julia
updaterun(mlf, "12345", "FINISHED", run_name="Updated Run", end_time=1633072800000)
```
- **deleterun(mlf::MLFlow, run)**: Deletes a run.
```julia
success = deleterun(mlf, "12345")
```
- **searchruns(mlf::MLFlow, experiment_ids::AbstractVector{Integer}; filter::String="", filter_params::AbstractDict{K,V}=Dict{}(), run_view_type::String="ACTIVE_ONLY", max_results::Integer=50000, order_by::String="attribute.end_time", page_token::String="")**: Searches for runs.
```julia
runs = searchruns(mlf, [1, 2, 3], filter="params.mlflow.runName = 'Test Run'", run_view_type="ALL")
```
### Logging
- **logparam(mlf::MLFlow, run::Union{String,MLFlowRun,MLFlowRunInfo}, *args)**: Logs parameters.
```julia
logparam(mlf, run, "param_key", "param_value")
logparam(mlf, run, Dict("param1" => "value1", "param2" => "value2"))
```
- **logmetric(mlf::MLFlow, run, key, value::Real; timestamp=missing, step=missing)**: Logs metrics.
```julia
logmetric(mlf, run, "accuracy", 0.95)
logmetric(mlf, run, "loss", [0.1, 0.08, 0.05]; step=1)
```
- **logartifact(mlf::MLFlow, run, filepath)**: Logs artifacts.
```julia
logartifact(mlf, run, "/path/to/local/file.txt")
```
- **listartifacts(mlf::MLFlow, run; path::String="", maxdepth::Int64=1)**: Lists artifacts.
```julia
artifacts = listartifacts(mlf, run, path="subdir", maxdepth=2)
```
### Utilities
- **mlfget(mlf, endpoint; kwargs...)**: Makes GET requests.
```julia
response = mlfget("http://api.example.com", "/data", param1="value1", param2="value2")
```
- **mlfpost(mlf, endpoint; kwargs...)**: Makes POST requests.
```julia
response = mlfpost("http://api.example.com", "/submit", key1="value1", key2="value2")
```
- **uri(mlf::MLFlow, endpoint="", query=missing)**: Generates a URI.
```julia
uri_str = uri(mlf, "experiments/get", Dict(:experiment_id => 10))
```
### Generating Filters
- **generatefilterfromparams(params::Dict)**: Generates a filter string from parameters.
```julia
filter_str = generatefilterfromparams(Dict("paramkey1" => "paramvalue1"))
```
- **generatefilterfromattributes(attributes::Dict)**: Generates a filter string from attributes.
```julia
filter_str = generatefilterfromattributes(Dict("attr1" => "value1"))
```
### Artifact Metadata Retrieval
- **MLFlowArtifactFileInfo**: Metadata that describes a single artifact file.
```julia
file_info = MLFlowArtifactFileInfo("path/to/file", 1024)
println(file_info.filepath) # Outputs: path/to/file
println(file_info.filesize) # Outputs: 1024
```
- **MLFlowArtifactDirInfo**: Metadata that describes a single artifact directory.
```julia
dir_info = MLFlowArtifactDirInfo("path/to/dir")
println(dir_info.dirpath) # Outputs: path/to/dir
```
## Tips and Best Practices
- Always use keyword arguments for clarity and maintainability in functions like `createrun` and `logmetric`.
- Regularly validate the existence of experiments and runs using `getexperiment` and `getrun` before attempting to log data.
- Utilize `logbatch` for performance efficiency when logging multiple parameters and metrics in a single operation.
- Handle artifacts carefully, especially large datasets, to avoid storage issues.
- Clean up by deleting unneeded experiments and runs to maintain an organized and performant MLFlow server.
## Additional Resources
- [Stable Documentation](https://juliaai.github.io/MLFlowClient.jl/stable)
- [Development Documentation](https://juliaai.github.io/MLFlowClient.jl/dev)
- [MLFlow Official Documentation](https://mlflow.org/docs/latest/index.html)
By following the guidelines in this cheatsheet, you can effectively leverage the MLFlowClient package to track and manage your machine learning experiments in Julia. Happy coding!
``` | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 4385 | # MLJ Cheatsheet
## Package Name: MLJ.jl
## URL
[MLJ Repository](https://github.com/JuliaAI/MLJ.jl)
## Purpose
MLJ is a comprehensive Machine Learning toolbox for Julia that integrates various models and functionalities for machine learning tasks such as data preprocessing, model selection, hyperparameter tuning, and model evaluation.
## Installation
### Prerequisites
Ensure you have Julia installed. MLJ works with Julia 1.5 and above.
### Setting Up Environment
```julia
using Pkg
Pkg.activate("my_MLJ_env", shared=true)
Pkg.add("MLJ")
```
To run tests:
```julia
Pkg.test("MLJ")
```
## Usage Overview
### Import MLJ
```julia
using MLJ
```
## Main Features and Functions
### Core Components
- **MLJBase.jl**: Primary interface for machine workflows.
- Data partitioning: `partition`
- Dataset unpacking: `unpack`
- Model evaluation: `evaluate`/`evaluate!`
- Utility functions: `scitype`, `schema`
- **StatisticalMeasures.jl**: Performance metrics and evaluation tools.
- **MLJModels.jl**: Loading and managing models.
- Load models: `using @load`
- **MLJTuning.jl**: Hyperparameter optimization.
- Wrapper example: `TunedModel`
- **MLJIteration.jl**: Iterative modeling control.
- Example: `IteratedModel` wrapper
- **MLJEnsembles.jl**: Ensemble modeling.
- Example: `EnsembleModel` wrapper
### Key Components Example Usage
### Loading and Preprocessing Data
```julia
using MLJ
@load_iris |> pretty
# Example: Loading and previewing iris dataset
iris = load_iris()
select(rows(iris, 1:3)) |> pretty
schema(iris)
```
### Splitting Data
```julia
y, X = unpack(iris, ==(:target); rng=123)
```
### Training a Model
```julia
using MLJ
model = @load DecisionTreeClassifier
machine = machine(model, X, y)
fit!(machine)
```
### Evaluating a Model
```julia
evaluate!(machine, resampling=CV(nfolds=6), measure=accuracy)
```
### Pipeline Creation
```julia
using MLJ
pipe = Standardizer() |> OneHotEncoder() |> @load DecisionTreeClassifier
mach = machine(pipe, X, y)
fit!(mach)
```
### Hyperparameter Tuning
```julia
using MLJ
model = @load DecisionTreeClassifier
r = range(model, :max_depth, lower=1, upper=15)
self_tuning_model = TunedModel(model=model, resampling=Holdout(), range=r, measure=auc)
mach = machine(self_tuning_model, X, y)
fit!(mach)
```
## Detailed Examples
### Example: Print MLJ Version
```julia
using Pkg
const PROJECT_FILE = normpath(joinpath(dirname(@__FILE__), "..", "Project.toml"))
const MLJ_VERSION = VersionNumber(Pkg.TOML.parse(read(PROJECT_FILE, String))["tools"]["MLJ"]["version"])
println("Current MLJ version: ", MLJ_VERSION)
```
### Types and Implementations
#### Defining Custom Types
```julia
struct SupervisedScitype{input_scitype, target_scitype, prediction_type} end
# Usage Example in Model
model = SomeSupervisedModel()
scitype_info = scitype(model, DefaultConvention())
println(scitype_info.input_scitype)
println(scitype_info.target_scitype)
println(scitype_info.prediction_type)
```
### Model Composition
#### Linear Pipelines
```julia
using MLJ
pipe = (X -> coerce(X, :age=>Continuous)) |> ContinuousEncoder() |> @load KNNRegressor(K=2)
```
#### Model Stacking
```julia
using MLJ
Stack(model1, model2, ..)
```
### Saving and Loading Models
```julia
MLJBase.save("model_file.jlso", mach) # Save
mach = machine("model_file.jlso") # Load
restore!(mach) # Post-process
```
## Tips and Best Practices
- Always check and align the scientific types (scitypes) of your data using `schema` and `coerce`.
- Utilize `@load` for importing models and `@iload` for interactive loading.
- Evaluate models with cross-validation using `CV` as the resampling strategy.
- Employ `TunedModel` and `Grid`, `RandomSearch` for hyperparameter optimization.
- Use `IteratedModel` for iterative models and `EnsembleModel` for building ensemble models.
## Additional Resources
- **Official Documentation**: [MLJ Documentation](https://JuliaAI.github.io/MLJ.jl/dev/)
- **Tutorials and Walkthroughs**: [Data Science in Julia Tutorials](https://JuliaAI.github.io/DataScienceTutorials.jl/)
- **Community Support**: [Julia Discourse Machine Learning category](https://discourse.julialang.org/c/domain/machine-learning)
By following this cheatsheet, you should now be well-equipped to start using the MLJ framework for your machine learning projects in Julia! Enjoy coding! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 3963 | # Makie.jl Cheatsheet
## Package Name: Makie.jl
## URL: [https://github.com/MakieOrg/Makie.jl](https://github.com/MakieOrg/Makie.jl)
## Purpose
**Makie.jl** is a high-performance, extensible, and flexible data visualization ecosystem in Julia. It supports a variety of visualizations, including interactive plots, GUIs, and high-quality vector graphics.
## Installation
### Step-by-Step Instructions
Choose and install one or more backend packages depending on your needs:
**GLMakie** (interactive OpenGL):
```julia
using Pkg
Pkg.add("GLMakie")
```
**WGLMakie** (interactive WebGL in browsers):
```julia
using Pkg
Pkg.add("WGLMakie")
```
**CairoMakie** (static 2D vector graphics):
```julia
using Pkg
Pkg.add("CairoMakie")
```
**RPRMakie** (experimental ray tracing):
```julia
using Pkg
Pkg.add("RPRMakie")
```
### Activating a Backend
Activate the backend you installed with:
```julia
using GLMakie # Example for GLMakie
GLMakie.activate!()
```
## Usage Overview
### Importing Makie
After activating your desired backend, import the Makie package:
```julia
using Makie
```
## Main Features and Functions
### Basic Plotting Functions
#### Scatter Plot
```julia
using GLMakie
x = 1:10
y = rand(10)
scatter(x, y, color = :blue, markersize = 10)
```
- **`x`, `y`**: Coordinates for the scatter points.
- **`color`**: Color of the points.
- **`markersize`**: Size of the points.
#### Line Plot
```julia
using GLMakie
x = 1:10
y = cumsum(randn(10))
lines(x, y, color = :red, linewidth = 2)
```
- **`color`**: Color of the line.
- **`linewidth`**: Thickness of the line.
#### Surface Plot
```julia
using GLMakie
x = y = -5:0.5:5
z = [sin(sqrt(x^2 + y^2)) for x in x, y in y]
surface(x, y, z, colormap = :viridis)
```
- **`colormap`**: Colormap to use for the surface.
### Adding Titles and Labels
```julia
x = 1:10
y = rand(10)
scatter(x, y, title="My Title", xlabel="X-Axis", ylabel="Y-Axis")
```
- **`title`**: Title of the plot.
- **`xlabel`**: Label for x-axis.
- **`ylabel`**: Label for y-axis.
### Advanced Customization
#### Subplots
```julia
f = Figure()
ax1 = Axis(f[1, 1])
scatter!(ax1, 1:10, rand(10))
ax2 = Axis(f[1, 2])
lines!(ax2, 1:10, cumsum(randn(10)))
f
```
#### Legends
```julia
f = Figure()
ax = Axis(f[1, 1])
lines!(ax, 1:10, rand(10), label="Line 1")
lines!(ax, 1:10, rand(10)+2, label="Line 2")
Legend(f[1, 2], ax)
f
```
- **`label`**: Label for each plot element.
- **`Legend`**: Adds a legend to the figure.
## Detailed Examples
### Customizing Plots with Themes
```julia
using GLMakie
set_theme!(palette = (color = [:red, :blue], marker = [:circle, :rect]))
f = Figure()
ax = Axis(f[1, 1])
scatter!(ax, 1:10, rand(10))
f
```
- **`set_theme!`**: Sets a theme for consistent styling.
### Interactive Sliders and Buttons
```julia
using GLMakie, Observables
# Create a figure and axis
fig = Figure()
ax = Axis(fig[1, 1])
# Create a slider
slider = Slider(fig[2, 1], 1:10, startvalue=5)
# Reactively update the plot based on slider value
squared = lift(slider.value) do x
x^2
end
scatter!(ax, 1:10, squared)
fig
```
- **`Slider`**: Adds a slider to control plot data interactively.
- **`Observable`**: Reactively update plot data.
## Tips and Best Practices
1. **Modular Layouts**
- Use `GridPosition` and `GridSubpositions` within a `Figure` for complex subplot layouts.
2. **Theme Management**
- Customize and reuse themes with `set_theme!`, `update_theme!`, and `with_theme`.
3. **Interaction**
- Utilize `Observable` and `lift` for interactive and dynamic plots.
4. **Efficient Updates**
- Use indexed updates and observables to efficiently update plots without redrawing.
## Conclusion
Makie.jl offers a comprehensive and flexible framework for data visualization in Julia, suitable for both static and interactive plots. By leveraging various backends and customization options, you can create high-quality, publication-ready visualizations and interactive data exploration tools. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5940 | # Comprehensive Cheatsheet for Using PromptingTools.jl
## Overview
PromptingTools.jl is a Julia package designed to simplify interactions with AI models by providing a variety of tools for generating, extracting, embedding, and classifying text. This cheatsheet covers everything from basic usage to advanced features such as RAG (Retrieve-Augmented Generation) tools and multi-turn conversations.
## Getting Started
### Installation
To install PromptingTools.jl, use the Julia package manager:
```julia
using Pkg
Pkg.add("PromptingTools")
```
### Setting Up API Keys
**OpenAI API Key:**
1. Sign up at [OpenAI](https://platform.openai.com/signup).
2. Navigate to [API Key Page](https://platform.openai.com/account/api-keys).
3. Set your API key in the environment:
```julia
ENV["OPENAI_API_KEY"] = "your-api-key"
```
4. Optionally, for terminal:
```bash
export OPENAI_API_KEY=<your-key>
```
## Basic Usage
### Quick Start with `@ai_str`
Generate responses quickly using the `@ai_str` string macro:
```julia
using PromptingTools
response = ai"What is the capital of France?"
println(response.content) # "The capital of France is Paris."
```
### Multi-Turn Conversations with `@ai!_str`
Keep context between queries:
```julia
response1 = ai"What is the weather today?"
response2 = ai!"Do I need an umbrella?"
```
### String Interpolation
Inject variables into your prompts:
```julia
country = "Spain"
response = ai"What is the capital of \$country?"
println(response.content) # "The capital of Spain is Madrid."
```
### Selecting Models
Choose specific models using flags:
```julia
response = ai"What is the meaning of life?"gpt4
```
## Advanced Functions
### `aigenerate` with Placeholders
Use handlebars-style templating for complex queries:
```julia
msg = aigenerate("What is the capital of {{country}}? Is the population larger than {{population}}?", country="Spain", population="1M")
println(msg.content)
```
**Asynchronous Version:**
```julia
response = aai"Say hi but slowly!"gpt4
```
### Creating Reusable Prompt Templates with `create_template`
#### Example Template Creation
Reusable templates streamline repeated tasks by defining a structure for prompts:
```julia
using PromptingTools
template = create_template(
system = "You are a helpful assistant designed to answer programming questions.",
user = "I need help with {{input_question}}"
)
question1 = "How do I reverse a list in Python?"
response1 = aigenerate(template; user_input=question1)
println(response1.content)
```
### Tips for a Good Prompt
1. **Clear Task Description:** Clearly define what the AI should do.
2. **Guidelines/Instructions:** Provide detailed conditions or steps.
3. **Desired Output Format:** Specify the expected format for the AI's response.
4. **System Prompt:** Should include clear task description, guidelines, and desired output format.
5. **User Prompt:** Should contain placeholders for inputs, like `{{input}}`.
## Multi-Turn Conversations with `AIGenerate`
### Using `AIGenerate` as a Functor
You can use `AIGenerate` for effortless multi-turn conversations with the LLM by treating it as a function:
```julia
conversation = AIGenerate("What is 1+1?")
response1 = conversation("Now multiply the result by 2.")
response2 = conversation("Subtract 3 from the result.")
println(response2)
```
## RAGTools Deep Dive
RAGTools enriches LLM capabilities with external data. The core functions include `airag`, `retrieve`, and `generate!`.
### `airag`
Combines retrieval and generation for advanced tasks.
```julia
response = airag(query="Describe the climate policies of different countries.")
```
### `retrieve`
Fetch relevant documents or data.
```julia
docs = retrieve("Explain neural networks in simple terms.")
```
### `generate!`
Use retrieved data to generate contextually rich responses.
```julia
context = retrieve("Explain neural networks in simple terms.")
response = generate!(context, "What are neural networks?")
println(response)
```
### Example Workflow
1. **Retrieve Data:**
```julia
data = retrieve("Explain photosynthesis.")
```
2. **Generate Response:**
```julia
response = generate!(data, "Using the following information, explain photosynthesis.")
println(response.content)
```
### Additional Features
#### Asynchronous Execution
For heavy models, avoid blocking the REPL:
```julia
response = aai"Provide a summary of this text."gpt4
```
#### Custom Model Aliases
Define and use your own model aliases:
```julia
const PT = PromptingTools
PT.MODEL_ALIASES["gpt4t"] = "gpt-4-turbo"
response = ai"Describe the impact of climate change."gpt4t
```
#### Integration with Ollama Models
```julia
schema = PT.OllamaSchema()
msg = aigenerate(schema, "Say hi!"; model="openhermes2.5-mistral")
println(msg.content) # "Hello! How can I assist you today?"
```
#### Custom API Schemas
For custom API integrations:
```julia
PT.register_model!(name="custom-model", schema=PT.CustomOpenAISchema(), description="Custom API model.")
msg = aigenerate(PT.CustomOpenAISchema(), "Ask me anything."; model="custom-model", api_key="your_api_key")
```
## Best Practices and Cost Management
### Tokens and Costs
Monitor token usage and costs to manage expenses:
```julia
response = ai"How many tokens were used?"gpt4
println("Tokens used: ", response.tokens)
println("Cost: $", response.cost)
```
### Save and Load Templates
Persist your templates for reuse:
```julia
PT.save_template("templates/GreatingPirate.json", tpl; version="1.0")
PT.load_templates!("templates")
```
## Conclusion
PromptingTools.jl provides a versatile platform for integrating advanced AI functionalities into your projects. From simple queries to sophisticated RAG workflows, it offers powerful tools for effective and efficient AI interactions. Follow best practices, leverage reusable templates, and utilize advanced features to harness the full potential of PromptingTools.jl. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 4854 | # StatsPlots.jl Comprehensive Cheatsheet
## Package Name: StatsPlots.jl
## URL: [StatsPlots GitHub Repository](https://github.com/JuliaPlots/StatsPlots.jl)
## Purpose
StatsPlots.jl enhances the capabilities of Plots.jl by providing a range of statistical plotting recipes. It integrates well with DataFrames, Distributions, and other statistical packages, enabling users to create comprehensive and informative plots for statistical data analysis.
## Installation
### Step-by-Step Instructions
1. **Install the package**:
```julia
julia> using Pkg
julia> Pkg.add("StatsPlots")
```
2. **Import the package**:
```julia
julia> using StatsPlots
```
3. **Optional Initialization for Plot Size**:
```julia
julia> gr(size=(400, 300))
```
## Usage Overview
### Basic Import and Data Plotting
- Utilize the `@df` macro to simplify plotting DataFrame columns.
- Example:
```julia
julia> using DataFrames, StatsPlots
julia> df = DataFrame(a = 1:10, b = 10 .* rand(10), c = 10 .* rand(10))
julia> @df df plot(:a, [:b :c], colour = [:red :blue])
julia> @df df scatter(:a, :b, markersize = 4 .* log.(:c .+ 0.1))
```
### Advanced Column Selection
- Use `cols()` for selecting column ranges or variables.
```julia
julia> cols(2:3)
julia> s = :b
julia> cols(s)
julia> cols()
```
### Handling Ambiguous Symbols
- Escape non-column symbols with `^()`.
```julia
julia> df[:red] = rand(10)
julia> @df df plot(:a, [:b :c], colour = ^([:red :blue]))
```
## Main Features and Functions
### 1. Plotting Recipes
- **Density Plot**:
```julia
julia> using KernelDensity
julia> x = randn(1000)
julia> density(x)
```
- **Boxplot**:
```julia
julia> @df df boxplot(:a, :b)
```
- **Violin Plot**:
```julia
julia> using RDatasets
julia> iris = dataset("datasets", "iris")
julia> @df iris violin(:Species, :SepalLength)
```
- **Corner Plot**:
```julia
julia> data = rand(100, 5)
julia> CornerPlot(data; compact=true)
```
- **Grouped Histogram**:
```julia
julia> @df iris groupedhist(:SepalLength, group = :Species, bar_position = :dodge)
```
### 2. Specialized Plots
- **Marginal Histograms**:
```julia
julia> @df iris marginalhist(:PetalLength, :PetalWidth)
```
- **Interactive DataViewer**:
```julia
julia> use DataFrames, Observable, Widget
julia> df = DataFrame(x = 1:100, y = rand(100))
julia> dataviewer(df)
```
### 3. Quantile-Quantile Plots (QQPlots)
- **QQPlot**:
```julia
julia> using Distributions, StatsPlots
julia> x = rand(Normal(), 100)
julia> y = rand(Cauchy(), 100)
julia> qqplot(x, y, qqline=:identity)
```
## Detailed Examples
### Kernel Density Estimation
1. **Plotting Univariate KDE**:
```julia
julia> data = randn(100)
julia> kde_result = kde(data)
julia> plot(kde_result)
```
2. **Plotting Bivariate KDE**:
```julia
julia> data = rand(2, 100)
julia> kde_result = kde(data)
julia> plot(kde_result)
```
### Boxplot and Violin Plot
1. **Basic Boxplot**:
```julia
julia> using Plots, StatsPlots
julia> x = rand(100)
julia> y = rand(100)
julia> boxplot(x, y; notch = true)
```
2. **Violin Plot with Grouping**:
```julia
julia> @df dataset("lattice", "singer") violin(:VoicePart, :Height)
```
### Interactive Plotting with Interact.jl
```julia
julia> using RDatasets, StatsPlots, Interact, Blink
julia> iris = RDatasets.dataset("datasets", "iris")
julia> w = Window()
julia> body!(w, dataviewer(iris))
```
## Tips and Best Practices
- **Utilize `@df` Macro**: Simplifies handling DataFrames for plotting.
- **Explore Package Functions**: Leverage functionalities from `KernelDensity`, `Distributions`, `Clustering`, and more.
- **Customize Plots**: Use attributes like `color`, `legend`, `linecolor`, and `fillalpha` to tweak plot appearances.
- **Interactive Exploration**: Use `dataviewer` for dynamic data visualization and exploration.
- **Grouped Plots**: Ideal for categorical data visualization; support for multiple grouping columns enhances clarity.
- **Kernel Density Plots**: Adjust `bandwidth` for finer control over the estimation.
## Additional Resources
**Documentation**:
- [StatsPlots Documentation](https://docs.juliaplots.org/latest/generated/statsplots/)
**Community and Support**:
- Join the [JuliaLang Zulip Chat](https://julialang.zulipchat.com/#narrow/stream/236493-plots) for discussions and support.
StatsPlots.jl offers a comprehensive suite of tools to create detailed and informative statistical plots, enhancing the visualization capabilities of Plots.jl significantly. With the provided examples and tips, newcomers can quickly start exploring and visualizing their statistical data in Julia. | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 4621 | # StippleUI.jl Cheatsheet
## Package Name
**StippleUI.jl**
## URL
[StippleUI.jl on GitHub](https://github.com/GenieFramework/StippleUI.jl)
## Purpose
StippleUI.jl provides a comprehensive set of reactive UI elements that seamlessly integrate with the Stipple ecosystem, including Stipple.jl and Genie.jl. It utilizes the Quasar Framework to deliver high-quality and interactive data dashboards entirely within Julia.
## Installation
To install StippleUI.jl, use the Julia package manager:
```julia
pkg> add StippleUI
```
## Usage Overview
To use StippleUI components in your Stipple-based application:
1. **Import StippleUI**:
```julia
using Stipple
using StippleUI
```
2. **Create Components**:
- Use StippleUI component functions (e.g., `btn`, `textfield`) to build interactive UI elements.
3. **Render Components**:
- Render the components within your pages using the `page` function from Stipple.
## Main Features and Functions
### Key Components
#### Buttons
Create customizable buttons using the `btn` function.
```julia
btn("Submit", @click(:submitAction), color="primary")
```
- **Parameters**:
- `label`: Button text.
- `@click`: Event handler for click events.
- `color`: Button color (e.g., "primary", "secondary").
- **Example**:
```julia
btn("Click Me", @click(:buttonClick), color="primary")
```
#### TextField
Create a text input field using the `textfield` function.
```julia
textfield("Name", :nameField, placeholder="Enter your name")
```
- **Parameters**:
- `label`: Field label.
- `v-model`: Bind to reactive variable.
- `placeholder`: Placeholder text.
#### Layouts
Organize application layout using `layout`, `page_container`, and `page`.
```julia
layout() # Basic layout
page_container() # Container for multiple pages
page("Page title") # Individual page within a container
```
#### Cards
Create card components using the `card`, `card_section`, and `card_actions`.
```julia
card(
class="card-class",
[
card_section("Card Header"),
card_section("Card Body Content"),
card_actions([btn("Accept"), btn("Decline")])
]
)
```
- **Parameters**:
- `class`: CSS class for styling.
- Nested components like sections and actions for structured content.
#### Dialogs
Create dialog windows using the `dialog` function.
```julia
dialog("Dialog Title", "This is the content of the dialog", [
btn("Close", @click(:closeDialog))
])
```
#### Avatars
Display avatars using the `avatar` function.
```julia
avatar(size=50, src="path/to/avatar.png")
```
- **Parameters**:
- `size`: Size of the avatar.
- `src`: Image source URL.
## Detailed Examples
### Creating a Button
```julia
using Stipple
using StippleUI
function ui()
@widget ([btn("Click Me", @click(:buttonClicked), color="primary"),])
end
function page()
page(
ui()
)
end
# Define click event
mixed @widget begin
function buttonClicked()
println("Button was clicked!")
end
end
Genie.isrunning(:webserver) || up()
```
### Form Example with TextField
```julia
using Stipple
using StippleUI
@vars UIForm begin
name::R{String} = ""
end
function ui()
[
textfield("Name", :name),
btn("Submit", @click(:submitAction))
]
end
function page()
page(
UIForm |> init |> ui
)
end
# Define the submit action
@widget begin
function submitAction()
println("Submitted Name: ", name[])
end
end
Genie.isrunning(:webserver) || up()
```
### Creating a Dialog
```julia
using Stipple
using StippleUI
@vars UIDialog begin
showDialog::R{Bool} = false
end
function ui()
[
btn("Open Dialog", @click("showDialog = true")),
dialog(:showDialog, "Dialog Title", "This is the dialog content", [
btn("Close", @click("showDialog = false"))
])
]
end
function page()
page(
UIDialog |> init |> ui
)
end
Genie.isrunning(:webserver) || up()
```
## Tips and Best Practices
- **Use Keyword Arguments**: Prefer keyword arguments for better clarity and code readability.
- **Consistent Naming**: Maintain consistent naming conventions for UI components and variables.
- **Error Handling**: Implement error checks and handle potential exceptions, especially in event handlers.
- **Documentation**: Keep components well-documented to help others understand your code quickly.
## Additional Resources
- **[Quasar Framework Documentation](https://quasar.dev)**
- **[Stipple.jl Documentation](https://github.com/GenieFramework/Stipple.jl)**
- **[Genie.jl Documentation](https://genieframework.github.io/Genie.jl/stable/)**
Start leveraging StippleUI.jl to create interactive and dynamic user interfaces in your Julia applications! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 8e9b3a308ccd9334fbcb8257afa447cd82aa10e8 | docs | 5139 | # Stipple.jl Cheatsheet
## Overview
**Stipple.jl** is a reactive UI library for Julia that integrates with Vue.js on the client side. It facilitates the development of dynamic, data-driven web applications with seamless two-way data binding between the Julia backend and the Vue.js frontend.
## Installation
Install Stipple from the GitHub repository via Julia's package manager:
```julia
pkg> add Stipple
```
## Key Concepts and Handlers
### Key Elements and Macros
#### `@app` Macro
The `@app` macro initializes the application, defines the data model, handlers, and UI components.
**Example:**
```julia
using Stipple
@app begin
@in counter = 0
@out doubled_value = 0
@onchange counter begin
doubled_value = counter * 2
end
end
function ui()
[
row(
column(
cell([p("Enter a number:"), textfield("Counter", :counter)])
),
column(
cell([p("Doubled Value: ", bignumber(:doubled_value))])
)
)
]
end
@page("/", ui)
```
#### `@in`, `@out`, `@onchange`, `@onclick`
These macros are used to manage reactive variables and event handlers within your application.
**`@in`**
Define reactive input variables:
```julia
@in user_name::String
```
**`@out`**
Define reactive output variables:
```julia
@out greeting::String = "Enter your name."
```
**`@onchange`**
Define a handler that triggers when a reactive variable changes:
```julia
@onchange user_name begin
greeting = "Hello, " * user_name
end
```
**`@onclick`**
Define a handler for click events:
```julia
@onclick greet_button begin
println("Button clicked!")
end
```
#### `@page` Macro
Define the structure of a UI page.
```julia
@page "/" begin
h1("Welcome to the App")
end
```
### Practical Examples
#### Example 1: Simple Greeting App
Define an app where a user enters their name and receives a greeting.
```julia
using Stipple
@app GreetingApp() begin
@in user_name::String
@out greeting::String = "Enter your name."
@onchange user_name begin
greeting = "Hello, " * user_name
end
layout() do
cell([
row([
column([
cell([input(user_name, placeholder="Enter your name...")])
]),
column([
cell([button("Greet Me", @onclick :greet_user)])
]),
column([
cell([p("Greeting: ", greeting)])
])
])
])
end
end
function greet_user()
@app().greeting = "Hello, " * @app().user_name
end
```
#### Example 2: Counter Application
Create an app that counts how many times a button is clicked.
```julia
using Stipple
@app ClickCounterApp() begin
@out click_count = 0
@onclick click_button begin
click_count += 1
end
layout() do
cell([
row([
column([
cell([button("Click me!", @onclick :click_button)])
]),
column([
cell([p("Click count: ", click_count)])
])
])
])
end
end
```
#### Example 3: Temperature Converter
Bind user input to model variables and perform real-time calculations.
```julia
using Stipple
@app TempConverterApp() begin
@in celsius::Float64 = 0.0
@out fahrenheit::Float64 = 32.0
@onchange celsius begin
fahrenheit = celsius * (9/5) + 32
end
layout() do
cell([
row([
column([
cell([
input(celsius, placeholder="Enter Celsius...", type="number")
])
]),
column([
cell([
p("Fahrenheit: ", fahrenheit)
])
])
])
])
end
end
```
## Advanced Component and Plugin Usage
Since upgrading to Vue3, additional components and plugins need to be handled differently:
```julia
# Registering a Vue2 component in a Vue3 app
Stipple.register_global_component("LegacyComponent", legacy = true)
# Adding a plugin to the application
Stipple.add_plugin(MyApp, "PluginName")
```
## Migration to Vue3/Quasar2
### Key Points
- Register components in the app instance.
- Update syntax for field synchronization from `<fieldname>.sync` to `v-model:<fieldname>`.
- Split components using `v-if` and `v-for` with a container element.
For more detailed migration support, refer to:
- [Quasar Upgrade Guide](https://quasar.dev/start/upgrade-guide/)
- [Vue3 Migration Guide](https://v3-migration.vuejs.org/)
## Additional Tips and Best Practices
- Initialize reactive variables with sensible default values.
- Use descriptive names for UI elements and reactive variables.
- Modularize significant UI components to keep the codebase maintainable.
## More Information
For more examples and detailed usage, access Stipple's documentation and function docstrings directly in Julia:
```julia
help?> btn
```
Happy coding with Stipple for your next interactive Julia application! | LLMCheatsheets | https://github.com/svilupp/LLMCheatsheets.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 538 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
module APIClient
using Dates, TimeZones
using OpenAPI
using OpenAPI.Clients
const API_VERSION = "2.0.29"
include("modelincludes.jl")
include("apis/api_AdminApi.jl")
include("apis/api_ChineseApi.jl")
include("apis/api_GeneralApi.jl")
include("apis/api_IndianApi.jl")
include("apis/api_JapaneseApi.jl")
include("apis/api_PersonalApi.jl")
include("apis/api_SocialApi.jl")
end # module APIClient
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 831 | module NamSor
include("APIClient.jl")
using Reexport
using JSON
using OpenAPI.Clients
using OpenAPI
@reexport using .APIClient
"""
init_api(::Type{T})::T where {T <: OpenAPI.APIClientImpl}
Initialize the NamSor API
"""
function init_api(::Type{T})::T where {T <: OpenAPI.APIClientImpl}
key = try ENV["NAMSOR_KEY"] catch end
if isnothing(key)
try
key = open(joinpath("$(homedir())",".config","NAMSOR_KEY.txt")) do f
readline(f)
end
catch
throw("Can't find API key.")
end
end
basepath = APIClient.basepath(T)
return T(Clients.Client(basepath;headers=Dict("X-API-KEY"=>"$(key)")));
end
# Suppress API key output for safety
Base.show(io::IO, obj::T) where {T <: OpenAPI.APIClientImpl}= ""
export init_api
end # module NamSor
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 5335 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
include("models/model_APIBillingPeriodUsageOut.jl")
include("models/model_APIClassifierOut.jl")
include("models/model_APIClassifierTaxonomyOut.jl")
include("models/model_APIClassifiersStatusOut.jl")
include("models/model_APICounterV2Out.jl")
include("models/model_APIKeyOut.jl")
include("models/model_APIPeriodUsageOut.jl")
include("models/model_APIPlanSubscriptionOut.jl")
include("models/model_APIServiceOut.jl")
include("models/model_APIServicesOut.jl")
include("models/model_APIUsageAggregatedOut.jl")
include("models/model_APIUsageHistoryOut.jl")
include("models/model_BatchCommunityEngageFullOut.jl")
include("models/model_BatchCommunityEngageOut.jl")
include("models/model_BatchCorridorIn.jl")
include("models/model_BatchCorridorOut.jl")
include("models/model_BatchFirstLastNameCasteOut.jl")
include("models/model_BatchFirstLastNameCastegroupOut.jl")
include("models/model_BatchFirstLastNameDiasporaedOut.jl")
include("models/model_BatchFirstLastNameGenderIn.jl")
include("models/model_BatchFirstLastNameGenderedOut.jl")
include("models/model_BatchFirstLastNameGeoIn.jl")
include("models/model_BatchFirstLastNameGeoOut.jl")
include("models/model_BatchFirstLastNameGeoSubclassificationOut.jl")
include("models/model_BatchFirstLastNameGeoSubdivisionIn.jl")
include("models/model_BatchFirstLastNameGeoZippedIn.jl")
include("models/model_BatchFirstLastNameIn.jl")
include("models/model_BatchFirstLastNameOriginedOut.jl")
include("models/model_BatchFirstLastNamePhoneCodedOut.jl")
include("models/model_BatchFirstLastNamePhoneNumberGeoIn.jl")
include("models/model_BatchFirstLastNamePhoneNumberIn.jl")
include("models/model_BatchFirstLastNameReligionedOut.jl")
include("models/model_BatchFirstLastNameSubdivisionIn.jl")
include("models/model_BatchFirstLastNameUSRaceEthnicityOut.jl")
include("models/model_BatchMatchPersonalFirstLastNameIn.jl")
include("models/model_BatchNameGeoIn.jl")
include("models/model_BatchNameIn.jl")
include("models/model_BatchNameMatchCandidatesOut.jl")
include("models/model_BatchNameMatchedOut.jl")
include("models/model_BatchPersonalNameCastegroupOut.jl")
include("models/model_BatchPersonalNameDiasporaedOut.jl")
include("models/model_BatchPersonalNameGenderedOut.jl")
include("models/model_BatchPersonalNameGeoIn.jl")
include("models/model_BatchPersonalNameGeoOut.jl")
include("models/model_BatchPersonalNameGeoSubclassificationOut.jl")
include("models/model_BatchPersonalNameGeoSubdivisionIn.jl")
include("models/model_BatchPersonalNameIn.jl")
include("models/model_BatchPersonalNameOriginedOut.jl")
include("models/model_BatchPersonalNameParsedOut.jl")
include("models/model_BatchPersonalNameReligionedOut.jl")
include("models/model_BatchPersonalNameSubdivisionIn.jl")
include("models/model_BatchPersonalNameUSRaceEthnicityOut.jl")
include("models/model_BatchProperNounCategorizedOut.jl")
include("models/model_CommunityEngageOptionOut.jl")
include("models/model_CommunityEngageOut.jl")
include("models/model_CorridorIn.jl")
include("models/model_CorridorOut.jl")
include("models/model_FeedbackLoopOut.jl")
include("models/model_FirstLastNameCasteOut.jl")
include("models/model_FirstLastNameCastegroupOut.jl")
include("models/model_FirstLastNameDiasporaedOut.jl")
include("models/model_FirstLastNameGenderIn.jl")
include("models/model_FirstLastNameGenderedOut.jl")
include("models/model_FirstLastNameGeoIn.jl")
include("models/model_FirstLastNameGeoOut.jl")
include("models/model_FirstLastNameGeoSubclassificationOut.jl")
include("models/model_FirstLastNameGeoSubdivisionIn.jl")
include("models/model_FirstLastNameGeoZippedIn.jl")
include("models/model_FirstLastNameIn.jl")
include("models/model_FirstLastNameOriginedOut.jl")
include("models/model_FirstLastNameOut.jl")
include("models/model_FirstLastNamePhoneCodedOut.jl")
include("models/model_FirstLastNamePhoneNumberGeoIn.jl")
include("models/model_FirstLastNamePhoneNumberIn.jl")
include("models/model_FirstLastNameReligionedOut.jl")
include("models/model_FirstLastNameSubdivisionIn.jl")
include("models/model_FirstLastNameUSRaceEthnicityOut.jl")
include("models/model_MatchPersonalFirstLastNameIn.jl")
include("models/model_NameGeoIn.jl")
include("models/model_NameIn.jl")
include("models/model_NameMatchCandidateOut.jl")
include("models/model_NameMatchCandidatesOut.jl")
include("models/model_NameMatchedOut.jl")
include("models/model_PersonalNameCastegroupOut.jl")
include("models/model_PersonalNameDiasporaedOut.jl")
include("models/model_PersonalNameGenderedOut.jl")
include("models/model_PersonalNameGeoIn.jl")
include("models/model_PersonalNameGeoOut.jl")
include("models/model_PersonalNameGeoSubclassificationOut.jl")
include("models/model_PersonalNameGeoSubdivisionIn.jl")
include("models/model_PersonalNameIn.jl")
include("models/model_PersonalNameOriginedOut.jl")
include("models/model_PersonalNameParsedOut.jl")
include("models/model_PersonalNameReligionedOut.jl")
include("models/model_PersonalNameSubdivisionIn.jl")
include("models/model_PersonalNameUSRaceEthnicityOut.jl")
include("models/model_ProperNounCategorizedOut.jl")
include("models/model_RegionISO.jl")
include("models/model_RegionOut.jl")
include("models/model_ReligionStatOut.jl")
include("models/model_SoftwareVersionOut.jl")
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 18389 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct AdminApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `AdminApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ AdminApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_anonymize_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_anonymize(_api::AdminApi, source::String, anonymized::Bool; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_anonymize_AdminApi, "/api2/json/anonymize/{source}/{anonymized}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "source", source) # type String
OpenAPI.Clients.set_param(_ctx.path, "anonymized", anonymized) # type Bool
OpenAPI.Clients.set_header_accept(_ctx, [])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Activate/deactivate anonymization for a source.
Params:
- source::String (required)
- anonymized::Bool (required)
Return: Nothing, OpenAPI.Clients.ApiResponse
"""
function anonymize(_api::AdminApi, source::String, anonymized::Bool; _mediaType=nothing)
_ctx = _oacinternal_anonymize(_api, source, anonymized; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function anonymize(_api::AdminApi, response_stream::Channel, source::String, anonymized::Bool; _mediaType=nothing)
_ctx = _oacinternal_anonymize(_api, source, anonymized; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_anonymize1_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIKeyOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_anonymize1(_api::AdminApi, source::String, anonymized::Bool, token::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_anonymize1_AdminApi, "/api2/json/anonymize/{source}/{anonymized}/{token}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "source", source) # type String
OpenAPI.Clients.set_param(_ctx.path, "anonymized", anonymized) # type Bool
OpenAPI.Clients.set_param(_ctx.path, "token", token) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Activate/deactivate anonymization for a source.
Params:
- source::String (required)
- anonymized::Bool (required)
- token::String (required)
Return: APIKeyOut, OpenAPI.Clients.ApiResponse
"""
function anonymize1(_api::AdminApi, source::String, anonymized::Bool, token::String; _mediaType=nothing)
_ctx = _oacinternal_anonymize1(_api, source, anonymized, token; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function anonymize1(_api::AdminApi, response_stream::Channel, source::String, anonymized::Bool, token::String; _mediaType=nothing)
_ctx = _oacinternal_anonymize1(_api, source, anonymized, token; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_api_key_info_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIKeyOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_api_key_info(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_api_key_info_AdminApi, "/api2/json/apiKeyInfo", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Read API Key info.
Params:
Return: APIKeyOut, OpenAPI.Clients.ApiResponse
"""
function api_key_info(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_api_key_info(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function api_key_info(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_api_key_info(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_api_status_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIClassifiersStatusOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_api_status(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_api_status_AdminApi, "/api2/json/apiStatus", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Prints the current status of the classifiers. A classifier name in apiStatus corresponds to a service name in apiServices.
Params:
Return: APIClassifiersStatusOut, OpenAPI.Clients.ApiResponse
"""
function api_status(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_api_status(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function api_status(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_api_status(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_api_usage_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIPeriodUsageOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_api_usage(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_api_usage_AdminApi, "/api2/json/apiUsage", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Print current API usage.
Params:
Return: APIPeriodUsageOut, OpenAPI.Clients.ApiResponse
"""
function api_usage(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_api_usage(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function api_usage(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_api_usage(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_api_usage_history_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIUsageHistoryOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_api_usage_history(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_api_usage_history_AdminApi, "/api2/json/apiUsageHistory", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Print historical API usage.
Params:
Return: APIUsageHistoryOut, OpenAPI.Clients.ApiResponse
"""
function api_usage_history(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_api_usage_history(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function api_usage_history(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_api_usage_history(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_api_usage_history_aggregate_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIUsageAggregatedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_api_usage_history_aggregate(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_api_usage_history_aggregate_AdminApi, "/api2/json/apiUsageHistoryAggregate", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Print historical API usage (in an aggregated view, by service, by day/hour/min).
Params:
Return: APIUsageAggregatedOut, OpenAPI.Clients.ApiResponse
"""
function api_usage_history_aggregate(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_api_usage_history_aggregate(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function api_usage_history_aggregate(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_api_usage_history_aggregate(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_available_services_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIServicesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_available_services(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_available_services_AdminApi, "/api2/json/apiServices", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""List of classification services and usage cost in Units per classification (default is 1=ONE Unit). Some API endpoints (ex. Corridor) combine multiple classifiers.
Params:
Return: APIServicesOut, OpenAPI.Clients.ApiResponse
"""
function available_services(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_available_services(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function available_services(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_available_services(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_disable_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_disable(_api::AdminApi, source::String, disabled::Bool; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_disable_AdminApi, "/api2/json/disable/{source}/{disabled}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "source", source) # type String
OpenAPI.Clients.set_param(_ctx.path, "disabled", disabled) # type Bool
OpenAPI.Clients.set_header_accept(_ctx, [])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Activate/deactivate an API Key.
Params:
- source::String (required)
- disabled::Bool (required)
Return: Nothing, OpenAPI.Clients.ApiResponse
"""
function disable(_api::AdminApi, source::String, disabled::Bool; _mediaType=nothing)
_ctx = _oacinternal_disable(_api, source, disabled; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function disable(_api::AdminApi, response_stream::Channel, source::String, disabled::Bool; _mediaType=nothing)
_ctx = _oacinternal_disable(_api, source, disabled; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_learnable_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIKeyOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_learnable(_api::AdminApi, source::String, learnable_param::Bool, token::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_learnable_AdminApi, "/api2/json/learnable/{source}/{learnable}/{token}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "source", source) # type String
OpenAPI.Clients.set_param(_ctx.path, "learnable", learnable_param) # type Bool
OpenAPI.Clients.set_param(_ctx.path, "token", token) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Activate/deactivate learning from a source.
Params:
- source::String (required)
- learnable_param::Bool (required)
- token::String (required)
Return: APIKeyOut, OpenAPI.Clients.ApiResponse
"""
function learnable(_api::AdminApi, source::String, learnable_param::Bool, token::String; _mediaType=nothing)
_ctx = _oacinternal_learnable(_api, source, learnable_param, token; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function learnable(_api::AdminApi, response_stream::Channel, source::String, learnable_param::Bool, token::String; _mediaType=nothing)
_ctx = _oacinternal_learnable(_api, source, learnable_param, token; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_learnable1_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_learnable1(_api::AdminApi, source::String, learnable::Bool; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_learnable1_AdminApi, "/api2/json/learnable/{source}/{learnable}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "source", source) # type String
OpenAPI.Clients.set_param(_ctx.path, "learnable", learnable) # type Bool
OpenAPI.Clients.set_header_accept(_ctx, [])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Activate/deactivate learning from a source.
Params:
- source::String (required)
- learnable::Bool (required)
Return: Nothing, OpenAPI.Clients.ApiResponse
"""
function learnable1(_api::AdminApi, source::String, learnable::Bool; _mediaType=nothing)
_ctx = _oacinternal_learnable1(_api, source, learnable; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function learnable1(_api::AdminApi, response_stream::Channel, source::String, learnable::Bool; _mediaType=nothing)
_ctx = _oacinternal_learnable1(_api, source, learnable; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_regions_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => RegionOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_regions(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_regions_AdminApi, "/api2/json/regions", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Print basic source statistics.
Params:
Return: RegionOut, OpenAPI.Clients.ApiResponse
"""
function regions(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_regions(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function regions(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_regions(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_software_version_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => SoftwareVersionOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_software_version(_api::AdminApi; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_software_version_AdminApi, "/api2/json/softwareVersion", ["api_key", ])
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Get the current software version
Params:
Return: SoftwareVersionOut, OpenAPI.Clients.ApiResponse
"""
function software_version(_api::AdminApi; _mediaType=nothing)
_ctx = _oacinternal_software_version(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function software_version(_api::AdminApi, response_stream::Channel; _mediaType=nothing)
_ctx = _oacinternal_software_version(_api; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_taxonomy_classes_AdminApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => APIClassifierTaxonomyOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_taxonomy_classes(_api::AdminApi, classifier_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_taxonomy_classes_AdminApi, "/api2/json/taxonomyClasses/{classifierName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "classifierName", classifier_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Print the taxonomy classes valid for the given classifier.
Params:
- classifier_name::String (required)
Return: APIClassifierTaxonomyOut, OpenAPI.Clients.ApiResponse
"""
function taxonomy_classes(_api::AdminApi, classifier_name::String; _mediaType=nothing)
_ctx = _oacinternal_taxonomy_classes(_api, classifier_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function taxonomy_classes(_api::AdminApi, response_stream::Channel, classifier_name::String; _mediaType=nothing)
_ctx = _oacinternal_taxonomy_classes(_api, classifier_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export anonymize
export anonymize1
export api_key_info
export api_status
export api_usage
export api_usage_history
export api_usage_history_aggregate
export available_services
export disable
export learnable
export learnable1
export regions
export software_version
export taxonomy_classes
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 25669 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct ChineseApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `ChineseApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ ChineseApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_chinese_name_candidates_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_chinese_name_candidates(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_chinese_name_candidates_ChineseApi, "/api2/json/chineseNameCandidates/{chineseSurnameLatin}/{chineseGivenNameLatin}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseSurnameLatin", chinese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "chineseGivenNameLatin", chinese_given_name_latin) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Identify Chinese name candidates, based on the romanized name ex. Wang Xiaoming
Params:
- chinese_surname_latin::String (required)
- chinese_given_name_latin::String (required)
Return: NameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function chinese_name_candidates(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String; _mediaType=nothing)
_ctx = _oacinternal_chinese_name_candidates(_api, chinese_surname_latin, chinese_given_name_latin; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function chinese_name_candidates(_api::ChineseApi, response_stream::Channel, chinese_surname_latin::String, chinese_given_name_latin::String; _mediaType=nothing)
_ctx = _oacinternal_chinese_name_candidates(_api, chinese_surname_latin, chinese_given_name_latin; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_chinese_name_candidates_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_chinese_name_candidates_batch(_api::ChineseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_chinese_name_candidates_batch_ChineseApi, "/api2/json/chineseNameCandidatesBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Identify Chinese name candidates, based on the romanized name (firstName = chineseGivenName; lastName=chineseSurname), ex. Wang Xiaoming
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchNameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function chinese_name_candidates_batch(_api::ChineseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_chinese_name_candidates_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function chinese_name_candidates_batch(_api::ChineseApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_chinese_name_candidates_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_chinese_name_candidates_gender_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_chinese_name_candidates_gender_batch(_api::ChineseApi; batch_first_last_name_gender_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_chinese_name_candidates_gender_batch_ChineseApi, "/api2/json/chineseNameCandidatesGenderBatch", ["api_key", ], batch_first_last_name_gender_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Identify Chinese name candidates, based on the romanized name (firstName = chineseGivenName; lastName=chineseSurname) ex. Wang Xiaoming.
Params:
- batch_first_last_name_gender_in::BatchFirstLastNameGenderIn
Return: BatchNameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function chinese_name_candidates_gender_batch(_api::ChineseApi; batch_first_last_name_gender_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_chinese_name_candidates_gender_batch(_api; batch_first_last_name_gender_in=batch_first_last_name_gender_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function chinese_name_candidates_gender_batch(_api::ChineseApi, response_stream::Channel; batch_first_last_name_gender_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_chinese_name_candidates_gender_batch(_api; batch_first_last_name_gender_in=batch_first_last_name_gender_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_chinese_name_gender_candidates_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_chinese_name_gender_candidates(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String, known_gender::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_chinese_name_gender_candidates_ChineseApi, "/api2/json/chineseNameGenderCandidates/{chineseSurnameLatin}/{chineseGivenNameLatin}/{knownGender}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseSurnameLatin", chinese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "chineseGivenNameLatin", chinese_given_name_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "knownGender", known_gender) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Identify Chinese name candidates, based on the romanized name ex. Wang Xiaoming - having a known gender ('male' or 'female')
Params:
- chinese_surname_latin::String (required)
- chinese_given_name_latin::String (required)
- known_gender::String (required)
Return: NameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function chinese_name_gender_candidates(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String, known_gender::String; _mediaType=nothing)
_ctx = _oacinternal_chinese_name_gender_candidates(_api, chinese_surname_latin, chinese_given_name_latin, known_gender; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function chinese_name_gender_candidates(_api::ChineseApi, response_stream::Channel, chinese_surname_latin::String, chinese_given_name_latin::String, known_gender::String; _mediaType=nothing)
_ctx = _oacinternal_chinese_name_gender_candidates(_api, chinese_surname_latin, chinese_given_name_latin, known_gender; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_chinese_name_match_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_chinese_name_match(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String, chinese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_chinese_name_match_ChineseApi, "/api2/json/chineseNameMatch/{chineseSurnameLatin}/{chineseGivenNameLatin}/{chineseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseSurnameLatin", chinese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "chineseGivenNameLatin", chinese_given_name_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "chineseName", chinese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Return a score for matching Chinese name ex. 王晓明 with a romanized name ex. Wang Xiaoming
Params:
- chinese_surname_latin::String (required)
- chinese_given_name_latin::String (required)
- chinese_name::String (required)
Return: NameMatchedOut, OpenAPI.Clients.ApiResponse
"""
function chinese_name_match(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_chinese_name_match(_api, chinese_surname_latin, chinese_given_name_latin, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function chinese_name_match(_api::ChineseApi, response_stream::Channel, chinese_surname_latin::String, chinese_given_name_latin::String, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_chinese_name_match(_api, chinese_surname_latin, chinese_given_name_latin, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_chinese_name_match_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_chinese_name_match_batch(_api::ChineseApi; batch_match_personal_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_chinese_name_match_batch_ChineseApi, "/api2/json/chineseNameMatchBatch", ["api_key", ], batch_match_personal_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Identify Chinese name candidates, based on the romanized name (firstName = chineseGivenName; lastName=chineseSurname), ex. Wang Xiaoming
Params:
- batch_match_personal_first_last_name_in::BatchMatchPersonalFirstLastNameIn
Return: BatchNameMatchedOut, OpenAPI.Clients.ApiResponse
"""
function chinese_name_match_batch(_api::ChineseApi; batch_match_personal_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_chinese_name_match_batch(_api; batch_match_personal_first_last_name_in=batch_match_personal_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function chinese_name_match_batch(_api::ChineseApi, response_stream::Channel; batch_match_personal_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_chinese_name_match_batch(_api; batch_match_personal_first_last_name_in=batch_match_personal_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_chinese_name_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_chinese_name(_api::ChineseApi, chinese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_chinese_name_ChineseApi, "/api2/json/genderChineseName/{chineseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseName", chinese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a Chinese full name ex. 王晓明
Params:
- chinese_name::String (required)
Return: PersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_chinese_name(_api::ChineseApi, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name(_api, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_chinese_name(_api::ChineseApi, response_stream::Channel, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name(_api, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_chinese_name_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_chinese_name_batch(_api::ChineseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_chinese_name_batch_ChineseApi, "/api2/json/genderChineseNameBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 full names ex. 王晓明
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_chinese_name_batch(_api::ChineseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_chinese_name_batch(_api::ChineseApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_chinese_name_pinyin_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_chinese_name_pinyin(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_chinese_name_pinyin_ChineseApi, "/api2/json/genderChineseNamePinyin/{chineseSurnameLatin}/{chineseGivenNameLatin}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseSurnameLatin", chinese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "chineseGivenNameLatin", chinese_given_name_latin) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a Chinese name in LATIN (Pinyin).
Params:
- chinese_surname_latin::String (required)
- chinese_given_name_latin::String (required)
Return: FirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_chinese_name_pinyin(_api::ChineseApi, chinese_surname_latin::String, chinese_given_name_latin::String; _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name_pinyin(_api, chinese_surname_latin, chinese_given_name_latin; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_chinese_name_pinyin(_api::ChineseApi, response_stream::Channel, chinese_surname_latin::String, chinese_given_name_latin::String; _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name_pinyin(_api, chinese_surname_latin, chinese_given_name_latin; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_chinese_name_pinyin_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_chinese_name_pinyin_batch(_api::ChineseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_chinese_name_pinyin_batch_ChineseApi, "/api2/json/genderChineseNamePinyinBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 Chinese names in LATIN (Pinyin).
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchFirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_chinese_name_pinyin_batch(_api::ChineseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name_pinyin_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_chinese_name_pinyin_batch(_api::ChineseApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_chinese_name_pinyin_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_chinese_name_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_chinese_name(_api::ChineseApi, chinese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_parse_chinese_name_ChineseApi, "/api2/json/parseChineseName/{chineseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseName", chinese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. 王晓明 -> 王(surname) 晓明(given name)
Params:
- chinese_name::String (required)
Return: PersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_chinese_name(_api::ChineseApi, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_parse_chinese_name(_api, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_chinese_name(_api::ChineseApi, response_stream::Channel, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_parse_chinese_name(_api, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_chinese_name_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_chinese_name_batch(_api::ChineseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_parse_chinese_name_batch_ChineseApi, "/api2/json/parseChineseNameBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. 王晓明 -> 王(surname) 晓明(given name).
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_chinese_name_batch(_api::ChineseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_chinese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_chinese_name_batch(_api::ChineseApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_chinese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_pinyin_chinese_name_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_pinyin_chinese_name(_api::ChineseApi, chinese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_pinyin_chinese_name_ChineseApi, "/api2/json/pinyinChineseName/{chineseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "chineseName", chinese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Romanize the Chinese name to Pinyin, ex. 王晓明 -> Wang (surname) Xiaoming (given name)
Params:
- chinese_name::String (required)
Return: PersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function pinyin_chinese_name(_api::ChineseApi, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_pinyin_chinese_name(_api, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function pinyin_chinese_name(_api::ChineseApi, response_stream::Channel, chinese_name::String; _mediaType=nothing)
_ctx = _oacinternal_pinyin_chinese_name(_api, chinese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_pinyin_chinese_name_batch_ChineseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_pinyin_chinese_name_batch(_api::ChineseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_pinyin_chinese_name_batch_ChineseApi, "/api2/json/pinyinChineseNameBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Romanize a list of Chinese name to Pinyin, ex. 王晓明 -> Wang (surname) Xiaoming (given name).
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function pinyin_chinese_name_batch(_api::ChineseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_pinyin_chinese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function pinyin_chinese_name_batch(_api::ChineseApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_pinyin_chinese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export chinese_name_candidates
export chinese_name_candidates_batch
export chinese_name_candidates_gender_batch
export chinese_name_gender_candidates
export chinese_name_match
export chinese_name_match_batch
export gender_chinese_name
export gender_chinese_name_batch
export gender_chinese_name_pinyin
export gender_chinese_name_pinyin_batch
export parse_chinese_name
export parse_chinese_name_batch
export pinyin_chinese_name
export pinyin_chinese_name_batch
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 6655 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct GeneralApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `GeneralApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ GeneralApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_name_type_GeneralApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => ProperNounCategorizedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_name_type(_api::GeneralApi, proper_noun::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_name_type_GeneralApi, "/api2/json/nameType/{properNoun}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "properNoun", proper_noun) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely type of a proper noun (personal name, brand name, place name etc.)
Params:
- proper_noun::String (required)
Return: ProperNounCategorizedOut, OpenAPI.Clients.ApiResponse
"""
function name_type(_api::GeneralApi, proper_noun::String; _mediaType=nothing)
_ctx = _oacinternal_name_type(_api, proper_noun; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function name_type(_api::GeneralApi, response_stream::Channel, proper_noun::String; _mediaType=nothing)
_ctx = _oacinternal_name_type(_api, proper_noun; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_name_type_batch_GeneralApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchProperNounCategorizedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_name_type_batch(_api::GeneralApi; batch_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_name_type_batch_GeneralApi, "/api2/json/nameTypeBatch", ["api_key", ], batch_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely common type of up to 100 proper nouns (personal name, brand name, place name etc.)
Params:
- batch_name_in::BatchNameIn
Return: BatchProperNounCategorizedOut, OpenAPI.Clients.ApiResponse
"""
function name_type_batch(_api::GeneralApi; batch_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_name_type_batch(_api; batch_name_in=batch_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function name_type_batch(_api::GeneralApi, response_stream::Channel; batch_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_name_type_batch(_api; batch_name_in=batch_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_name_type_geo_GeneralApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => ProperNounCategorizedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_name_type_geo(_api::GeneralApi, proper_noun::String, country_iso2::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_name_type_geo_GeneralApi, "/api2/json/nameTypeGeo/{properNoun}/{countryIso2}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "properNoun", proper_noun) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely type of a proper noun (personal name, brand name, place name etc.)
Params:
- proper_noun::String (required)
- country_iso2::String (required)
Return: ProperNounCategorizedOut, OpenAPI.Clients.ApiResponse
"""
function name_type_geo(_api::GeneralApi, proper_noun::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_name_type_geo(_api, proper_noun, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function name_type_geo(_api::GeneralApi, response_stream::Channel, proper_noun::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_name_type_geo(_api, proper_noun, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_name_type_geo_batch_GeneralApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchProperNounCategorizedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_name_type_geo_batch(_api::GeneralApi; batch_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_name_type_geo_batch_GeneralApi, "/api2/json/nameTypeGeoBatch", ["api_key", ], batch_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely common type of up to 100 proper nouns (personal name, brand name, place name etc.)
Params:
- batch_name_geo_in::BatchNameGeoIn
Return: BatchProperNounCategorizedOut, OpenAPI.Clients.ApiResponse
"""
function name_type_geo_batch(_api::GeneralApi; batch_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_name_type_geo_batch(_api; batch_name_geo_in=batch_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function name_type_geo_batch(_api::GeneralApi, response_stream::Channel; batch_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_name_type_geo_batch(_api; batch_name_geo_in=batch_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export name_type
export name_type_batch
export name_type_geo
export name_type_geo_batch
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 26839 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct IndianApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `IndianApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ IndianApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_caste_indian_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameCasteOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_caste_indian_batch(_api::IndianApi; batch_first_last_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_caste_indian_batch_IndianApi, "/api2/json/casteIndianBatch", ["api_key", ], batch_first_last_name_geo_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian name caste of up to 100 personal Indian Hindu names.
Params:
- batch_first_last_name_geo_subdivision_in::BatchFirstLastNameGeoSubdivisionIn
Return: BatchFirstLastNameCasteOut, OpenAPI.Clients.ApiResponse
"""
function caste_indian_batch(_api::IndianApi; batch_first_last_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_caste_indian_batch(_api; batch_first_last_name_geo_subdivision_in=batch_first_last_name_geo_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function caste_indian_batch(_api::IndianApi, response_stream::Channel; batch_first_last_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_caste_indian_batch(_api; batch_first_last_name_geo_subdivision_in=batch_first_last_name_geo_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_castegroup_indian_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameCastegroupOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_castegroup_indian(_api::IndianApi, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_castegroup_indian_IndianApi, "/api2/json/castegroupIndian/{subDivisionIso31662}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian name castegroup of a first / last name.
Params:
- sub_division_iso31662::String (required)
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameCastegroupOut, OpenAPI.Clients.ApiResponse
"""
function castegroup_indian(_api::IndianApi, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian(_api, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function castegroup_indian(_api::IndianApi, response_stream::Channel, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian(_api, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_castegroup_indian_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameCastegroupOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_castegroup_indian_batch(_api::IndianApi; batch_first_last_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_castegroup_indian_batch_IndianApi, "/api2/json/castegroupIndianBatch", ["api_key", ], batch_first_last_name_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian name castegroup of up to 100 personal first / last names.
Params:
- batch_first_last_name_subdivision_in::BatchFirstLastNameSubdivisionIn
Return: BatchFirstLastNameCastegroupOut, OpenAPI.Clients.ApiResponse
"""
function castegroup_indian_batch(_api::IndianApi; batch_first_last_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_batch(_api; batch_first_last_name_subdivision_in=batch_first_last_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function castegroup_indian_batch(_api::IndianApi, response_stream::Channel; batch_first_last_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_batch(_api; batch_first_last_name_subdivision_in=batch_first_last_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_castegroup_indian_full_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameCastegroupOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_castegroup_indian_full(_api::IndianApi, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_castegroup_indian_full_IndianApi, "/api2/json/castegroupIndianFull/{subDivisionIso31662}/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian name castegroup of a personal full name.
Params:
- sub_division_iso31662::String (required)
- personal_name_full::String (required)
Return: PersonalNameCastegroupOut, OpenAPI.Clients.ApiResponse
"""
function castegroup_indian_full(_api::IndianApi, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_full(_api, sub_division_iso31662, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function castegroup_indian_full(_api::IndianApi, response_stream::Channel, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_full(_api, sub_division_iso31662, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_castegroup_indian_full_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameCastegroupOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_castegroup_indian_full_batch(_api::IndianApi; batch_personal_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_castegroup_indian_full_batch_IndianApi, "/api2/json/castegroupIndianFullBatch", ["api_key", ], batch_personal_name_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian name castegroup of up to 100 personal full names.
Params:
- batch_personal_name_subdivision_in::BatchPersonalNameSubdivisionIn
Return: BatchPersonalNameCastegroupOut, OpenAPI.Clients.ApiResponse
"""
function castegroup_indian_full_batch(_api::IndianApi; batch_personal_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_full_batch(_api; batch_personal_name_subdivision_in=batch_personal_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function castegroup_indian_full_batch(_api::IndianApi, response_stream::Channel; batch_personal_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_full_batch(_api; batch_personal_name_subdivision_in=batch_personal_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_castegroup_indian_hindu_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameCasteOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_castegroup_indian_hindu(_api::IndianApi, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_castegroup_indian_hindu_IndianApi, "/api2/json/casteIndian/{subDivisionIso31662}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian name caste of a personal Hindu name.
Params:
- sub_division_iso31662::String (required)
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameCasteOut, OpenAPI.Clients.ApiResponse
"""
function castegroup_indian_hindu(_api::IndianApi, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_hindu(_api, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function castegroup_indian_hindu(_api::IndianApi, response_stream::Channel, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_castegroup_indian_hindu(_api, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion(_api::IndianApi, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_religion_IndianApi, "/api2/json/religionIndianFull/{subDivisionIso31662}/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of a personal Indian full name, provided the Indian state or Union territory (NB/ this can be inferred using the subclassification endpoint).
Params:
- sub_division_iso31662::String (required)
- personal_name_full::String (required)
Return: PersonalNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion(_api::IndianApi, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_religion(_api, sub_division_iso31662, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion(_api::IndianApi, response_stream::Channel, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_religion(_api, sub_division_iso31662, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion1_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion1(_api::IndianApi, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_religion1_IndianApi, "/api2/json/religionIndian/{subDivisionIso31662}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of a personal Indian first/last name, provided the Indian state or Union territory (NB/ this can be inferred using the subclassification endpoint).
Params:
- sub_division_iso31662::String (required)
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion1(_api::IndianApi, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_religion1(_api, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion1(_api::IndianApi, response_stream::Channel, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_religion1(_api, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion_indian_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion_indian_batch(_api::IndianApi; batch_first_last_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_religion_indian_batch_IndianApi, "/api2/json/religionIndianBatch", ["api_key", ], batch_first_last_name_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of up to 100 personal first/last Indian names, provided the subclassification at State or Union territory level (NB/ can be inferred using the subclassification endpoint).
Params:
- batch_first_last_name_subdivision_in::BatchFirstLastNameSubdivisionIn
Return: BatchFirstLastNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion_indian_batch(_api::IndianApi; batch_first_last_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_indian_batch(_api; batch_first_last_name_subdivision_in=batch_first_last_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion_indian_batch(_api::IndianApi, response_stream::Channel; batch_first_last_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_indian_batch(_api; batch_first_last_name_subdivision_in=batch_first_last_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion_indian_full_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion_indian_full_batch(_api::IndianApi; batch_personal_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_religion_indian_full_batch_IndianApi, "/api2/json/religionIndianFullBatch", ["api_key", ], batch_personal_name_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of up to 100 personal full Indian names, provided the subclassification at State or Union territory level (NB/ can be inferred using the subclassification endpoint).
Params:
- batch_personal_name_subdivision_in::BatchPersonalNameSubdivisionIn
Return: BatchPersonalNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion_indian_full_batch(_api::IndianApi; batch_personal_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_indian_full_batch(_api; batch_personal_name_subdivision_in=batch_personal_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion_indian_full_batch(_api::IndianApi, response_stream::Channel; batch_personal_name_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_indian_full_batch(_api; batch_personal_name_subdivision_in=batch_personal_name_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_indian_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_indian(_api::IndianApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_subclassification_indian_IndianApi, "/api2/json/subclassificationIndian/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian state of Union territory according to ISO 3166-2:IN based on the name.
Params:
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_indian(_api::IndianApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_indian(_api::IndianApi, response_stream::Channel, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_indian_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_indian_batch(_api::IndianApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_subclassification_indian_batch_IndianApi, "/api2/json/subclassificationIndianBatch", ["api_key", ], batch_first_last_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian state of Union territory according to ISO 3166-2:IN based on a list of up to 100 names.
Params:
- batch_first_last_name_geo_in::BatchFirstLastNameGeoIn
Return: BatchFirstLastNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_indian_batch(_api::IndianApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_indian_batch(_api::IndianApi, response_stream::Channel; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_indian_full_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_indian_full(_api::IndianApi, full_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_subclassification_indian_full_IndianApi, "/api2/json/subclassificationIndianFull/{fullName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "fullName", full_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian state of Union territory according to ISO 3166-2:IN based on the name.
Params:
- full_name::String (required)
Return: PersonalNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_indian_full(_api::IndianApi, full_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian_full(_api, full_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_indian_full(_api::IndianApi, response_stream::Channel, full_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian_full(_api, full_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_indian_full_batch_IndianApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_indian_full_batch(_api::IndianApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_subclassification_indian_full_batch_IndianApi, "/api2/json/subclassificationIndianFullBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely Indian state of Union territory according to ISO 3166-2:IN based on a list of up to 100 names.
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchPersonalNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_indian_full_batch(_api::IndianApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_indian_full_batch(_api::IndianApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_indian_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export caste_indian_batch
export castegroup_indian
export castegroup_indian_batch
export castegroup_indian_full
export castegroup_indian_full_batch
export castegroup_indian_hindu
export religion
export religion1
export religion_indian_batch
export religion_indian_full_batch
export subclassification_indian
export subclassification_indian_batch
export subclassification_indian_full
export subclassification_indian_full_batch
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 28999 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct JapaneseApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `JapaneseApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ JapaneseApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_gender_japanese_name_full_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_japanese_name_full(_api::JapaneseApi, japanese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_japanese_name_full_JapaneseApi, "/api2/json/genderJapaneseNameFull/{japaneseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseName", japanese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a Japanese full name ex. 王晓明
Params:
- japanese_name::String (required)
Return: PersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_japanese_name_full(_api::JapaneseApi, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_full(_api, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_japanese_name_full(_api::JapaneseApi, response_stream::Channel, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_full(_api, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_japanese_name_full_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_japanese_name_full_batch(_api::JapaneseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_japanese_name_full_batch_JapaneseApi, "/api2/json/genderJapaneseNameFullBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 full names
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_japanese_name_full_batch(_api::JapaneseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_full_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_japanese_name_full_batch(_api::JapaneseApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_full_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_japanese_name_pinyin_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_japanese_name_pinyin(_api::JapaneseApi, japanese_surname::String, japanese_given_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_japanese_name_pinyin_JapaneseApi, "/api2/json/genderJapaneseName/{japaneseSurname}/{japaneseGivenName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseSurname", japanese_surname) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseGivenName", japanese_given_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a Japanese name in LATIN (Pinyin).
Params:
- japanese_surname::String (required)
- japanese_given_name::String (required)
Return: FirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_japanese_name_pinyin(_api::JapaneseApi, japanese_surname::String, japanese_given_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_pinyin(_api, japanese_surname, japanese_given_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_japanese_name_pinyin(_api::JapaneseApi, response_stream::Channel, japanese_surname::String, japanese_given_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_pinyin(_api, japanese_surname, japanese_given_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_japanese_name_pinyin_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_japanese_name_pinyin_batch(_api::JapaneseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_japanese_name_pinyin_batch_JapaneseApi, "/api2/json/genderJapaneseNameBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 Japanese names in LATIN (Pinyin).
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchFirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_japanese_name_pinyin_batch(_api::JapaneseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_pinyin_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_japanese_name_pinyin_batch(_api::JapaneseApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_japanese_name_pinyin_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_gender_kanji_candidates_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_gender_kanji_candidates_batch(_api::JapaneseApi; batch_first_last_name_gender_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_japanese_name_gender_kanji_candidates_batch_JapaneseApi, "/api2/json/japaneseNameGenderKanjiCandidatesBatch", ["api_key", ], batch_first_last_name_gender_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Identify japanese name candidates in KANJI, based on the romanized name (firstName = japaneseGivenName; lastName=japaneseSurname) with KNOWN gender, ex. Yamamoto Sanae
Params:
- batch_first_last_name_gender_in::BatchFirstLastNameGenderIn
Return: BatchNameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_gender_kanji_candidates_batch(_api::JapaneseApi; batch_first_last_name_gender_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_gender_kanji_candidates_batch(_api; batch_first_last_name_gender_in=batch_first_last_name_gender_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_gender_kanji_candidates_batch(_api::JapaneseApi, response_stream::Channel; batch_first_last_name_gender_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_gender_kanji_candidates_batch(_api; batch_first_last_name_gender_in=batch_first_last_name_gender_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_kanji_candidates_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_kanji_candidates(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String, known_gender::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_japanese_name_kanji_candidates_JapaneseApi, "/api2/json/japaneseNameKanjiCandidates/{japaneseSurnameLatin}/{japaneseGivenNameLatin}/{knownGender}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseSurnameLatin", japanese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseGivenNameLatin", japanese_given_name_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "knownGender", known_gender) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Identify japanese name candidates in KANJI, based on the romanized name ex. Yamamoto Sanae - and a known gender.
Params:
- japanese_surname_latin::String (required)
- japanese_given_name_latin::String (required)
- known_gender::String (required)
Return: NameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_kanji_candidates(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String, known_gender::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_kanji_candidates(_api, japanese_surname_latin, japanese_given_name_latin, known_gender; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_kanji_candidates(_api::JapaneseApi, response_stream::Channel, japanese_surname_latin::String, japanese_given_name_latin::String, known_gender::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_kanji_candidates(_api, japanese_surname_latin, japanese_given_name_latin, known_gender; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_kanji_candidates1_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_kanji_candidates1(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_japanese_name_kanji_candidates1_JapaneseApi, "/api2/json/japaneseNameKanjiCandidates/{japaneseSurnameLatin}/{japaneseGivenNameLatin}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseSurnameLatin", japanese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseGivenNameLatin", japanese_given_name_latin) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Identify japanese name candidates in KANJI, based on the romanized name ex. Yamamoto Sanae
Params:
- japanese_surname_latin::String (required)
- japanese_given_name_latin::String (required)
Return: NameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_kanji_candidates1(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_kanji_candidates1(_api, japanese_surname_latin, japanese_given_name_latin; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_kanji_candidates1(_api::JapaneseApi, response_stream::Channel, japanese_surname_latin::String, japanese_given_name_latin::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_kanji_candidates1(_api, japanese_surname_latin, japanese_given_name_latin; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_kanji_candidates_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_kanji_candidates_batch(_api::JapaneseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_japanese_name_kanji_candidates_batch_JapaneseApi, "/api2/json/japaneseNameKanjiCandidatesBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Identify japanese name candidates in KANJI, based on the romanized name (firstName = japaneseGivenName; lastName=japaneseSurname), ex. Yamamoto Sanae
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchNameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_kanji_candidates_batch(_api::JapaneseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_kanji_candidates_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_kanji_candidates_batch(_api::JapaneseApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_kanji_candidates_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_latin_candidates_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_latin_candidates(_api::JapaneseApi, japanese_surname_kanji::String, japanese_given_name_kanji::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_japanese_name_latin_candidates_JapaneseApi, "/api2/json/japaneseNameLatinCandidates/{japaneseSurnameKanji}/{japaneseGivenNameKanji}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseSurnameKanji", japanese_surname_kanji) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseGivenNameKanji", japanese_given_name_kanji) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Romanize japanese name, based on the name in Kanji.
Params:
- japanese_surname_kanji::String (required)
- japanese_given_name_kanji::String (required)
Return: NameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_latin_candidates(_api::JapaneseApi, japanese_surname_kanji::String, japanese_given_name_kanji::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_latin_candidates(_api, japanese_surname_kanji, japanese_given_name_kanji; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_latin_candidates(_api::JapaneseApi, response_stream::Channel, japanese_surname_kanji::String, japanese_given_name_kanji::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_latin_candidates(_api, japanese_surname_kanji, japanese_given_name_kanji; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_latin_candidates_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchCandidatesOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_latin_candidates_batch(_api::JapaneseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_japanese_name_latin_candidates_batch_JapaneseApi, "/api2/json/japaneseNameLatinCandidatesBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Romanize japanese names, based on the name in KANJI
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchNameMatchCandidatesOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_latin_candidates_batch(_api::JapaneseApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_latin_candidates_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_latin_candidates_batch(_api::JapaneseApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_latin_candidates_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_match_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => NameMatchedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_match(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String, japanese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_japanese_name_match_JapaneseApi, "/api2/json/japaneseNameMatch/{japaneseSurnameLatin}/{japaneseGivenNameLatin}/{japaneseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseSurnameLatin", japanese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseGivenNameLatin", japanese_given_name_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseName", japanese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Return a score for matching Japanese name in KANJI ex. 山本 早苗 with a romanized name ex. Yamamoto Sanae
Params:
- japanese_surname_latin::String (required)
- japanese_given_name_latin::String (required)
- japanese_name::String (required)
Return: NameMatchedOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_match(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_match(_api, japanese_surname_latin, japanese_given_name_latin, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_match(_api::JapaneseApi, response_stream::Channel, japanese_surname_latin::String, japanese_given_name_latin::String, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_match(_api, japanese_surname_latin, japanese_given_name_latin, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_match_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchNameMatchedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_match_batch(_api::JapaneseApi; batch_match_personal_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_japanese_name_match_batch_JapaneseApi, "/api2/json/japaneseNameMatchBatch", ["api_key", ], batch_match_personal_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Return a score for matching a list of Japanese names in KANJI ex. 山本 早苗 with romanized names ex. Yamamoto Sanae
Params:
- batch_match_personal_first_last_name_in::BatchMatchPersonalFirstLastNameIn
Return: BatchNameMatchedOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_match_batch(_api::JapaneseApi; batch_match_personal_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_match_batch(_api; batch_match_personal_first_last_name_in=batch_match_personal_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_match_batch(_api::JapaneseApi, response_stream::Channel; batch_match_personal_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_japanese_name_match_batch(_api; batch_match_personal_first_last_name_in=batch_match_personal_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_japanese_name_match_feedback_loop_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FeedbackLoopOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_japanese_name_match_feedback_loop(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String, japanese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_japanese_name_match_feedback_loop_JapaneseApi, "/api2/json/japaneseNameMatchFeedbackLoop/{japaneseSurnameLatin}/{japaneseGivenNameLatin}/{japaneseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseSurnameLatin", japanese_surname_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseGivenNameLatin", japanese_given_name_latin) # type String
OpenAPI.Clients.set_param(_ctx.path, "japaneseName", japanese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[CREDITS 1 UNIT] Feedback loop to better perform matching Japanese name in KANJI ex. 山本 早苗 with a romanized name ex. Yamamoto Sanae
Params:
- japanese_surname_latin::String (required)
- japanese_given_name_latin::String (required)
- japanese_name::String (required)
Return: FeedbackLoopOut, OpenAPI.Clients.ApiResponse
"""
function japanese_name_match_feedback_loop(_api::JapaneseApi, japanese_surname_latin::String, japanese_given_name_latin::String, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_match_feedback_loop(_api, japanese_surname_latin, japanese_given_name_latin, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function japanese_name_match_feedback_loop(_api::JapaneseApi, response_stream::Channel, japanese_surname_latin::String, japanese_given_name_latin::String, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_japanese_name_match_feedback_loop(_api, japanese_surname_latin, japanese_given_name_latin, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_japanese_name_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_japanese_name(_api::JapaneseApi, japanese_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_parse_japanese_name_JapaneseApi, "/api2/json/parseJapaneseName/{japaneseName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "japaneseName", japanese_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. 山本 早苗 or Yamamoto Sanae
Params:
- japanese_name::String (required)
Return: PersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_japanese_name(_api::JapaneseApi, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_parse_japanese_name(_api, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_japanese_name(_api::JapaneseApi, response_stream::Channel, japanese_name::String; _mediaType=nothing)
_ctx = _oacinternal_parse_japanese_name(_api, japanese_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_japanese_name_batch_JapaneseApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_japanese_name_batch(_api::JapaneseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_parse_japanese_name_batch_JapaneseApi, "/api2/json/parseJapaneseNameBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. 山本 早苗 or Yamamoto Sanae
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_japanese_name_batch(_api::JapaneseApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_japanese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_japanese_name_batch(_api::JapaneseApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_japanese_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export gender_japanese_name_full
export gender_japanese_name_full_batch
export gender_japanese_name_pinyin
export gender_japanese_name_pinyin_batch
export japanese_name_gender_kanji_candidates_batch
export japanese_name_kanji_candidates
export japanese_name_kanji_candidates1
export japanese_name_kanji_candidates_batch
export japanese_name_latin_candidates
export japanese_name_latin_candidates_batch
export japanese_name_match
export japanese_name_match_batch
export japanese_name_match_feedback_loop
export parse_japanese_name
export parse_japanese_name_batch
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 82248 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct PersonalApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `PersonalApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ PersonalApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_community_engage_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => CommunityEngageOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_community_engage(_api::PersonalApi, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_community_engage_PersonalApi, "/api2/json/communityEngage/{countryIso2}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME] Infer the likely ethnicity/diaspora, country, gender of a personal name, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.) for community engagement (require special module/pricing)
Params:
- country_iso2::String (required)
- first_name::String (required)
- last_name::String (required)
Return: CommunityEngageOut, OpenAPI.Clients.ApiResponse
"""
function community_engage(_api::PersonalApi, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_community_engage(_api, country_iso2, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function community_engage(_api::PersonalApi, response_stream::Channel, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_community_engage(_api, country_iso2, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_community_engage_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchCommunityEngageOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_community_engage_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_community_engage_batch_PersonalApi, "/api2/json/communityEngageBatch", ["api_key", ], batch_first_last_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely ethnicity/diaspora, country, gender of up to 100 personal names, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.) for community engagement (require special module/pricing)
Params:
- batch_first_last_name_geo_in::BatchFirstLastNameGeoIn
Return: BatchCommunityEngageOut, OpenAPI.Clients.ApiResponse
"""
function community_engage_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_community_engage_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function community_engage_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_community_engage_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_community_engage_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => CommunityEngageOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_community_engage_full(_api::PersonalApi, country_iso2::String, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_community_engage_full_PersonalApi, "/api2/json/communityEngageFull/{countryIso2}/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME] Infer the likely ethnicity/diaspora, country, gender of a personal name, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.) for community engagement (require special module/pricing)
Params:
- country_iso2::String (required)
- personal_name_full::String (required)
Return: CommunityEngageOut, OpenAPI.Clients.ApiResponse
"""
function community_engage_full(_api::PersonalApi, country_iso2::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_community_engage_full(_api, country_iso2, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function community_engage_full(_api::PersonalApi, response_stream::Channel, country_iso2::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_community_engage_full(_api, country_iso2, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_community_engage_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchCommunityEngageFullOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_community_engage_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_community_engage_full_batch_PersonalApi, "/api2/json/communityEngageFullBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely ethnicity/diaspora, country, gender of up to 100 personal names, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.) for community engagement (require special module/pricing)
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchCommunityEngageFullOut, OpenAPI.Clients.ApiResponse
"""
function community_engage_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_community_engage_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function community_engage_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_community_engage_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_corridor_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => CorridorOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_corridor(_api::PersonalApi, country_iso2_from::String, first_name_from::String, last_name_from::String, country_iso2_to::String, first_name_to::String, last_name_to::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_corridor_PersonalApi, "/api2/json/corridor/{countryIso2From}/{firstNameFrom}/{lastNameFrom}/{countryIso2To}/{firstNameTo}/{lastNameTo}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2From", country_iso2_from) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstNameFrom", first_name_from) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastNameFrom", last_name_from) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2To", country_iso2_to) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstNameTo", first_name_to) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastNameTo", last_name_to) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME COUPLE] Infer several classifications for a cross border interaction between names (ex. remit, travel, intl com)
Params:
- country_iso2_from::String (required)
- first_name_from::String (required)
- last_name_from::String (required)
- country_iso2_to::String (required)
- first_name_to::String (required)
- last_name_to::String (required)
Return: CorridorOut, OpenAPI.Clients.ApiResponse
"""
function corridor(_api::PersonalApi, country_iso2_from::String, first_name_from::String, last_name_from::String, country_iso2_to::String, first_name_to::String, last_name_to::String; _mediaType=nothing)
_ctx = _oacinternal_corridor(_api, country_iso2_from, first_name_from, last_name_from, country_iso2_to, first_name_to, last_name_to; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function corridor(_api::PersonalApi, response_stream::Channel, country_iso2_from::String, first_name_from::String, last_name_from::String, country_iso2_to::String, first_name_to::String, last_name_to::String; _mediaType=nothing)
_ctx = _oacinternal_corridor(_api, country_iso2_from, first_name_from, last_name_from, country_iso2_to, first_name_to, last_name_to; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_corridor_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchCorridorOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_corridor_batch(_api::PersonalApi; batch_corridor_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_corridor_batch_PersonalApi, "/api2/json/corridorBatch", ["api_key", ], batch_corridor_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME PAIR] Infer several classifications for up to 100 cross border interaction between names (ex. remit, travel, intl com)
Params:
- batch_corridor_in::BatchCorridorIn
Return: BatchCorridorOut, OpenAPI.Clients.ApiResponse
"""
function corridor_batch(_api::PersonalApi; batch_corridor_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_corridor_batch(_api; batch_corridor_in=batch_corridor_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function corridor_batch(_api::PersonalApi, response_stream::Channel; batch_corridor_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_corridor_batch(_api; batch_corridor_in=batch_corridor_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_country_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameGeoOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_country(_api::PersonalApi, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_country_PersonalApi, "/api2/json/country/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of residence of a personal full name, or one surname. Assumes names as they are in the country of residence OR the country of origin.
Params:
- personal_name_full::String (required)
Return: PersonalNameGeoOut, OpenAPI.Clients.ApiResponse
"""
function country(_api::PersonalApi, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_country(_api, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function country(_api::PersonalApi, response_stream::Channel, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_country(_api, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_country_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGeoOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_country_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_country_batch_PersonalApi, "/api2/json/countryBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of residence of up to 100 personal full names, or surnames. Assumes names as they are in the country of residence OR the country of origin.
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameGeoOut, OpenAPI.Clients.ApiResponse
"""
function country_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_country_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function country_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_country_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_country_fn_ln_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameOriginedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_country_fn_ln(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_country_fn_ln_PersonalApi, "/api2/json/countryFnLn/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of residence of a personal first / last name, or one surname. Assumes names as they are in the country of residence OR the country of origin.
Params:
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameOriginedOut, OpenAPI.Clients.ApiResponse
"""
function country_fn_ln(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_country_fn_ln(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function country_fn_ln(_api::PersonalApi, response_stream::Channel, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_country_fn_ln(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_country_fn_ln_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGeoOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_country_fn_ln_batch(_api::PersonalApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_country_fn_ln_batch_PersonalApi, "/api2/json/countryFnLnBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of residence of up to 100 personal first / last names, or surnames. Assumes names as they are in the country of residence OR the country of origin.
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchFirstLastNameGeoOut, OpenAPI.Clients.ApiResponse
"""
function country_fn_ln_batch(_api::PersonalApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_country_fn_ln_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function country_fn_ln_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_country_fn_ln_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_diaspora_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameDiasporaedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_diaspora(_api::PersonalApi, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_diaspora_PersonalApi, "/api2/json/diaspora/{countryIso2}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME] Infer the likely ethnicity/diaspora of a personal name, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.)
Params:
- country_iso2::String (required)
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameDiasporaedOut, OpenAPI.Clients.ApiResponse
"""
function diaspora(_api::PersonalApi, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_diaspora(_api, country_iso2, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function diaspora(_api::PersonalApi, response_stream::Channel, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_diaspora(_api, country_iso2, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_diaspora_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameDiasporaedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_diaspora_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_diaspora_batch_PersonalApi, "/api2/json/diasporaBatch", ["api_key", ], batch_first_last_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME] Infer the likely ethnicity/diaspora of up to 100 personal names, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.)
Params:
- batch_first_last_name_geo_in::BatchFirstLastNameGeoIn
Return: BatchFirstLastNameDiasporaedOut, OpenAPI.Clients.ApiResponse
"""
function diaspora_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_diaspora_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function diaspora_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_diaspora_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_diaspora_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameDiasporaedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_diaspora_full(_api::PersonalApi, country_iso2::String, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_diaspora_full_PersonalApi, "/api2/json/diasporaFull/{countryIso2}/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME] Infer the likely ethnicity/diaspora of a personal name, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.)
Params:
- country_iso2::String (required)
- personal_name_full::String (required)
Return: PersonalNameDiasporaedOut, OpenAPI.Clients.ApiResponse
"""
function diaspora_full(_api::PersonalApi, country_iso2::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_diaspora_full(_api, country_iso2, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function diaspora_full(_api::PersonalApi, response_stream::Channel, country_iso2::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_diaspora_full(_api, country_iso2, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_diaspora_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameDiasporaedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_diaspora_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_diaspora_full_batch_PersonalApi, "/api2/json/diasporaFullBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 20 UNITS PER NAME] Infer the likely ethnicity/diaspora of up to 100 personal names, given a country of residence ISO2 code (ex. US, CA, AU, NZ etc.)
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchPersonalNameDiasporaedOut, OpenAPI.Clients.ApiResponse
"""
function diaspora_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_diaspora_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function diaspora_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_diaspora_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender(_api::PersonalApi, first_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_PersonalApi, "/api2/json/gender/{firstName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a just a fiven name, assuming default 'US' local context. Please use preferably full names and local geographic context for better accuracy.
Params:
- first_name::String (required)
Return: FirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender(_api::PersonalApi, first_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender(_api, first_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender(_api::PersonalApi, response_stream::Channel, first_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender(_api, first_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender1_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender1(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender1_PersonalApi, "/api2/json/gender/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a name.
Params:
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender1(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender1(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender1(_api::PersonalApi, response_stream::Channel, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender1(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_batch(_api::PersonalApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_batch_PersonalApi, "/api2/json/genderBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 names, detecting automatically the cultural context.
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchFirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_batch(_api::PersonalApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_full(_api::PersonalApi, full_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_full_PersonalApi, "/api2/json/genderFull/{fullName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "fullName", full_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a full name, ex. John H. Smith
Params:
- full_name::String (required)
Return: PersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_full(_api::PersonalApi, full_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_full(_api, full_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_full(_api::PersonalApi, response_stream::Channel, full_name::String; _mediaType=nothing)
_ctx = _oacinternal_gender_full(_api, full_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_full_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_full_batch_PersonalApi, "/api2/json/genderFullBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 full names, detecting automatically the cultural context.
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_full_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_full_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_full_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_full_geo_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_full_geo(_api::PersonalApi, full_name::String, country_iso2::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_full_geo_PersonalApi, "/api2/json/genderFullGeo/{fullName}/{countryIso2}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "fullName", full_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a full name, given a local context (ISO2 country code).
Params:
- full_name::String (required)
- country_iso2::String (required)
Return: PersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_full_geo(_api::PersonalApi, full_name::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_gender_full_geo(_api, full_name, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_full_geo(_api::PersonalApi, response_stream::Channel, full_name::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_gender_full_geo(_api, full_name, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_full_geo_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_full_geo_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_full_geo_batch_PersonalApi, "/api2/json/genderFullGeoBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 full names, with a given cultural context (country ISO2 code).
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchPersonalNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_full_geo_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_full_geo_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_full_geo_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_full_geo_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_geo_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_geo(_api::PersonalApi, first_name::String, last_name::String, country_iso2::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_gender_geo_PersonalApi, "/api2/json/genderGeo/{firstName}/{lastName}/{countryIso2}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of a name, given a local context (ISO2 country code).
Params:
- first_name::String (required)
- last_name::String (required)
- country_iso2::String (required)
Return: FirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_geo(_api::PersonalApi, first_name::String, last_name::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_gender_geo(_api, first_name, last_name, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_geo(_api::PersonalApi, response_stream::Channel, first_name::String, last_name::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_gender_geo(_api, first_name, last_name, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_gender_geo_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGenderedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_gender_geo_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_gender_geo_batch_PersonalApi, "/api2/json/genderGeoBatch", ["api_key", ], batch_first_last_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely gender of up to 100 names, each given a local context (ISO2 country code).
Params:
- batch_first_last_name_geo_in::BatchFirstLastNameGeoIn
Return: BatchFirstLastNameGenderedOut, OpenAPI.Clients.ApiResponse
"""
function gender_geo_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_geo_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function gender_geo_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_gender_geo_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_origin_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameOriginedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_origin(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_origin_PersonalApi, "/api2/json/origin/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of origin of a personal name. Assumes names as they are in the country of origin. For US, CA, AU, NZ and other melting-pots : use 'diaspora' instead.
Params:
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameOriginedOut, OpenAPI.Clients.ApiResponse
"""
function origin(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_origin(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function origin(_api::PersonalApi, response_stream::Channel, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_origin(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_origin_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameOriginedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_origin_batch(_api::PersonalApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_origin_batch_PersonalApi, "/api2/json/originBatch", ["api_key", ], batch_first_last_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of origin of up to 100 names, detecting automatically the cultural context.
Params:
- batch_first_last_name_in::BatchFirstLastNameIn
Return: BatchFirstLastNameOriginedOut, OpenAPI.Clients.ApiResponse
"""
function origin_batch(_api::PersonalApi; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_origin_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function origin_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_origin_batch(_api; batch_first_last_name_in=batch_first_last_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_origin_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameOriginedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_origin_full(_api::PersonalApi, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_origin_full_PersonalApi, "/api2/json/originFull/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of origin of a personal name. Assumes names as they are in the country of origin. For US, CA, AU, NZ and other melting-pots : use 'diaspora' instead.
Params:
- personal_name_full::String (required)
Return: PersonalNameOriginedOut, OpenAPI.Clients.ApiResponse
"""
function origin_full(_api::PersonalApi, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_origin_full(_api, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function origin_full(_api::PersonalApi, response_stream::Channel, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_origin_full(_api, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_origin_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameOriginedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_origin_full_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_origin_full_batch_PersonalApi, "/api2/json/originFullBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely country of origin of up to 100 names, detecting automatically the cultural context.
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameOriginedOut, OpenAPI.Clients.ApiResponse
"""
function origin_full_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_origin_full_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function origin_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_origin_full_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_name_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_name(_api::PersonalApi, name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_parse_name_PersonalApi, "/api2/json/parseName/{nameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "nameFull", name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. John Smith or SMITH, John or SMITH; John.
Params:
- name_full::String (required)
Return: PersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_name(_api::PersonalApi, name_full::String; _mediaType=nothing)
_ctx = _oacinternal_parse_name(_api, name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_name(_api::PersonalApi, response_stream::Channel, name_full::String; _mediaType=nothing)
_ctx = _oacinternal_parse_name(_api, name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_name_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_name_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_parse_name_batch_PersonalApi, "/api2/json/parseNameBatch", ["api_key", ], batch_personal_name_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. John Smith or SMITH, John or SMITH; John.
Params:
- batch_personal_name_in::BatchPersonalNameIn
Return: BatchPersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_name_batch(_api::PersonalApi; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_name_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_name_batch(_api; batch_personal_name_in=batch_personal_name_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_name_geo_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_name_geo(_api::PersonalApi, name_full::String, country_iso2::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_parse_name_geo_PersonalApi, "/api2/json/parseName/{nameFull}/{countryIso2}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "nameFull", name_full) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. John Smith or SMITH, John or SMITH; John. For better accuracy, provide a geographic context.
Params:
- name_full::String (required)
- country_iso2::String (required)
Return: PersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_name_geo(_api::PersonalApi, name_full::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_parse_name_geo(_api, name_full, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_name_geo(_api::PersonalApi, response_stream::Channel, name_full::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_parse_name_geo(_api, name_full, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_parse_name_geo_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameParsedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_parse_name_geo_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_parse_name_geo_batch_PersonalApi, "/api2/json/parseNameGeoBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""Infer the likely first/last name structure of a name, ex. John Smith or SMITH, John or SMITH; John. Giving a local context improves precision.
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchPersonalNameParsedOut, OpenAPI.Clients.ApiResponse
"""
function parse_name_geo_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_name_geo_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function parse_name_geo_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_parse_name_geo_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion2_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion2(_api::PersonalApi, country_iso2::String, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_religion2_PersonalApi, "/api2/json/religion/{countryIso2}/{subDivisionIso31662}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of a personal first/last name. NB: only for INDIA (as of current version).
Params:
- country_iso2::String (required)
- sub_division_iso31662::String (required)
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion2(_api::PersonalApi, country_iso2::String, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_religion2(_api, country_iso2, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion2(_api::PersonalApi, response_stream::Channel, country_iso2::String, sub_division_iso31662::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_religion2(_api, country_iso2, sub_division_iso31662, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion_batch(_api::PersonalApi; batch_first_last_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_religion_batch_PersonalApi, "/api2/json/religionBatch", ["api_key", ], batch_first_last_name_geo_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of up to 100 personal first/last names. NB: only for India as of currently.
Params:
- batch_first_last_name_geo_subdivision_in::BatchFirstLastNameGeoSubdivisionIn
Return: BatchFirstLastNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion_batch(_api::PersonalApi; batch_first_last_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_batch(_api; batch_first_last_name_geo_subdivision_in=batch_first_last_name_geo_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_batch(_api; batch_first_last_name_geo_subdivision_in=batch_first_last_name_geo_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion_full(_api::PersonalApi, country_iso2::String, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_religion_full_PersonalApi, "/api2/json/religionFull/{countryIso2}/{subDivisionIso31662}/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "subDivisionIso31662", sub_division_iso31662) # type String
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of a personal full name. NB: only for INDIA (as of current version).
Params:
- country_iso2::String (required)
- sub_division_iso31662::String (required)
- personal_name_full::String (required)
Return: PersonalNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion_full(_api::PersonalApi, country_iso2::String, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_religion_full(_api, country_iso2, sub_division_iso31662, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion_full(_api::PersonalApi, response_stream::Channel, country_iso2::String, sub_division_iso31662::String, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_religion_full(_api, country_iso2, sub_division_iso31662, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_religion_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameReligionedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_religion_full_batch(_api::PersonalApi; batch_personal_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_religion_full_batch_PersonalApi, "/api2/json/religionFullBatch", ["api_key", ], batch_personal_name_geo_subdivision_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely religion of up to 100 personal full names. NB: only for India as of currently.
Params:
- batch_personal_name_geo_subdivision_in::BatchPersonalNameGeoSubdivisionIn
Return: BatchPersonalNameReligionedOut, OpenAPI.Clients.ApiResponse
"""
function religion_full_batch(_api::PersonalApi; batch_personal_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_full_batch(_api; batch_personal_name_geo_subdivision_in=batch_personal_name_geo_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function religion_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_subdivision_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_religion_full_batch(_api; batch_personal_name_geo_subdivision_in=batch_personal_name_geo_subdivision_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification(_api::PersonalApi, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_subclassification_PersonalApi, "/api2/json/subclassification/{countryIso2}/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely origin of a name at a country subclassification level (state or regeion). Initially, this is only supported for India (ISO2 code 'IN').
Params:
- country_iso2::String (required)
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification(_api::PersonalApi, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification(_api, country_iso2, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification(_api::PersonalApi, response_stream::Channel, country_iso2::String, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification(_api, country_iso2, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_subclassification_batch_PersonalApi, "/api2/json/subclassificationBatch", ["api_key", ], batch_first_last_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely origin of a list of up to 100 names at a country subclassification level (state or regeion). Initially, this is only supported for India (ISO2 code 'IN').
Params:
- batch_first_last_name_geo_in::BatchFirstLastNameGeoIn
Return: BatchFirstLastNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_full(_api::PersonalApi, country_iso2::String, full_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_subclassification_full_PersonalApi, "/api2/json/subclassificationFull/{countryIso2}/{fullName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_param(_ctx.path, "fullName", full_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely origin of a name at a country subclassification level (state or regeion). Initially, this is only supported for India (ISO2 code 'IN').
Params:
- country_iso2::String (required)
- full_name::String (required)
Return: FirstLastNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_full(_api::PersonalApi, country_iso2::String, full_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification_full(_api, country_iso2, full_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_full(_api::PersonalApi, response_stream::Channel, country_iso2::String, full_name::String; _mediaType=nothing)
_ctx = _oacinternal_subclassification_full(_api, country_iso2, full_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_subclassification_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameGeoSubclassificationOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_subclassification_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_subclassification_full_batch_PersonalApi, "/api2/json/subclassificationFullBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer the likely origin of a list of up to 100 names at a country subclassification level (state or regeion). Initially, this is only supported for India (ISO2 code 'IN').
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchPersonalNameGeoSubclassificationOut, OpenAPI.Clients.ApiResponse
"""
function subclassification_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function subclassification_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_subclassification_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_us_race_ethnicity_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameUSRaceEthnicityOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_us_race_ethnicity(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_us_race_ethnicity_PersonalApi, "/api2/json/usRaceEthnicity/{firstName}/{lastName}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer a US resident's likely race/ethnicity according to US Census taxonomy W_NL (white, non latino), HL (hispano latino), A (asian, non latino), B_NL (black, non latino). Optionally add header X-OPTION-USRACEETHNICITY-TAXONOMY: USRACEETHNICITY-6CLASSES for two additional classes, AI_AN (American Indian or Alaskan Native) and PI (Pacific Islander).
Params:
- first_name::String (required)
- last_name::String (required)
Return: FirstLastNameUSRaceEthnicityOut, OpenAPI.Clients.ApiResponse
"""
function us_race_ethnicity(_api::PersonalApi, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function us_race_ethnicity(_api::PersonalApi, response_stream::Channel, first_name::String, last_name::String; _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity(_api, first_name, last_name; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_us_race_ethnicity_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameUSRaceEthnicityOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_us_race_ethnicity_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_us_race_ethnicity_batch_PersonalApi, "/api2/json/usRaceEthnicityBatch", ["api_key", ], batch_first_last_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer up-to 100 US resident's likely race/ethnicity according to US Census taxonomy. Output is W_NL (white, non latino), HL (hispano latino), A (asian, non latino), B_NL (black, non latino). Optionally add header X-OPTION-USRACEETHNICITY-TAXONOMY: USRACEETHNICITY-6CLASSES for two additional classes, AI_AN (American Indian or Alaskan Native) and PI (Pacific Islander).
Params:
- batch_first_last_name_geo_in::BatchFirstLastNameGeoIn
Return: BatchFirstLastNameUSRaceEthnicityOut, OpenAPI.Clients.ApiResponse
"""
function us_race_ethnicity_batch(_api::PersonalApi; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function us_race_ethnicity_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_batch(_api; batch_first_last_name_geo_in=batch_first_last_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_us_race_ethnicity_full_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => PersonalNameUSRaceEthnicityOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_us_race_ethnicity_full(_api::PersonalApi, personal_name_full::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_us_race_ethnicity_full_PersonalApi, "/api2/json/usRaceEthnicityFull/{personalNameFull}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "personalNameFull", personal_name_full) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer a US resident's likely race/ethnicity according to US Census taxonomy W_NL (white, non latino), HL (hispano latino), A (asian, non latino), B_NL (black, non latino). Optionally add header X-OPTION-USRACEETHNICITY-TAXONOMY: USRACEETHNICITY-6CLASSES for two additional classes, AI_AN (American Indian or Alaskan Native) and PI (Pacific Islander).
Params:
- personal_name_full::String (required)
Return: PersonalNameUSRaceEthnicityOut, OpenAPI.Clients.ApiResponse
"""
function us_race_ethnicity_full(_api::PersonalApi, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_full(_api, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function us_race_ethnicity_full(_api::PersonalApi, response_stream::Channel, personal_name_full::String; _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_full(_api, personal_name_full; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_us_race_ethnicity_full_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchPersonalNameUSRaceEthnicityOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_us_race_ethnicity_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_us_race_ethnicity_full_batch_PersonalApi, "/api2/json/usRaceEthnicityFullBatch", ["api_key", ], batch_personal_name_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer up-to 100 US resident's likely race/ethnicity according to US Census taxonomy. Output is W_NL (white, non latino), HL (hispano latino), A (asian, non latino), B_NL (black, non latino). Optionally add header X-OPTION-USRACEETHNICITY-TAXONOMY: USRACEETHNICITY-6CLASSES for two additional classes, AI_AN (American Indian or Alaskan Native) and PI (Pacific Islander).
Params:
- batch_personal_name_geo_in::BatchPersonalNameGeoIn
Return: BatchPersonalNameUSRaceEthnicityOut, OpenAPI.Clients.ApiResponse
"""
function us_race_ethnicity_full_batch(_api::PersonalApi; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function us_race_ethnicity_full_batch(_api::PersonalApi, response_stream::Channel; batch_personal_name_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_full_batch(_api; batch_personal_name_geo_in=batch_personal_name_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_us_race_ethnicity_z_i_p5_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNameUSRaceEthnicityOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_us_race_ethnicity_z_i_p5(_api::PersonalApi, first_name::String, last_name::String, zip5_code::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_us_race_ethnicity_z_i_p5_PersonalApi, "/api2/json/usRaceEthnicityZIP5/{firstName}/{lastName}/{zip5Code}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "zip5Code", zip5_code) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer a US resident's likely race/ethnicity according to US Census taxonomy, using (optional) ZIP5 code info. Output is W_NL (white, non latino), HL (hispano latino), A (asian, non latino), B_NL (black, non latino). Optionally add header X-OPTION-USRACEETHNICITY-TAXONOMY: USRACEETHNICITY-6CLASSES for two additional classes, AI_AN (American Indian or Alaskan Native) and PI (Pacific Islander).
Params:
- first_name::String (required)
- last_name::String (required)
- zip5_code::String (required)
Return: FirstLastNameUSRaceEthnicityOut, OpenAPI.Clients.ApiResponse
"""
function us_race_ethnicity_z_i_p5(_api::PersonalApi, first_name::String, last_name::String, zip5_code::String; _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_z_i_p5(_api, first_name, last_name, zip5_code; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function us_race_ethnicity_z_i_p5(_api::PersonalApi, response_stream::Channel, first_name::String, last_name::String, zip5_code::String; _mediaType=nothing)
_ctx = _oacinternal_us_race_ethnicity_z_i_p5(_api, first_name, last_name, zip5_code; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_us_zip_race_ethnicity_batch_PersonalApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNameUSRaceEthnicityOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_us_zip_race_ethnicity_batch(_api::PersonalApi; batch_first_last_name_geo_zipped_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_us_zip_race_ethnicity_batch_PersonalApi, "/api2/json/usZipRaceEthnicityBatch", ["api_key", ], batch_first_last_name_geo_zipped_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 10 UNITS PER NAME] Infer up-to 100 US resident's likely race/ethnicity according to US Census taxonomy, with (optional) ZIP code. Output is W_NL (white, non latino), HL (hispano latino), A (asian, non latino), B_NL (black, non latino). Optionally add header X-OPTION-USRACEETHNICITY-TAXONOMY: USRACEETHNICITY-6CLASSES for two additional classes, AI_AN (American Indian or Alaskan Native) and PI (Pacific Islander).
Params:
- batch_first_last_name_geo_zipped_in::BatchFirstLastNameGeoZippedIn
Return: BatchFirstLastNameUSRaceEthnicityOut, OpenAPI.Clients.ApiResponse
"""
function us_zip_race_ethnicity_batch(_api::PersonalApi; batch_first_last_name_geo_zipped_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_us_zip_race_ethnicity_batch(_api; batch_first_last_name_geo_zipped_in=batch_first_last_name_geo_zipped_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function us_zip_race_ethnicity_batch(_api::PersonalApi, response_stream::Channel; batch_first_last_name_geo_zipped_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_us_zip_race_ethnicity_batch(_api; batch_first_last_name_geo_zipped_in=batch_first_last_name_geo_zipped_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export community_engage
export community_engage_batch
export community_engage_full
export community_engage_full_batch
export corridor
export corridor_batch
export country
export country_batch
export country_fn_ln
export country_fn_ln_batch
export diaspora
export diaspora_batch
export diaspora_full
export diaspora_full_batch
export gender
export gender1
export gender_batch
export gender_full
export gender_full_batch
export gender_full_geo
export gender_full_geo_batch
export gender_geo
export gender_geo_batch
export origin
export origin_batch
export origin_full
export origin_full_batch
export parse_name
export parse_name_batch
export parse_name_geo
export parse_name_geo_batch
export religion2
export religion_batch
export religion_full
export religion_full_batch
export subclassification
export subclassification_batch
export subclassification_full
export subclassification_full_batch
export us_race_ethnicity
export us_race_ethnicity_batch
export us_race_ethnicity_full
export us_race_ethnicity_full_batch
export us_race_ethnicity_z_i_p5
export us_zip_race_ethnicity_batch
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
|
[
"MIT"
] | 0.1.0 | 2d6ab091a1f4af72f40a76fe35b2c01982aa0bbf | code | 10868 | # This file was generated by the Julia OpenAPI Code Generator
# Do not modify this file directly. Modify the OpenAPI specification instead.
struct SocialApi <: OpenAPI.APIClientImpl
client::OpenAPI.Clients.Client
end
"""
The default API base path for APIs in `SocialApi`.
This can be used to construct the `OpenAPI.Clients.Client` instance.
"""
basepath(::Type{ SocialApi }) = "https://v2.namsor.com/NamSorAPIv2"
const _returntypes_phone_code_SocialApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNamePhoneCodedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_phone_code(_api::SocialApi, first_name::String, last_name::String, phone_number::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_phone_code_SocialApi, "/api2/json/phoneCode/{firstName}/{lastName}/{phoneNumber}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "phoneNumber", phone_number) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 11 UNITS PER NAME] Infer the likely country and phone prefix, given a personal name and formatted / unformatted phone number.
Params:
- first_name::String (required)
- last_name::String (required)
- phone_number::String (required)
Return: FirstLastNamePhoneCodedOut, OpenAPI.Clients.ApiResponse
"""
function phone_code(_api::SocialApi, first_name::String, last_name::String, phone_number::String; _mediaType=nothing)
_ctx = _oacinternal_phone_code(_api, first_name, last_name, phone_number; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function phone_code(_api::SocialApi, response_stream::Channel, first_name::String, last_name::String, phone_number::String; _mediaType=nothing)
_ctx = _oacinternal_phone_code(_api, first_name, last_name, phone_number; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_phone_code_batch_SocialApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNamePhoneCodedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_phone_code_batch(_api::SocialApi; batch_first_last_name_phone_number_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_phone_code_batch_SocialApi, "/api2/json/phoneCodeBatch", ["api_key", ], batch_first_last_name_phone_number_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 11 UNITS PER NAME] Infer the likely country and phone prefix, of up to 100 personal names, detecting automatically the local context given a name and formatted / unformatted phone number.
Params:
- batch_first_last_name_phone_number_in::BatchFirstLastNamePhoneNumberIn
Return: BatchFirstLastNamePhoneCodedOut, OpenAPI.Clients.ApiResponse
"""
function phone_code_batch(_api::SocialApi; batch_first_last_name_phone_number_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_phone_code_batch(_api; batch_first_last_name_phone_number_in=batch_first_last_name_phone_number_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function phone_code_batch(_api::SocialApi, response_stream::Channel; batch_first_last_name_phone_number_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_phone_code_batch(_api; batch_first_last_name_phone_number_in=batch_first_last_name_phone_number_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_phone_code_geo_SocialApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNamePhoneCodedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_phone_code_geo(_api::SocialApi, first_name::String, last_name::String, phone_number::String, country_iso2::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_phone_code_geo_SocialApi, "/api2/json/phoneCodeGeo/{firstName}/{lastName}/{phoneNumber}/{countryIso2}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "phoneNumber", phone_number) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[USES 11 UNITS PER NAME] Infer the likely phone prefix, given a personal name and formatted / unformatted phone number, with a local context (ISO2 country of residence).
Params:
- first_name::String (required)
- last_name::String (required)
- phone_number::String (required)
- country_iso2::String (required)
Return: FirstLastNamePhoneCodedOut, OpenAPI.Clients.ApiResponse
"""
function phone_code_geo(_api::SocialApi, first_name::String, last_name::String, phone_number::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_phone_code_geo(_api, first_name, last_name, phone_number, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function phone_code_geo(_api::SocialApi, response_stream::Channel, first_name::String, last_name::String, phone_number::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_phone_code_geo(_api, first_name, last_name, phone_number, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_phone_code_geo_batch_SocialApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => BatchFirstLastNamePhoneCodedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("400", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_phone_code_geo_batch(_api::SocialApi; batch_first_last_name_phone_number_geo_in=nothing, _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "POST", _returntypes_phone_code_geo_batch_SocialApi, "/api2/json/phoneCodeGeoBatch", ["api_key", ], batch_first_last_name_phone_number_geo_in)
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", ] : [_mediaType])
return _ctx
end
@doc raw"""[USES 11 UNITS PER NAME] Infer the likely country and phone prefix, of up to 100 personal names, with a local context (ISO2 country of residence).
Params:
- batch_first_last_name_phone_number_geo_in::BatchFirstLastNamePhoneNumberGeoIn
Return: BatchFirstLastNamePhoneCodedOut, OpenAPI.Clients.ApiResponse
"""
function phone_code_geo_batch(_api::SocialApi; batch_first_last_name_phone_number_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_phone_code_geo_batch(_api; batch_first_last_name_phone_number_geo_in=batch_first_last_name_phone_number_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function phone_code_geo_batch(_api::SocialApi, response_stream::Channel; batch_first_last_name_phone_number_geo_in=nothing, _mediaType=nothing)
_ctx = _oacinternal_phone_code_geo_batch(_api; batch_first_last_name_phone_number_geo_in=batch_first_last_name_phone_number_geo_in, _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
const _returntypes_phone_code_geo_feedback_loop_SocialApi = Dict{Regex,Type}(
Regex("^" * replace("200", "x"=>".") * "\$") => FirstLastNamePhoneCodedOut,
Regex("^" * replace("401", "x"=>".") * "\$") => Nothing,
Regex("^" * replace("403", "x"=>".") * "\$") => Nothing,
)
function _oacinternal_phone_code_geo_feedback_loop(_api::SocialApi, first_name::String, last_name::String, phone_number::String, phone_number_e164::String, country_iso2::String; _mediaType=nothing)
_ctx = OpenAPI.Clients.Ctx(_api.client, "GET", _returntypes_phone_code_geo_feedback_loop_SocialApi, "/api2/json/phoneCodeGeoFeedbackLoop/{firstName}/{lastName}/{phoneNumber}/{phoneNumberE164}/{countryIso2}", ["api_key", ])
OpenAPI.Clients.set_param(_ctx.path, "firstName", first_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "lastName", last_name) # type String
OpenAPI.Clients.set_param(_ctx.path, "phoneNumber", phone_number) # type String
OpenAPI.Clients.set_param(_ctx.path, "phoneNumberE164", phone_number_e164) # type String
OpenAPI.Clients.set_param(_ctx.path, "countryIso2", country_iso2) # type String
OpenAPI.Clients.set_header_accept(_ctx, ["application/json", ])
OpenAPI.Clients.set_header_content_type(_ctx, (_mediaType === nothing) ? [] : [_mediaType])
return _ctx
end
@doc raw"""[CREDITS 1 UNIT] Feedback loop to better infer the likely phone prefix, given a personal name and formatted / unformatted phone number, with a local context (ISO2 country of residence).
Params:
- first_name::String (required)
- last_name::String (required)
- phone_number::String (required)
- phone_number_e164::String (required)
- country_iso2::String (required)
Return: FirstLastNamePhoneCodedOut, OpenAPI.Clients.ApiResponse
"""
function phone_code_geo_feedback_loop(_api::SocialApi, first_name::String, last_name::String, phone_number::String, phone_number_e164::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_phone_code_geo_feedback_loop(_api, first_name, last_name, phone_number, phone_number_e164, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx)
end
function phone_code_geo_feedback_loop(_api::SocialApi, response_stream::Channel, first_name::String, last_name::String, phone_number::String, phone_number_e164::String, country_iso2::String; _mediaType=nothing)
_ctx = _oacinternal_phone_code_geo_feedback_loop(_api, first_name, last_name, phone_number, phone_number_e164, country_iso2; _mediaType=_mediaType)
return OpenAPI.Clients.exec(_ctx, response_stream)
end
export phone_code
export phone_code_batch
export phone_code_geo
export phone_code_geo_batch
export phone_code_geo_feedback_loop
| NamSor | https://github.com/NeroBlackstone/NamSor.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.