diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..2a68297a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "imas_composer"] + path = imas_composer + url = git@github.com:GA-FDP/imas_composer.git diff --git a/Project.toml b/Project.toml index 0b56ca8f..074a8387 100644 --- a/Project.toml +++ b/Project.toml @@ -22,6 +22,12 @@ StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" ThreadSafeDicts = "4239201d-c60e-5e0a-9702-85d713665ba7" TimerOutputs = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f" +[weakdeps] +PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d" + +[extensions] +IMASddPythonCallExt = "PythonCall" + [compat] AbstractTrees = "0.4" AdaptiveArrayPools = "0.3" @@ -35,6 +41,7 @@ Memoization = "0.2.2" OrderedCollections = "1, 2" PrecompileTools = "1" Preferences = "1" +PythonCall = "0.9.37" StaticArraysCore = "1" ThreadSafeDicts = "0.1.6" TimerOutputs = "0.5" diff --git a/deploy/container/Project.toml b/deploy/container/Project.toml new file mode 100644 index 00000000..a0fa46cd --- /dev/null +++ b/deploy/container/Project.toml @@ -0,0 +1,17 @@ +[deps] +IMASdd = "c5a45a97-b3f9-491c-b9a7-aa88c3bc0067" +PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d" + +[extras] +CondaPkg = "992eb4ea-22a4-4c89-a5bb-47a3300528ab" + +[sources] +IMASdd = {path = "../.."} + +[compat] +PythonCall = "0.9.37" +julia = "1.11" + +# Python comes from the activated imas_composer_julia conda env, CondaPkg must not manage one +[preferences.CondaPkg] +backend = "Null" diff --git a/deploy/container/README.md b/deploy/container/README.md new file mode 100644 index 00000000..3b6726f6 --- /dev/null +++ b/deploy/container/README.md @@ -0,0 +1,73 @@ +# imas_composer from Julia: environment recipe + +This sets up a conda env with [imas_composer](https://github.com/GA-FDP/imas_composer) and +toksearch that IMASdd.jl can call in-process through PythonCall.jl. CondaPkg.jl does not +manage the Python env. You build it with micromamba, activate it, and start Julia inside it. + +## Files + +| file | purpose | +|---|---| +| `environment_julia_pins.yaml` | Overlay on top of imas_composer's `environment_dev.yaml` that caps the libraries Julia also loads | +| `Project.toml` / `Manifest.toml` | Julia env: IMASdd (this checkout) + PythonCall, CondaPkg backend set to `Null` | +| `smoke_test.jl` | Imports the stack, loads every IDS for one shot and checks the awkward → Julia conversion | + +## Setup + +You need micromamba (or mamba), Julia ≥ 1.11, and SSH access to the GA-FDP GitHub org (for +the toksearch submodule). The commands below assume `imas_composer` and `IMASdd.jl` are +cloned side by side. + +```bash +git clone --recurse-submodules git@github.com:GA-FDP/imas_composer.git + +# 1. Conda env: imas_composer's dev env + Julia compatibility pins +micromamba create -n imas_composer_julia \ + -f imas_composer/environment_dev.yaml \ + -f IMASdd.jl/deploy/container/environment_julia_pins.yaml +micromamba activate imas_composer_julia + +# 2. Editable installs (toksearch is unreleased, so it comes from the submodule) +for d in imas_composer imas_composer/toksearch_submodule imas_composer/omas_submodule; do + pip install --no-deps --no-build-isolation -e "$d" +done + +# 3. CA bundle for the FDP tunnel (see below), stored in the env and applied on activation +micromamba env config vars set FDP_TUNNEL_CAINFO="$CONDA_PREFIX/ssl/cacert.pem" +micromamba deactivate && micromamba activate imas_composer_julia + +# 4. Julia env +julia --project=IMASdd.jl/deploy/container -e 'using Pkg; Pkg.instantiate()' +julia --project=IMASdd.jl/deploy/container IMASdd.jl/deploy/container/smoke_test.jl +``` + +The smoke test should print `OK` for every import and the python path inside +`imas_composer_julia`. It then loads every IDS for one shot, which takes a few minutes +(magnetics and pf_active are the slow ones). For every awkward field it checks that +`IMASdd.awkward_from_buffers` rebuilds the same values as `ak.to_list`, and it should end +with `awkward fields rebuilt: N/N match ak.to_list`. If your account can't use the FDP +archive, an `HTTP 401` from the fdp transport followed by a fallback to the next server is +normal. An `SSL peer certificate ... not OK` error means step 3 is missing. + +Always start Julia from inside the activated env. PythonCall picks up `python` from `PATH`, +and activation sets `FDP_TUNNEL_CAINFO`. + +## Why the extra steps + +Python runs inside the Julia process, so Julia and conda share one set of loaded shared +libraries. When both ship a library with the same soname, whichever copy loads first is +used by both sides. + +- **AWS C libraries (`environment_julia_pins.yaml`).** IMASdd depends on HDF5.jl, and + HDF5_jll loads the `aws_c_*_jll` libraries. Conda's pyarrow (pulled in by pyspark) links + the same libraries, which keep the soname `.so.1.0.0` across versions. With unpinned + conda versions, `import awkward` fails with + `undefined symbol: aws_byte_cursor_next_split_on_cursor`. The overlay keeps conda's copies + no newer than Julia's, which currently costs pyarrow 25 → 24. When IMASdd's HDF5_jll + moves, update the bounds to the `aws_c_*_jll` versions in its `Manifest.toml`. +- **TLS (`FDP_TUNNEL_CAINFO`).** Julia's libcurl, which the FDP tunnel in mdsip-fdp also + ends up using, is built without a default CA path. `FDP_TUNNEL_CAINFO` tells mdsip-fdp + where conda's CA bundle is. +- **curl and OpenSSL are deliberately not pinned.** Pinning them downgrades mdsip-fdp and + xrdcl-pelican-fdp. Conda's curl 8.23 / OpenSSL 3.6 consumers work against Julia's + 8.22 / 3.5. diff --git a/deploy/container/environment_julia_pins.yaml b/deploy/container/environment_julia_pins.yaml new file mode 100644 index 00000000..9364877b --- /dev/null +++ b/deploy/container/environment_julia_pins.yaml @@ -0,0 +1,20 @@ +# Overlay for imas_composer/environment_dev.yaml when Python runs inside a Julia process +# (PythonCall). Apply as a second -f, see README.md. +# +# HDF5_jll loads the aws-c-* JLLs into the Julia process. These libraries keep the soname +# .so.1.0.0 across versions, so whichever copy loads first serves both Julia and Python. +# Conda's copies must therefore not be newer than the aws_c_*_jll versions in IMASdd's +# Manifest.toml (currently via HDF5_jll 2.2.3). Raise these bounds when those JLLs move. +channels: + - conda-forge + +dependencies: + - aws-c-common<=0.12.6 + - aws-c-io<=0.26.3 + - aws-c-http<=0.10.15 + - aws-c-auth<=0.9.6 + - aws-c-s3<=0.11.5 + - aws-c-cal<=0.9.13 + - aws-c-sdkutils<=0.2.4 + - aws-checksums<=0.2.10 + - aws-c-compression<=0.3.2 diff --git a/deploy/container/smoke_test.jl b/deploy/container/smoke_test.jl new file mode 100644 index 00000000..eaac5f4a --- /dev/null +++ b/deploy/container/smoke_test.jl @@ -0,0 +1,54 @@ +using IMASdd +using PythonCall +using Libdl + +println("python: ", PythonCall.C.CTX.exe_path) + +for mod in ["numpy", "awkward", "MDSplus", "XRootD.client", "toksearch", "imas_composer"] + m = pyimport(mod) + println("OK ", rpad(mod, 16), pyhasattr(m, "__file__") ? m.__file__ : "") +end + +ak = pyimport("awkward") +np = pyimport("numpy") +imas_composer = pyimport("imas_composer") +julia_interface = pyimport("imas_composer.julia") + +shot = 205055 + +# Small load through the Julia interface +data = julia_interface.simple_load_julia(pylist(["equilibrium.time", "equilibrium.time_slice.boundary.outline.r"]), shot) +outline_r = IMASdd.awkward_from_buffers(data["equilibrium.time_slice.boundary.outline.r"]) +println("\nequilibrium.time: ", size(PyArray(data["equilibrium.time"])), + " boundary.outline.r: ", length(outline_r), " time slices, first has ", length(outline_r[1]), " points") + +# Nested Julia copy of ak.to_list, the reference for awkward_from_buffers +to_julia(x::Py) = pyisinstance(x, pybuiltins.list) ? [to_julia(e) for e in x] : pyconvert(Any, x) + +# Every awkward field of every IDS: buffers rebuilt in Julia must match ak.to_list +composer = imas_composer.ImasComposer() +n_checked, mismatches = 0, String[] +for ids in composer.ids_factory.list_ids() + fields = composer.get_supported_fields(ids) + t0 = time() + values = imas_composer.simple_load(fields, shot, composer=composer) + t_load = time() - t0 + + t_convert, n_awkward = 0.0, 0 + for (path, value) in values.items() + pyisinstance(value, ak.Array) || continue + n_awkward += 1 + t0 = time() + rebuilt = IMASdd.awkward_from_buffers(julia_interface.julia_value(value)) + t_convert += time() - t0 + isequal(rebuilt, to_julia(ak.to_list(ak.fill_none(value, np.nan)))) || push!(mismatches, pyconvert(String, path)) + end + global n_checked += n_awkward + println(rpad(pyconvert(String, ids), 24), lpad(n_awkward, 3), " awkward of ", lpad(length(fields), 3), + " fields load ", lpad(round(t_load; digits=1), 5), " s convert ", lpad(round(t_convert * 1e3; digits=1), 6), " ms") +end +println("\nawkward fields rebuilt: ", n_checked - length(mismatches), "/", n_checked, " match ak.to_list") +foreach(path -> println("MISMATCH ", path), mismatches) + +println("\nshared libraries Julia and Python both use:") +foreach(println, sort(filter(l -> occursin(r"libcurl|libssl|libcrypto|libaws-c-common", l), Libdl.dllist()))) diff --git a/ext/IMASddPythonCallExt.jl b/ext/IMASddPythonCallExt.jl new file mode 100644 index 00000000..e6b772ef --- /dev/null +++ b/ext/IMASddPythonCallExt.jl @@ -0,0 +1,19 @@ +module IMASddPythonCallExt + +import IMASdd +import IMASdd: JSON +using PythonCall: Py, PyArray, pyconvert + +""" + IMASdd.awkward_from_buffers(value::Py) + +Rebuild an awkward array from the dict that `imas_composer.julia.julia_value` returns +(`form`, `length`, `buffers`), with zero-copy views into the numpy buffers. +""" +function IMASdd.awkward_from_buffers(value::Py) + form = JSON.parse(pyconvert(String, value["form"]); dicttype=Dict{String,Any}) + buffers = Dict(key => PyArray(buffer) for (key, buffer) in pyconvert(Dict{String,Py}, value["buffers"])) + return IMASdd.awkward_from_buffers(form, pyconvert(Int, value["length"]), buffers) +end + +end diff --git a/imas_composer b/imas_composer new file mode 160000 index 00000000..c52baaed --- /dev/null +++ b/imas_composer @@ -0,0 +1 @@ +Subproject commit c52baaed450a6fca0ce7e8a721d55d13c470f2ee diff --git a/src/io.jl b/src/io.jl index ad214c06..1878bc69 100644 --- a/src/io.jl +++ b/src/io.jl @@ -2029,4 +2029,51 @@ end export h5merge push!(document[:IO], :h5merge) export read_combined_h5 -push!(document[:IO], :read_combined_h5) \ No newline at end of file +push!(document[:IO], :read_combined_h5) +#= =============== =# +# awkward buffers # +#= =============== =# +""" + awkward_from_buffers(form::AbstractDict, len::Integer, buffers::AbstractDict) + +Rebuild an awkward array from awkward's buffer format (`ak.to_buffers` of a packed array), +as nested vectors of views into the flat `buffers`. + +Supports `NumpyArray`, `ListOffsetArray` (including strings), `RegularArray` and +`ByteMaskedArray` nodes. Masked float entries become `NaN`. +""" +function awkward_from_buffers(form::AbstractDict, len::Integer, buffers::AbstractDict) + array = _awkward_node(form, buffers) + @assert length(array) == len "awkward array has $(length(array)) elements but its buffers say $len" + return array +end + +function _awkward_node(form::AbstractDict, buffers::AbstractDict) + class = form["class"] + key = form["form_key"] + if class == "NumpyArray" + isempty(get(form, "inner_shape", [])) || error("awkward NumpyArray with inner_shape $(form["inner_shape"]) is not supported") + return buffers["$key-data"] + end + + content = _awkward_node(form["content"], buffers) + if class == "ListOffsetArray" + offsets = buffers["$key-offsets"] + if get(get(form, "parameters", Dict()), "__array__", nothing) == "string" + return [String(content[offsets[i]+1:offsets[i+1]]) for i in 1:length(offsets)-1] + end + return [view(content, offsets[i]+1:offsets[i+1]) for i in 1:length(offsets)-1] + + elseif class == "RegularArray" + size = form["size"] + return [view(content, (i-1)*size+1:i*size) for i in 1:div(length(content), size)] + + elseif class == "ByteMaskedArray" + T = eltype(content) + T <: AbstractFloat || error("awkward ByteMaskedArray of $T is not supported, only of floats") + mask = buffers["$key-mask"] + return [(mask[i] != 0) == form["valid_when"] ? content[i] : T(NaN) for i in 1:length(mask)] + end + + error("awkward node class $class is not supported") +end diff --git a/test/runtests.jl b/test/runtests.jl index d8119d61..0aa085d7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -22,6 +22,8 @@ else include("runtests_io_extended.jl") + include("runtests_awkward.jl") + include("runtests_findall.jl") include("runtests_filled.jl") diff --git a/test/runtests_awkward.jl b/test/runtests_awkward.jl new file mode 100644 index 00000000..7215f7ed --- /dev/null +++ b/test/runtests_awkward.jl @@ -0,0 +1,81 @@ +using IMASdd +using Test +import IMASdd.JSON as JSON + +numpy(key; primitive="float64", parameters="{}") = + """{"class": "NumpyArray", "primitive": "$primitive", "form_key": "$key", "parameters": $parameters}""" +list_offset(key, content; parameters="{}") = + """{"class": "ListOffsetArray", "offsets": "i64", "content": $content, "form_key": "$key", "parameters": $parameters}""" +regular(key, content, size) = + """{"class": "RegularArray", "size": $size, "content": $content, "form_key": "$key"}""" +byte_masked(key, content; valid_when=true) = + """{"class": "ByteMaskedArray", "mask": "i8", "valid_when": $valid_when, "content": $content, "form_key": "$key"}""" + +parse_form(form) = JSON.parse(form; dicttype=Dict{String,Any}) + +# (name, form, length, buffers, expected), buffers as ak.to_buffers names them +const AWKWARD_CASES = [ + ("var_float64", list_offset("node0", numpy("node1")), 3, + Dict("node0-offsets" => [0, 3, 4, 4], "node1-data" => [1.0, 2.0, 3.0, 4.0]), + [[1.0, 2.0, 3.0], [4.0], Float64[]]), + ("var_option_float32", list_offset("node0", byte_masked("node1", numpy("node2"; primitive="float32"))), 2, + Dict("node0-offsets" => [0, 2, 4], "node1-mask" => Int8[1, 0, 1, 1], "node2-data" => Float32[1, 2, 3, 4]), + [Float32[1, NaN], Float32[3, 4]]), + ("var_option_float32_valid_when_false", + list_offset("node0", byte_masked("node1", numpy("node2"; primitive="float32"); valid_when=false)), 2, + Dict("node0-offsets" => [0, 2, 4], "node1-mask" => Int8[0, 1, 0, 0], "node2-data" => Float32[1, 2, 3, 4]), + [Float32[1, NaN], Float32[3, 4]]), + ("var_var_float64", list_offset("node0", list_offset("node1", numpy("node2"))), 2, + Dict("node0-offsets" => [0, 2, 3], "node1-offsets" => [0, 1, 3, 3], "node2-data" => [1.0, 2.0, 3.0]), + [[[1.0], [2.0, 3.0]], [Float64[]]]), + ("regular_var_var_float64", regular("node0", list_offset("node1", list_offset("node2", numpy("node3"))), 1), 1, + Dict("node1-offsets" => [0, 2], "node2-offsets" => [0, 1, 3], "node3-data" => [1.0, 2.0, 3.0]), + [[[[1.0], [2.0, 3.0]]]]), + ("regular_float64", regular("node0", numpy("node1"), 3), 2, + Dict("node1-data" => [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), + [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]), + ("var_int64", list_offset("node0", numpy("node1"; primitive="int64")), 3, + Dict("node0-offsets" => [0, 1, 3, 3], "node1-data" => [0, 1, 2]), + [[0], [1, 2], Int[]]), + ("var_string", + list_offset("node0", list_offset("node1", numpy("node2"; primitive="uint8", parameters="""{"__array__": "char"}"""); + parameters="""{"__array__": "string"}""")), 2, + Dict("node0-offsets" => [0, 2, 3], "node1-offsets" => [0, 6, 14, 17], "node2-data" => collect(codeunits("ECOILAECOILA_1F1A"))), + [["ECOILA", "ECOILA_1"], ["F1A"]]), + ("flat_float64", numpy("node0"), 3, + Dict("node0-data" => [1.0, 2.0, 3.0]), + [1.0, 2.0, 3.0]), +] + +# (name, form, length, buffers, exception) +const AWKWARD_ERRORS = [ + ("unsupported_class", """{"class": "IndexedOptionArray", "index": "i64", "content": $(numpy("node1")), "form_key": "node0"}""", 1, + Dict("node0-index" => [0], "node1-data" => [1.0]), ErrorException), + ("masked_int", byte_masked("node0", numpy("node1"; primitive="int64")), 1, + Dict("node0-mask" => Int8[1], "node1-data" => [1]), ErrorException), + ("inner_shape", """{"class": "NumpyArray", "primitive": "float64", "inner_shape": [2], "form_key": "node0"}""", 1, + Dict("node0-data" => [1.0, 2.0]), ErrorException), + ("length_mismatch", numpy("node0"), 4, + Dict("node0-data" => [1.0, 2.0, 3.0]), AssertionError), +] + +@testset "awkward_from_buffers" begin + for (name, form, len, buffers, expected) in AWKWARD_CASES + @testset "$name" begin + array = IMASdd.awkward_from_buffers(parse_form(form), len, buffers) + @test isequal(array, expected) + end + end + + for (name, form, len, buffers, exception) in AWKWARD_ERRORS + @testset "$name" begin + @test_throws exception IMASdd.awkward_from_buffers(parse_form(form), len, buffers) + end + end + + @testset "views share the buffers" begin + buffers = Dict("node0-offsets" => [0, 2, 3], "node1-data" => [1.0, 2.0, 3.0]) + array = IMASdd.awkward_from_buffers(parse_form(list_offset("node0", numpy("node1"))), 2, buffers) + @test parent(array[1]) === buffers["node1-data"] + end +end