commit c3d5daeec54976f61e7de028606bc1b483023d5f Author: Pixelguy14 Date: Wed Nov 25 13:25:07 2026 -0600 feat: JuliaMSI MCP server v0.1.0 — 20 tools ready for testing Implements the Model Context Protocol server for the JuliaMSI mass spectrometry imaging engine, covering phases 1–3 of the implementation plan plus the main phase-4 items. Tools (20): session/dataset: msi_open_dataset, msi_close_dataset, msi_dataset_info, msi_get_dataset_stats spectra: msi_get_spectrum_at_coord, msi_get_spectrum_by_index ion images: msi_get_mz_slice, msi_get_multiple_mz_slices, msi_plan_ion_image, msi_plan_multiple_slices preprocessing: msi_plan_preprocessing, msi_plan_streaming_pipeline, msi_plan_analytics execution: msi_execute_runspec, msi_list_plans, msi_get_task_status, msi_get_task_result, msi_cancel_task, msi_list_tasks maintenance: msi_clean_artifacts Resources (msi://): dataset/metadata, dataset/stats, tasks/{task_id}/status, tasks/{task_id}/result Prompts: analyze_region_of_interest, standard_pipeline, diagnose_task - Persistent session: one MSIData kept alive between tool calls - Plan -> execute -> poll async core (SHA-256 RunSpecs + background tasks) - Results as on-disk artifacts (CSV/PGM/MatrixMarket) with compact previews - Structured JSON-RPC error mapping with suggested actions - stdio and Streamable HTTP transports, optional shared-token auth - Artifact retention (age + size budgets) and glibc malloc_trim cleanup - 107 tests + end-to-end stdio smoke test; validated on HR2MSI bladder (imzML) and T9_A1/Col_1 (mzML) Required JuliaMSI engine fixes are tracked in patches/ (already upstream on the rel/Windows_Mac_Recompatibility branch and GitHub main). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1a617cf --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: CI + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + + # The MCP project links the engine at ../JuliaMSI via [sources]. Cloning it + # as a sibling (rather than into the workspace) keeps the default layout and + # avoids touching [sources] or the Manifest. + - name: Clone JuliaMSI engine (sibling) + run: | + git clone --depth 1 https://github.com/Pixelguy14/Julia_msi_GUI ../JuliaMSI + + - uses: julia-actions/setup-julia@v2 + with: + version: "1.11" + + - uses: julia-actions/cache@v2 + + - name: Instantiate + run: | + julia --project=. -e 'using Pkg; Pkg.instantiate()' + + - name: Unit & integration tests + run: | + julia --project=. -e 'using Pkg; Pkg.test()' + + - name: Smoke test (stdio, synthetic dataset) + run: | + python3 test/smoke_stdio.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..61fd8ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# Generated results +artifacts/ +build/ +*.imzML.cache +*.log +*.so +*.dll +*.dylib + +# Julia +*.jl.cov +*.jl.*.cov +*.jl.mem + +# Editors +.vscode/ +.idea/ +.DS_Store + +# Python +__pycache__/ +*.pyc diff --git a/Manifest.toml b/Manifest.toml new file mode 100644 index 0000000..cc609f6 --- /dev/null +++ b/Manifest.toml @@ -0,0 +1,2867 @@ +# This file is machine-generated - editing it directly is not advised + +julia_version = "1.11.7" +manifest_format = "2.0" +project_hash = "62043f5b2831a3534ab00d541807d6f79ce2ab53" + +[[deps.ANSIColoredPrinters]] +git-tree-sha1 = "574baf8110975760d391c710b6341da1afa48d8c" +uuid = "a4c015fc-c6ff-483c-b24f-f7ea428134e9" +version = "0.0.1" + +[[deps.ATK_jll]] +deps = ["Artifacts", "Glib_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c0a10eaf3a7e1e909ef8fe45971a73524bfce1bf" +uuid = "7b86fcea-f67b-53e1-809c-8f1719c154e8" +version = "2.38.1+0" + +[[deps.AbstractFFTs]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef" +uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c" +version = "1.5.0" +weakdeps = ["ChainRulesCore", "Test"] + + [deps.AbstractFFTs.extensions] + AbstractFFTsChainRulesCoreExt = "ChainRulesCore" + AbstractFFTsTestExt = "Test" + +[[deps.AbstractTrees]] +git-tree-sha1 = "2d9c9a55f9c93e8887ad391fbae72f8ef55e1177" +uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" +version = "0.4.5" + +[[deps.Accessors]] +deps = ["CompositionsBase", "ConstructionBase", "Dates", "InverseFunctions", "MacroTools"] +git-tree-sha1 = "8c0bc12397dabf5d2dfc4b5763ec463854cc44d3" +uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697" +version = "0.1.46" + + [deps.Accessors.extensions] + AxisKeysExt = "AxisKeys" + IntervalSetsExt = "IntervalSets" + LinearAlgebraExt = "LinearAlgebra" + StaticArraysExt = "StaticArrays" + StructArraysExt = "StructArrays" + TestExt = "Test" + UnitfulExt = "Unitful" + + [deps.Accessors.weakdeps] + AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" + Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.Adapt]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "eec8a0ad4e4b673afba213931504c360fffb8f97" +uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" +version = "4.8.0" +weakdeps = ["SparseArrays", "StaticArrays"] + + [deps.Adapt.extensions] + AdaptSparseArraysExt = "SparseArrays" + AdaptStaticArraysExt = "StaticArrays" + +[[deps.AdaptivePredicates]] +git-tree-sha1 = "7e651ea8d262d2d74ce75fdf47c4d63c07dba7a6" +uuid = "35492f91-a3bd-45ad-95db-fcad7dcfedb7" +version = "1.2.0" + +[[deps.AliasTables]] +deps = ["PtrArrays", "Random"] +git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff" +uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8" +version = "1.1.3" + +[[deps.Animations]] +deps = ["Colors"] +git-tree-sha1 = "e092fa223bf66a3c41f9c022bd074d916dc303e7" +uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340" +version = "0.4.2" + +[[deps.ArgParse]] +deps = ["Logging", "TextWrap"] +git-tree-sha1 = "22cf435ac22956a7b45b0168abbc871176e7eecc" +uuid = "c7e460c6-2fb9-53a9-8c5b-16f535851c63" +version = "1.2.0" + +[[deps.ArgTools]] +uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" +version = "1.1.2" + +[[deps.ArnoldiMethod]] +deps = ["LinearAlgebra", "Random", "StaticArrays"] +git-tree-sha1 = "d57bd3762d308bded22c3b82d033bff85f6195c6" +uuid = "ec485272-7323-5ecc-a04f-4719b315124d" +version = "0.4.0" + +[[deps.ArrayInterface]] +deps = ["Adapt", "LinearAlgebra"] +git-tree-sha1 = "1aec1ff0dcaa83a484e7f72097562fa3102c6722" +uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9" +version = "7.30.2" + + [deps.ArrayInterface.extensions] + ArrayInterfaceAMDGPUExt = "AMDGPU" + ArrayInterfaceBandedMatricesExt = "BandedMatrices" + ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices" + ArrayInterfaceCUDAExt = "CUDA" + ArrayInterfaceCUDSSExt = ["CUDSS", "CUDA"] + ArrayInterfaceChainRulesCoreExt = "ChainRulesCore" + ArrayInterfaceChainRulesExt = "ChainRules" + ArrayInterfaceFillArraysExt = "FillArrays" + ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore" + ArrayInterfaceGPUArraysCoreTrackerExt = ["GPUArraysCore", "Tracker"] + ArrayInterfaceMetalExt = "Metal" + ArrayInterfaceReverseDiffExt = "ReverseDiff" + ArrayInterfaceSparseArraysExt = "SparseArrays" + ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore" + ArrayInterfaceTrackerExt = "Tracker" + + [deps.ArrayInterface.weakdeps] + AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" + BandedMatrices = "aae01518-5342-5314-be14-df237901396f" + BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0" + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e" + ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2" + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + FillArrays = "1a297f60-69ca-5386-bcde-b61e274b549b" + GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" + Metal = "dde4c033-4e86-420c-a63e-0dd931031962" + ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" + Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c" + +[[deps.Artifacts]] +uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" +version = "1.11.0" + +[[deps.Automa]] +deps = ["PrecompileTools", "TranscodingStreams"] +git-tree-sha1 = "94eab0b3ccdcac361188cc661daf69d4433c1818" +uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b" +version = "1.2.0" + +[[deps.AxisAlgorithms]] +deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"] +git-tree-sha1 = "01b8ccb13d68535d73d2b0c23e39bd23155fb712" +uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950" +version = "1.1.0" + +[[deps.AxisArrays]] +deps = ["Dates", "IntervalSets", "IterTools", "RangeArrays"] +git-tree-sha1 = "4126b08903b777c88edf1754288144a0492c05ad" +uuid = "39de3d68-74b9-583c-8d2d-e117c070f3a9" +version = "0.4.8" + +[[deps.Base64]] +uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" +version = "1.11.0" + +[[deps.BaseDirs]] +git-tree-sha1 = "8c290a1b223deaeea9aea44b235d24546da8eb98" +uuid = "18cc8868-cbac-4acf-b575-c8ff214dc66f" +version = "1.4.0" + +[[deps.Bessels]] +git-tree-sha1 = "4435559dc39793d53a9e3d278e185e920b4619ef" +uuid = "0e736298-9ec6-45e8-9647-e4fc86a2fe38" +version = "0.2.8" + +[[deps.BitFlags]] +git-tree-sha1 = "bbe1079eecf9c9fbb52765193ad2bae27ae09bc8" +uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35" +version = "0.1.10" + +[[deps.BitTwiddlingConvenienceFunctions]] +deps = ["Static"] +git-tree-sha1 = "f21cfd4950cb9f0587d5067e69405ad2acd27b87" +uuid = "62783981-4cbd-42fc-bca8-16325de8dc4b" +version = "0.1.6" + +[[deps.BufferedStreams]] +git-tree-sha1 = "6863c5b7fc997eadcabdbaf6c5f201dc30032643" +uuid = "e1450e63-4bb3-523b-b2a4-4ffa8c0fd77d" +version = "1.2.2" + +[[deps.Bzip2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1b96ea4a01afe0ea4090c5c8039690672dd13f2e" +uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0" +version = "1.0.9+0" + +[[deps.CEnum]] +git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc" +uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" +version = "0.5.0" + +[[deps.CPUSummary]] +deps = ["CpuId", "IfElse", "PrecompileTools", "Preferences", "Static"] +git-tree-sha1 = "f3a21d7fc84ba618a779d1ed2fcca2e682865bab" +uuid = "2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9" +version = "0.2.7" + +[[deps.CRC32c]] +uuid = "8bf52ea8-c179-5cab-976a-9e18b702a9bc" +version = "1.11.0" + +[[deps.CRlibm]] +deps = ["CRlibm_jll"] +git-tree-sha1 = "0db159493e83ecb2d122f9c40138d89b70d43963" +uuid = "96374032-68de-5a5b-8d9e-752f78720389" +version = "1.1.1" + +[[deps.CRlibm_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "e329286945d0cfc04456972ea732551869af1cfc" +uuid = "4e9b3aee-d8a1-5a3d-ad8b-7d824db253f0" +version = "1.0.1+0" + +[[deps.CSV]] +deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "PrecompileTools", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings", "WorkerUtilities"] +git-tree-sha1 = "abed1e735dd4152f48c90cf0767e1790e25f332f" +uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" +version = "0.10.17" + +[[deps.Cairo]] +deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"] +git-tree-sha1 = "71aa551c5c33f1a4415867fe06b7844faadb0ae9" +uuid = "159f3aea-2a34-519c-b102-8c37f9878175" +version = "1.1.1" + +[[deps.CairoMakie]] +deps = ["CRC32c", "Cairo", "Cairo_jll", "Colors", "FileIO", "FreeType", "GeometryBasics", "LinearAlgebra", "Makie", "PrecompileTools"] +git-tree-sha1 = "9bd45574379e50579a78774334f4a1f1238c0af5" +uuid = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" +version = "0.13.10" + +[[deps.Cairo_jll]] +deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"] +git-tree-sha1 = "0cfb779e24fdced77a05df1dbe99200821a9f563" +uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a" +version = "1.18.8+1" + +[[deps.CatIndices]] +deps = ["CustomUnitRanges", "OffsetArrays"] +git-tree-sha1 = "a0f80a09780eed9b1d106a1bf62041c2efc995bc" +uuid = "aafaddc9-749c-510e-ac4f-586e18779b91" +version = "0.2.2" + +[[deps.ChainRulesCore]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "295fa9b898db109bc56df62c0fc20bd105cec00e" +uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" +version = "1.26.8" +weakdeps = ["SparseArrays"] + + [deps.ChainRulesCore.extensions] + ChainRulesCoreSparseArraysExt = "SparseArrays" + +[[deps.ChunkCodecCore]] +git-tree-sha1 = "3496e2b359c27793d12bec54ec94be7983a6ceb2" +uuid = "0b6fb165-00bc-4d37-ab8b-79f91016dbe1" +version = "1.0.2" + +[[deps.ChunkCodecLibZlib]] +deps = ["ChunkCodecCore", "Zlib_jll"] +git-tree-sha1 = "d4101e848e8d3f585d61d244c2fe0c80a70e6b3b" +uuid = "4c0bbee4-addc-4d73-81a0-b6caacae83c8" +version = "1.1.0" + +[[deps.ChunkCodecLibZstd]] +deps = ["ChunkCodecCore", "Zstd_jll"] +git-tree-sha1 = "34d9873079e4cb3d0c62926a225136824677073f" +uuid = "55437552-ac27-4d47-9aa3-63184e8fd398" +version = "1.0.0" + +[[deps.CloseOpenIntervals]] +deps = ["Static", "StaticArrayInterface"] +git-tree-sha1 = "05ba0d07cd4fd8b7a39541e31a7b0254704ea581" +uuid = "fb6a15b2-703c-40df-9091-08a04967cfa9" +version = "0.1.13" + +[[deps.Clustering]] +deps = ["Distances", "LinearAlgebra", "NearestNeighbors", "Printf", "Random", "SparseArrays", "Statistics", "StatsBase"] +git-tree-sha1 = "3e22db924e2945282e70c33b75d4dde8bfa44c94" +uuid = "aaaa29a8-35af-508c-8bc3-b662a17a0fe5" +version = "0.15.8" + +[[deps.CodeTracking]] +deps = ["InteractiveUtils", "REPL", "UUIDs"] +git-tree-sha1 = "cfb7a2e89e245a9d5016b70323db412b3a7438d5" +uuid = "da1fd8a2-8d9e-5ec2-8556-3022fb5608a2" +version = "3.0.2" + +[[deps.CodecBase]] +deps = ["TranscodingStreams"] +git-tree-sha1 = "40956acdbef3d8c7cc38cba42b56034af8f8581a" +uuid = "6c391c72-fb7b-5838-ba82-7cfb1bcfecbf" +version = "0.3.4" + +[[deps.CodecZlib]] +deps = ["TranscodingStreams", "Zlib_jll"] +git-tree-sha1 = "970758a3d591a2a5c2a907c53f2e2f8c1b1d3537" +uuid = "944b1d66-785c-5afd-91f1-9de20f533193" +version = "0.7.9" + +[[deps.CodecZstd]] +deps = ["TranscodingStreams", "Zstd_jll"] +git-tree-sha1 = "da54a6cd93c54950c15adf1d336cfd7d71f51a56" +uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2" +version = "0.8.7" + +[[deps.ColorBrewer]] +deps = ["Colors", "JSON"] +git-tree-sha1 = "07da79661b919001e6863b81fc572497daa58349" +uuid = "a2cac450-b92f-5266-8821-25eda20663c8" +version = "0.4.2" + +[[deps.ColorSchemes]] +deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"] +git-tree-sha1 = "b0fd3f56fa442f81e0a47815c92245acfaaa4e34" +uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" +version = "3.31.0" + +[[deps.ColorTypes]] +deps = ["FixedPointNumbers", "Random"] +git-tree-sha1 = "b10d0b65641d57b8b4d5e234446582de5047050d" +uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" +version = "0.11.5" + +[[deps.ColorVectorSpace]] +deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"] +git-tree-sha1 = "a1f44953f2382ebb937d60dafbe2deea4bd23249" +uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" +version = "0.10.0" +weakdeps = ["SpecialFunctions"] + + [deps.ColorVectorSpace.extensions] + SpecialFunctionsExt = "SpecialFunctions" + +[[deps.Colors]] +deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] +git-tree-sha1 = "362a287c3aa50601b0bc359053d5c2468f0e7ce0" +uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" +version = "0.12.11" + +[[deps.CommonMark]] +deps = ["PrecompileTools"] +git-tree-sha1 = "7c8fe02c7eb6fe22e89d3990123a2a931ca8fcfb" +uuid = "a80b9123-70ca-4bc0-993e-6e3bcb318db6" +version = "1.0.4" +weakdeps = ["Markdown", "MarkdownAST"] + + [deps.CommonMark.extensions] + CommonMarkMarkdownASTExt = "MarkdownAST" + CommonMarkMarkdownExt = "Markdown" + +[[deps.CommonSolve]] +deps = ["PrecompileTools"] +git-tree-sha1 = "6c389fa857f6ca5a95474b52a52023fd77f24cb7" +uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2" +version = "0.2.14" + +[[deps.CommonWorldInvalidations]] +deps = ["PrecompileTools"] +git-tree-sha1 = "7c4ea0adfb7238bf4678aa36325863fab6163f6f" +uuid = "f70d9fcc-98c5-4d4a-abd7-e4cdeebd8ca8" +version = "1.2.2" + +[[deps.Compat]] +deps = ["TOML", "UUIDs"] +git-tree-sha1 = "9d8a54ce4b17aa5bdce0ea5c34bc5e7c340d16ad" +uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" +version = "4.18.1" +weakdeps = ["Dates", "LinearAlgebra"] + + [deps.Compat.extensions] + CompatLinearAlgebraExt = "LinearAlgebra" + +[[deps.Compiler]] +git-tree-sha1 = "382d79bfe72a406294faca39ef0c3cef6e6ce1f1" +uuid = "807dbc54-b67e-4c79-8afb-eafe4df6f2e1" +version = "0.1.1" + +[[deps.CompilerSupportLibraries_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" +version = "1.1.1+0" + +[[deps.CompositionsBase]] +git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad" +uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b" +version = "0.1.2" +weakdeps = ["InverseFunctions"] + + [deps.CompositionsBase.extensions] + CompositionsBaseInverseFunctionsExt = "InverseFunctions" + +[[deps.ComputationalResources]] +git-tree-sha1 = "52cb3ec90e8a8bea0e62e275ba577ad0f74821f7" +uuid = "ed09eef8-17a6-5b46-8889-db040fac31e3" +version = "0.3.2" + +[[deps.ConcurrentUtilities]] +deps = ["Serialization", "Sockets"] +git-tree-sha1 = "8e0b1057b8c3627562526304d3cc8f835fbb36c0" +uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb" +version = "2.8.0" + +[[deps.Configurations]] +deps = ["ExproniconLite", "OrderedCollections", "TOML"] +git-tree-sha1 = "4358750bb58a3caefd5f37a4a0c5bfdbbf075252" +uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d" +version = "0.17.6" + +[[deps.ConstructionBase]] +git-tree-sha1 = "b1bc10667320dd5367aff450a992c951ea38fbbc" +uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9" +version = "1.6.1" +weakdeps = ["IntervalSets", "LinearAlgebra", "StaticArrays"] + + [deps.ConstructionBase.extensions] + ConstructionBaseIntervalSetsExt = "IntervalSets" + ConstructionBaseLinearAlgebraExt = "LinearAlgebra" + ConstructionBaseStaticArraysExt = "StaticArrays" + +[[deps.ContinuousWavelets]] +deps = ["AbstractFFTs", "Adapt", "Documenter", "FFTW", "Interpolations", "LinearAlgebra", "SpecialFunctions", "Wavelets"] +git-tree-sha1 = "3273d7b8bec0cf1235f0a383d5e0f199b17d7e99" +uuid = "96eb917e-2868-4417-9cb6-27e7ff17528f" +version = "1.2.3" + + [deps.ContinuousWavelets.extensions] + CUDAExt = ["CUDA", "cuFFT"] + MetalExt = "Metal" + + [deps.ContinuousWavelets.weakdeps] + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + Metal = "dde4c033-4e86-420c-a63e-0dd931031962" + cuFFT = "533571aa-0936-420e-b4be-9c66f5f626ca" + +[[deps.Contour]] +git-tree-sha1 = "439e35b0b36e2e5881738abc8857bd92ad6ff9a8" +uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" +version = "0.6.3" + +[[deps.ConvexHulls2d]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "cd7759cfeaf855fed46ec26a26fb323ac3a5501e" +uuid = "438b5665-92b0-42e6-bc36-e4ac8449fa2d" +version = "0.1.1" +weakdeps = ["Makie"] + + [deps.ConvexHulls2d.extensions] + ConvexHulls2dMakieExt = "Makie" + +[[deps.CoordinateTransformations]] +deps = ["LinearAlgebra", "StaticArrays"] +git-tree-sha1 = "a692f5e257d332de1e554e4566a4e5a8a72de2b2" +uuid = "150eb455-5306-5404-9cee-2592286d6298" +version = "0.6.4" + +[[deps.CoreMath]] +deps = ["CoreMath_jll"] +git-tree-sha1 = "8c0480f92b1b1796239156a1b9b1bfb1b39499b4" +uuid = "b7a15901-be09-4a0e-87d2-2e66b0e09b5a" +version = "0.1.0" + +[[deps.CoreMath_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "a692a4c1dc59a4b8bc0b6403876eb3250fde2bc3" +uuid = "a38c48d9-6df1-5ac9-9223-b6ada3b5572b" +version = "0.1.0+0" + +[[deps.CpuId]] +deps = ["Markdown", "PrecompileTools"] +git-tree-sha1 = "5dbd5150b96f29553fc3b553c6bfb0eadf7ac204" +uuid = "adafc99b-e345-5852-983c-f28acb93d879" +version = "0.3.3" + +[[deps.Crayons]] +git-tree-sha1 = "54b76cbb40d9a0f5368c880725b2f141da77c94f" +uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" +version = "4.2.0" + +[[deps.CustomUnitRanges]] +git-tree-sha1 = "1a3f97f907e6dd8983b744d2642651bb162a3f7a" +uuid = "dc8bdbbb-1ca9-579f-8c36-e416f6a65cce" +version = "1.0.2" + +[[deps.DSP]] +deps = ["Bessels", "FFTW", "IterTools", "LinearAlgebra", "Polynomials", "Random", "Reexport", "SpecialFunctions", "Statistics"] +git-tree-sha1 = "dd73b345b24e52d7b57550b69113261ef2d79c92" +uuid = "717857b8-e6f2-59f4-9121-6e50c889abd2" +version = "0.8.7" +weakdeps = ["OffsetArrays"] + + [deps.DSP.extensions] + OffsetArraysExt = "OffsetArrays" + +[[deps.DataAPI]] +git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe" +uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" +version = "1.16.0" + +[[deps.DataFrames]] +deps = ["Compat", "DataAPI", "DataStructures", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrecompileTools", "PrettyTables", "Printf", "Random", "Reexport", "SentinelArrays", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] +git-tree-sha1 = "fd798b61b03b15dda0715aac807885397e6ded88" +uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" +version = "1.8.3" + +[[deps.DataStructures]] +deps = ["Compat", "InteractiveUtils", "OrderedCollections"] +git-tree-sha1 = "4e1fe97fdaed23e9dc21d4d664bea76b65fc50a0" +uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" +version = "0.18.22" + +[[deps.DataValueInterfaces]] +git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" +uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" +version = "1.0.0" + +[[deps.Dates]] +deps = ["Printf"] +uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" +version = "1.11.0" + +[[deps.Dbus_jll]] +deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "473e9afc9cf30814eb67ffa5f2db7df82c3ad9fd" +uuid = "ee1fde0b-3d02-5ea6-8484-8dfef6360eab" +version = "1.16.2+0" + +[[deps.DelaunayTriangulation]] +deps = ["AdaptivePredicates", "EnumX", "ExactPredicates", "Random"] +git-tree-sha1 = "e1e28f37cbdca4b594ad86ecfe2ee8f25796ebff" +uuid = "927a84f5-c5f4-47a5-9785-b46e178433df" +version = "1.7.0" + +[[deps.DelimitedFiles]] +deps = ["Mmap"] +git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae" +uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" +version = "1.9.1" + +[[deps.Distances]] +deps = ["LinearAlgebra", "Statistics", "StatsAPI"] +git-tree-sha1 = "c7e3a542b999843086e2f29dac96a618c105be1d" +uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" +version = "0.10.12" +weakdeps = ["ChainRulesCore", "SparseArrays"] + + [deps.Distances.extensions] + DistancesChainRulesCoreExt = "ChainRulesCore" + DistancesSparseArraysExt = "SparseArrays" + +[[deps.Distributed]] +deps = ["Random", "Serialization", "Sockets"] +uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" +version = "1.11.0" + +[[deps.Distributions]] +deps = ["AliasTables", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "Roots", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns"] +git-tree-sha1 = "478d3450b1cc56521d1d99ad923acf43f8813c6d" +uuid = "31c24e10-a181-5473-b8eb-7969acd0382f" +version = "0.25.134" + + [deps.Distributions.extensions] + DistributionsChainRulesCoreExt = "ChainRulesCore" + DistributionsDensityInterfaceExt = "DensityInterface" + DistributionsSparseConnectivityTracerExt = "SparseConnectivityTracer" + DistributionsTestExt = "Test" + + [deps.Distributions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + DensityInterface = "b429d917-457f-4dbc-8f4c-0cc954292b1d" + SparseConnectivityTracer = "9f842d2f-2579-4b1d-911e-f412cf18a3f5" + Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[[deps.DocStringExtensions]] +git-tree-sha1 = "7442a5dfe1ebb773c29cc2962a8980f47221d76c" +uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" +version = "0.9.5" + +[[deps.Documenter]] +deps = ["ANSIColoredPrinters", "AbstractTrees", "Base64", "CodecZlib", "Dates", "DocStringExtensions", "Downloads", "Git", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "MarkdownAST", "Pkg", "PrecompileTools", "REPL", "RegistryInstances", "SHA", "SimpleImageMetadata", "TOML", "Test", "Unicode"] +git-tree-sha1 = "b0c5f73f14c6fabc2161b94b873ccb5afeb0b424" +uuid = "e30172f5-a6a5-5a46-863b-614d45cd2de4" +version = "1.20.0" + +[[deps.DotEnv]] +deps = ["PrecompileTools"] +git-tree-sha1 = "92e88cb68a5b10545234f46dfaeb2fa8a8a50c45" +uuid = "4dc1fcf4-5e3b-5448-94ab-0c38ec0385c1" +version = "1.0.0" + +[[deps.Downloads]] +deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] +uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" +version = "1.6.0" + +[[deps.EarCut_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "e3290f2d49e661fbd94046d7e3726ffcb2d41053" +uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5" +version = "2.2.4+0" + +[[deps.EnumX]] +git-tree-sha1 = "c49898e8438c828577f04b92fc9368c388ac783c" +uuid = "4e289a0a-7415-4d19-859d-a7e5c4648b56" +version = "1.0.7" + +[[deps.EpollShim_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "8a4be429317c42cfae6a7fc03c31bad1970c310d" +uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43" +version = "0.0.20230411+1" + +[[deps.ExactPredicates]] +deps = ["IntervalArithmetic", "Random", "StaticArrays"] +git-tree-sha1 = "83231673ea4d3d6008ac74dc5079e77ab2209d8f" +uuid = "429591f6-91af-11e9-00e2-59fbe8cec110" +version = "2.2.9" + +[[deps.ExceptionUnwrapping]] +deps = ["Test"] +git-tree-sha1 = "4e468f521e1f9f86891cb07186de5df90360a666" +uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4" +version = "0.1.12" + +[[deps.Expat_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "f2659a735f9360fedfa29925812380f322679e93" +uuid = "2e619515-83b5-522b-bb60-26c02a35a201" +version = "2.10.0+0" + +[[deps.ExproniconLite]] +git-tree-sha1 = "250aa1562e840b38c72b44a9ebef0f39f6b6e950" +uuid = "55351af7-c7e9-48d6-89ff-24e801d99491" +version = "0.10.16" + +[[deps.EzXML]] +deps = ["Printf", "XML2_jll"] +git-tree-sha1 = "7ea1aa5869e2626ccae84480e4f37185bc6f41d3" +uuid = "8f5d6c58-4d21-5cfd-889c-e3ad7ee6a615" +version = "1.2.3" + +[[deps.FFMPEG_jll]] +deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"] +git-tree-sha1 = "eaa040768ea663ca695d442be1bc97edfe6824f2" +uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5" +version = "6.1.3+0" + +[[deps.FFTA]] +deps = ["AbstractFFTs", "DocStringExtensions", "LinearAlgebra", "MuladdMacro", "Primes", "Random", "Reexport"] +git-tree-sha1 = "f4d904e7ff5aadd8e7fe9ab8544a0a295dfa8904" +uuid = "b86e33f2-c0db-4aa1-a6e0-ab43e668529e" +version = "0.3.3" + +[[deps.FFTViews]] +deps = ["CustomUnitRanges", "FFTW"] +git-tree-sha1 = "cbdf14d1e8c7c8aacbe8b19862e0179fd08321c2" +uuid = "4f61f5a4-77b1-5117-aa51-3ab5ef4ef0cd" +version = "0.3.2" + +[[deps.FFTW]] +deps = ["AbstractFFTs", "FFTW_jll", "Libdl", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"] +git-tree-sha1 = "97f08406df914023af55ade2f843c39e99c5d969" +uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" +version = "1.10.0" + +[[deps.FFTW_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6866aec60ef98e3164cd8d6855225684207e9dff" +uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a" +version = "3.3.12+0" + +[[deps.FileIO]] +deps = ["Pkg", "Requires", "UUIDs"] +git-tree-sha1 = "6621fef488e496356c9c9625d0562c12a6070819" +uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" +version = "1.20.0" +weakdeps = ["HTTP"] + + [deps.FileIO.extensions] + HTTPExt = "HTTP" + +[[deps.FilePaths]] +deps = ["FilePathsBase", "MacroTools", "Reexport", "Requires"] +git-tree-sha1 = "919d9412dbf53a2e6fe74af62a73ceed0bce0629" +uuid = "8fc22ac5-c921-52a6-82fd-178b2807b824" +version = "0.8.3" + +[[deps.FilePathsBase]] +deps = ["Compat", "Dates"] +git-tree-sha1 = "3bab2c5aa25e7840a4b065805c0cdfc01f3068d2" +uuid = "48062228-2e41-5def-b9a4-89aafe57970f" +version = "0.9.24" +weakdeps = ["Mmap", "Test"] + + [deps.FilePathsBase.extensions] + FilePathsBaseMmapExt = "Mmap" + FilePathsBaseTestExt = "Test" + +[[deps.FileWatching]] +uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" +version = "1.11.0" + +[[deps.FillArrays]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "831f86fde78ab7f6470d6ba4d1161a11fb6b4ec0" +uuid = "1a297f60-69ca-5386-bcde-b61e274b549b" +version = "1.18.2" +weakdeps = ["PDMats", "SparseArrays", "StaticArrays", "Statistics"] + + [deps.FillArrays.extensions] + FillArraysPDMatsExt = "PDMats" + FillArraysSparseArraysExt = "SparseArrays" + FillArraysStaticArraysExt = "StaticArrays" + FillArraysStatisticsExt = "Statistics" + +[[deps.FixedPointNumbers]] +deps = ["Random", "Statistics"] +git-tree-sha1 = "59af96b98217c6ef4ae0dfe065ac7c20831d1a84" +uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" +version = "0.8.6" + +[[deps.Fontconfig_jll]] +deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Zlib_jll"] +git-tree-sha1 = "e1e9ba3a8f5d71e6ae698f138a1362aeabb42e9f" +uuid = "a3f928ae-7b40-5064-980b-68af3947d34b" +version = "2.18.3+0" + +[[deps.Format]] +git-tree-sha1 = "9c68794ef81b08086aeb32eeaf33531668d5f5fc" +uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8" +version = "1.3.7" + +[[deps.FreeType]] +deps = ["CEnum", "FreeType2_jll"] +git-tree-sha1 = "907369da0f8e80728ab49c1c7e09327bf0d6d999" +uuid = "b38be410-82b0-50bf-ab77-7b57e271db43" +version = "4.1.1" + +[[deps.FreeType2_jll]] +deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "d95a7a3a7e0f2fffc6291bd33035830aab01310b" +uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7" +version = "2.15.0+0" + +[[deps.FreeTypeAbstraction]] +deps = ["BaseDirs", "ColorVectorSpace", "Colors", "FreeType", "GeometryBasics", "Mmap"] +git-tree-sha1 = "4ebb930ef4a43817991ba35db6317a05e59abd11" +uuid = "663a7486-cb36-511b-a19d-713bb74d65c9" +version = "0.10.8" + +[[deps.FriBidi_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e894be022a2eba58463939f1bf1f7f7006f27f52" +uuid = "559328eb-81f9-559d-9380-de523a88c83c" +version = "1.0.19+0" + +[[deps.Future]] +deps = ["Random"] +uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" +version = "1.11.0" + +[[deps.GMP_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "781609d7-10c4-51f6-84f2-b8444358ff6d" +version = "6.3.0+0" + +[[deps.GTK3_jll]] +deps = ["ATK_jll", "Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Libepoxy_jll", "Pango_jll", "Pkg", "Wayland_jll", "Xorg_libX11_jll", "Xorg_libXcomposite_jll", "Xorg_libXcursor_jll", "Xorg_libXdamage_jll", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll", "Xorg_libXrender_jll", "at_spi2_atk_jll", "gdk_pixbuf_jll", "iso_codes_jll", "xkbcommon_jll"] +git-tree-sha1 = "b080a592525632d287aee4637a62682576b7f5e4" +uuid = "77ec8976-b24b-556a-a1bf-49a033a670a6" +version = "3.24.31+0" + +[[deps.Gamma]] +git-tree-sha1 = "86f86b6168a016ed88e4ae4e64577b98c3b59e8e" +uuid = "a0844989-3bd2-4988-8bea-c9407ab0941b" +version = "1.1.0" + +[[deps.GarishPrint]] +deps = ["Configurations", "Preferences"] +git-tree-sha1 = "41136d24cc02c4d7c2b8c8982823fedac66d0a45" +uuid = "b0ab02a7-8576-43f7-aa76-eaa7c3897c54" +version = "0.5.1" + +[[deps.Genie]] +deps = ["ArgParse", "Base64", "Dates", "Distributed", "DotEnv", "EzXML", "FilePathsBase", "HTTP", "HttpCommon", "Inflector", "JSON", "JuliaFormatter", "Logging", "LoggingExtras", "LoweredCodeUtils", "MIMEs", "Markdown", "Millboard", "Nettle", "OrderedCollections", "Pkg", "REPL", "Random", "Reexport", "Revise", "SHA", "Serialization", "Sockets", "UUIDs", "Unicode", "XML2_jll", "YAML"] +git-tree-sha1 = "3172f6300fb2d97f429d3d718f92bd49e9a932f5" +uuid = "c43c736e-a2d1-11e8-161f-af95117fbd1e" +version = "5.35.15" + +[[deps.GenieAutoReload]] +deps = ["Distributed", "Genie", "Logging", "Revise"] +git-tree-sha1 = "7b6edfd6db5863fc1f8469218a165b373ab0d3fb" +uuid = "c6228e60-a24f-11e9-1776-c313472ebacc" +version = "2.3.0" + +[[deps.GenieDevTools]] +deps = ["Dates", "Genie", "RemoteREPL", "Revise", "Stipple", "StippleUI", "Tables"] +git-tree-sha1 = "b22880786aa80cc425af43d562a6be5ebb617511" +uuid = "4e5d9629-6565-4102-a9ff-45c707eb060e" +version = "2.13.0" + +[[deps.GenieFramework]] +deps = ["GarishPrint", "Genie", "GenieAutoReload", "GenieDevTools", "GeniePackageManager", "Reexport", "Revise", "Stipple", "StipplePivotTable", "StipplePlotly", "StippleTable", "StippleTabs", "StippleUI"] +git-tree-sha1 = "4dcc51e8dbaf7d02ba80a2dbebc7b05eb477cc03" +uuid = "a59fdf5c-6bf0-4f5d-949c-a137c9e2f353" +version = "2.10.0" + +[[deps.GeniePackageManager]] +deps = ["Base64", "Genie", "Pkg"] +git-tree-sha1 = "07b62e3765f6c2f7f621c664d8a1d51da3d0b5d1" +uuid = "3bdcc7f3-4b7d-42a1-be8e-724ecf5e3574" +version = "1.2.0" + +[[deps.GenieSession]] +deps = ["Dates", "Genie", "HTTP", "Logging", "Random", "SHA"] +git-tree-sha1 = "58a358281dcfff95bafb9d8413d5d9bd02d883a9" +uuid = "03cc5b98-4f21-4eb6-99f2-22eced81f962" +version = "1.1.3" + +[[deps.GenieSessionFileSession]] +deps = ["Genie", "GenieSession", "Logging", "Serialization"] +git-tree-sha1 = "0dd1faf1013a1bb9da969763074217b7540d5196" +uuid = "5c4fdc26-39e3-47cf-9034-e533e09961c2" +version = "1.1.1" + +[[deps.GeometryBasics]] +deps = ["EarCut_jll", "LinearAlgebra", "PrecompileTools", "Random", "StaticArrays"] +git-tree-sha1 = "ec46c5825710fa1a15d468acb2d93cc939a7a5fe" +uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326" +version = "0.5.13" + + [deps.GeometryBasics.extensions] + ExtentsExt = "Extents" + GeometryBasicsGeoInterfaceExt = "GeoInterface" + IntervalSetsExt = "IntervalSets" + + [deps.GeometryBasics.weakdeps] + Extents = "411431e0-e8b7-467b-b5e0-f676ba4f2910" + GeoInterface = "cf35fbd7-0cd7-5166-be24-54bfbe79505f" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + +[[deps.GettextRuntime_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll"] +git-tree-sha1 = "45288942190db7c5f760f59c04495064eedf9340" +uuid = "b0724c58-0f36-5564-988d-3bb0596ebc4a" +version = "0.22.4+0" + +[[deps.Ghostscript_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Zlib_jll"] +git-tree-sha1 = "38044a04637976140074d0b0621c1edf0eb531fd" +uuid = "61579ee1-b43e-5ca0-a5da-69d92c66a64b" +version = "9.55.1+0" + +[[deps.Giflib_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "a3efbbc027441271444dcd0c0a46f2d119dc4329" +uuid = "59f7168a-df46-5410-90c8-f2779963d0ec" +version = "6.1.3+0" + +[[deps.Git]] +deps = ["Git_LFS_jll", "Git_jll", "JLLWrappers", "OpenSSH_jll"] +git-tree-sha1 = "824a1890086880696fc908fe12a17bcf61738bd8" +uuid = "d7ba0133-e1db-5d97-8f8c-041e4b3a1eb2" +version = "1.5.0" + +[[deps.Git_LFS_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "d310b22511a51569401e975194cc76077bcd3786" +uuid = "020c3dae-16b3-5ae5-87b3-4cb189e250b2" +version = "3.8.1+0" + +[[deps.Git_jll]] +deps = ["Artifacts", "Expat_jll", "JLLWrappers", "LibCURL_jll", "Libdl", "Libiconv_jll", "OpenSSL_jll", "PCRE2_jll", "Zlib_jll"] +git-tree-sha1 = "3842d761162baf8efce819cdfb5ea070fe44ac40" +uuid = "f8c6e375-362e-5223-8a59-34ff63f689eb" +version = "2.56.0+0" + +[[deps.Glib_jll]] +deps = ["Artifacts", "GettextRuntime_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE2_jll", "Zlib_jll"] +git-tree-sha1 = "ea9f1fb37ff10597353b56f3ba0ebd525acef6e0" +uuid = "7746bdde-850d-59dc-9ae8-88ece973131d" +version = "2.90.1+0" + +[[deps.Glob]] +git-tree-sha1 = "246c628cec062230b7d183aab88841fa94fcabe9" +uuid = "c27321d9-0574-5035-807b-f59d2c89b15c" +version = "1.5.0" + +[[deps.Graphics]] +deps = ["Colors", "LinearAlgebra", "NaNMath"] +git-tree-sha1 = "a641238db938fff9b2f60d08ed9030387daf428c" +uuid = "a2bd30eb-e257-5431-a919-1863eab51364" +version = "1.1.3" + +[[deps.Graphite2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "69ffb934a5c5b7e086a0b4fee3427db2556fba6e" +uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472" +version = "1.3.16+0" + +[[deps.Graphs]] +deps = ["ArnoldiMethod", "DataStructures", "Distributed", "Inflate", "LinearAlgebra", "Random", "SharedArrays", "SimpleTraits", "SparseArrays", "Statistics"] +git-tree-sha1 = "7a98c6502f4632dbe9fb1973a4244eaa3324e84d" +uuid = "86223c79-3864-5bf0-83f7-82e725a168b6" +version = "1.13.1" + +[[deps.GridLayoutBase]] +deps = ["GeometryBasics", "InteractiveUtils", "Observables"] +git-tree-sha1 = "ef70da5e123a06a29e2d6ddff0f09985bc226491" +uuid = "3955a311-db13-416c-9275-1d80ed98e5e9" +version = "0.11.3" + +[[deps.HTTP]] +deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "PrecompileTools", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"] +git-tree-sha1 = "49a7885f0e1c0ecabd51b25f2fd14f26357777e0" +uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" +version = "1.11.1" + +[[deps.HarfBuzz_jll]] +deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll"] +git-tree-sha1 = "59d266e426ab9695f625fe2b6a51c2d3a04f1ecd" +uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566" +version = "100.15001.0+0" + +[[deps.HashArrayMappedTries]] +git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae" +uuid = "076d061b-32b6-4027-95e0-9a2c6f6d7e74" +version = "0.2.0" + +[[deps.HistogramThresholding]] +deps = ["ImageBase", "LinearAlgebra", "MappedArrays"] +git-tree-sha1 = "7194dfbb2f8d945abdaf68fa9480a965d6661e69" +uuid = "2c695a8d-9458-5d45-9878-1b8a99cf7853" +version = "0.3.1" + +[[deps.HostCPUFeatures]] +deps = ["BitTwiddlingConvenienceFunctions", "IfElse", "Libdl", "Preferences", "Static"] +git-tree-sha1 = "af9ab7d1f70739a47f03be78771ebda38c3c71bf" +uuid = "3e5b6fbb-0976-4d2c-9146-d79de83f2fb0" +version = "0.1.18" + +[[deps.HttpCommon]] +deps = ["Dates", "Nullables", "Test", "URIParser"] +git-tree-sha1 = "46313284237aa6ca67a6bce6d6fbd323d19cff59" +uuid = "77172c1b-203f-54ac-aa54-3f1198fe9f90" +version = "0.5.0" + +[[deps.HypergeometricFunctions]] +deps = ["Gamma", "LinearAlgebra"] +git-tree-sha1 = "c28dceeadc1c9c699656a3ac9d63f79cfaa17472" +uuid = "34004b35-14d8-5ef3-9330-4cdb6864b03a" +version = "0.3.31" + +[[deps.IOCapture]] +deps = ["Logging", "Random"] +git-tree-sha1 = "0ee181ec08df7d7c911901ea38baf16f755114dc" +uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89" +version = "1.0.0" + +[[deps.IfElse]] +git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1" +uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173" +version = "0.1.1" + +[[deps.ImageAxes]] +deps = ["AxisArrays", "ImageBase", "ImageCore", "Reexport", "SimpleTraits"] +git-tree-sha1 = "e12629406c6c4442539436581041d372d69c55ba" +uuid = "2803e5a7-5153-5ecf-9a86-9b4c37f5f5ac" +version = "0.6.12" + +[[deps.ImageBase]] +deps = ["ImageCore", "Reexport"] +git-tree-sha1 = "eb49b82c172811fd2c86759fa0553a2221feb909" +uuid = "c817782e-172a-44cc-b673-b171935fbb9e" +version = "0.1.7" + +[[deps.ImageBinarization]] +deps = ["HistogramThresholding", "ImageCore", "LinearAlgebra", "Polynomials", "Reexport", "Statistics"] +git-tree-sha1 = "33485b4e40d1df46c806498c73ea32dc17475c59" +uuid = "cbc4b850-ae4b-5111-9e64-df94c024a13d" +version = "0.3.1" + +[[deps.ImageComponentAnalysis]] +deps = ["AbstractTrees", "ConvexHulls2d", "DataFrames", "DataStructures", "ImageFiltering", "LeftChildRightSiblingTrees", "LinearAlgebra", "OffsetArrays", "Parameters", "StaticArrays"] +git-tree-sha1 = "0f1e954d54bafec3df4aa9d1ce1f110e311a9043" +uuid = "d9b9e9a0-1569-11e9-2cb5-bbca914b0e89" +version = "0.2.2" + +[[deps.ImageContrastAdjustment]] +deps = ["ImageBase", "ImageCore", "ImageTransformations", "Parameters"] +git-tree-sha1 = "4051d637a9536eb9f4aa731b8e2b31d1cd39ae64" +uuid = "f332f351-ec65-5f6a-b3d1-319c6670881a" +version = "0.3.13" + +[[deps.ImageCore]] +deps = ["ColorVectorSpace", "Colors", "FixedPointNumbers", "MappedArrays", "MosaicViews", "OffsetArrays", "PaddedViews", "PrecompileTools", "Reexport"] +git-tree-sha1 = "8c193230235bbcee22c8066b0374f63b5683c2d3" +uuid = "a09fc81d-aa75-5fe9-8630-4744c3626534" +version = "0.10.5" + +[[deps.ImageCorners]] +deps = ["ImageCore", "ImageFiltering", "PrecompileTools", "StaticArrays", "StatsBase"] +git-tree-sha1 = "24c52de051293745a9bad7d73497708954562b79" +uuid = "89d5987c-236e-4e32-acd0-25bd6bd87b70" +version = "0.1.3" + +[[deps.ImageDistances]] +deps = ["Distances", "ImageCore", "ImageMorphology", "LinearAlgebra", "Statistics"] +git-tree-sha1 = "08b0e6354b21ef5dd5e49026028e41831401aca8" +uuid = "51556ac3-7006-55f5-8cb3-34580c88182d" +version = "0.2.17" + +[[deps.ImageFiltering]] +deps = ["CatIndices", "ComputationalResources", "DataStructures", "FFTViews", "FFTW", "ImageBase", "ImageCore", "LinearAlgebra", "OffsetArrays", "PrecompileTools", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "TiledIteration"] +git-tree-sha1 = "52116260a234af5f69969c5286e6a5f8dc3feab8" +uuid = "6a3955dd-da59-5b1f-98d4-e7296123deb5" +version = "0.7.12" + +[[deps.ImageIO]] +deps = ["FileIO", "IndirectArrays", "JpegTurbo", "LazyModules", "Netpbm", "OpenEXR", "PNGFiles", "QOI", "Sixel", "TiffImages", "UUIDs", "WebP"] +git-tree-sha1 = "f0f005f997dfb8c5fe23920d99458a9619873893" +uuid = "82e4d734-157c-48bb-816b-45c225c6df19" +version = "0.6.10" + +[[deps.ImageMagick]] +deps = ["FileIO", "ImageCore", "ImageMagick_jll", "InteractiveUtils"] +git-tree-sha1 = "8e64ab2f0da7b928c8ae889c514a52741debc1c2" +uuid = "6218d12a-5da1-5696-b52f-db25d2ecc6d1" +version = "1.4.2" + +[[deps.ImageMagick_jll]] +deps = ["Artifacts", "Bzip2_jll", "FFTW_jll", "Ghostscript_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "OpenJpeg_jll", "Zlib_jll", "Zstd_jll", "libpng_jll", "libwebp_jll", "libzip_jll"] +git-tree-sha1 = "1bb9ff98fead7d25c16d773b02ae13895e8abe74" +uuid = "c73af94c-d91f-53ed-93a7-00f77d67a9d7" +version = "7.1.2029+0" + +[[deps.ImageMetadata]] +deps = ["AxisArrays", "ImageAxes", "ImageBase", "ImageCore"] +git-tree-sha1 = "2a81c3897be6fbcde0802a0ebe6796d0562f63ec" +uuid = "bc367c6b-8a6b-528e-b4bd-a4b897500b49" +version = "0.9.10" + +[[deps.ImageMorphology]] +deps = ["DataStructures", "ImageCore", "LinearAlgebra", "LoopVectorization", "OffsetArrays", "Requires", "TiledIteration"] +git-tree-sha1 = "cffa21df12f00ca1a365eb8ed107614b40e8c6da" +uuid = "787d08f9-d448-5407-9aad-5290dd7ab264" +version = "0.4.6" + +[[deps.ImageQualityIndexes]] +deps = ["ImageContrastAdjustment", "ImageCore", "ImageDistances", "ImageFiltering", "LazyModules", "OffsetArrays", "PrecompileTools", "Statistics"] +git-tree-sha1 = "783b70725ed326340adf225be4889906c96b8fd1" +uuid = "2996bd0c-7a13-11e9-2da2-2f5ce47296a9" +version = "0.3.7" + +[[deps.ImageSegmentation]] +deps = ["Clustering", "DataStructures", "Distances", "Graphs", "ImageCore", "ImageFiltering", "ImageMorphology", "LinearAlgebra", "MetaGraphs", "RegionTrees", "SimpleWeightedGraphs", "StaticArrays", "Statistics"] +git-tree-sha1 = "7196039573b6f312864547eb7a74360d6c0ab8e6" +uuid = "80713f31-8817-5129-9cf8-209ff8fb23e1" +version = "1.9.0" + +[[deps.ImageShow]] +deps = ["Base64", "ColorSchemes", "FileIO", "ImageBase", "ImageCore", "OffsetArrays", "StackViews"] +git-tree-sha1 = "3b5344bcdbdc11ad58f3b1956709b5b9345355de" +uuid = "4e3cecfd-b093-5904-9786-8bbb286a6a31" +version = "0.3.8" + +[[deps.ImageTransformations]] +deps = ["AxisAlgorithms", "CoordinateTransformations", "ImageBase", "ImageCore", "Interpolations", "OffsetArrays", "Rotations", "StaticArrays"] +git-tree-sha1 = "d48ebb91ef84ce0c091f2161c5d29c119d8c7833" +uuid = "02fcd773-0e25-5acc-982a-7f6622650795" +version = "0.10.3" + +[[deps.Images]] +deps = ["Base64", "FileIO", "Graphics", "ImageAxes", "ImageBase", "ImageBinarization", "ImageContrastAdjustment", "ImageCore", "ImageCorners", "ImageDistances", "ImageFiltering", "ImageIO", "ImageMagick", "ImageMetadata", "ImageMorphology", "ImageQualityIndexes", "ImageSegmentation", "ImageShow", "ImageTransformations", "IndirectArrays", "IntegralArrays", "Random", "Reexport", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "TiledIteration"] +git-tree-sha1 = "a49b96fd4a8d1a9a718dfd9cde34c154fc84fcd5" +uuid = "916415d5-f1e6-5110-898d-aaa5f9f070e0" +version = "0.26.2" + +[[deps.Imath_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "dcc8d0cd653e55213df9b75ebc6fe4a8d3254c65" +uuid = "905a6f67-0a94-5f89-b386-d35d92009cd1" +version = "3.2.2+0" + +[[deps.IndirectArrays]] +git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f" +uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959" +version = "1.0.0" + +[[deps.Inflate]] +git-tree-sha1 = "d1b1b796e47d94588b3757fe84fbf65a5ec4a80d" +uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9" +version = "0.1.5" + +[[deps.Inflector]] +deps = ["Unicode"] +git-tree-sha1 = "c82a172a07c94887709e613cc67cec0b472fb742" +uuid = "6d011eab-0732-4556-8808-e463c76bf3b6" +version = "1.1.0" + +[[deps.InlineStrings]] +git-tree-sha1 = "06b65886c7577a3784d616e29f1302c2e36e389d" +uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" +version = "1.4.6" + + [deps.InlineStrings.extensions] + ArrowTypesExt = "ArrowTypes" + ParsersExt = "Parsers" + + [deps.InlineStrings.weakdeps] + ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" + Parsers = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" + +[[deps.IntegerMathUtils]] +git-tree-sha1 = "c72458f1962faeb003bf23cbdb75164fe6280906" +uuid = "18e54dd8-cb9d-406c-a71d-865a43cbb235" +version = "0.1.4" + +[[deps.IntegralArrays]] +deps = ["ColorTypes", "FixedPointNumbers", "IntervalSets"] +git-tree-sha1 = "b842cbff3f44804a84fda409745cc8f04c029a20" +uuid = "1d092043-8f09-5a30-832f-7509e371ab51" +version = "0.1.6" + +[[deps.IntelOpenMP_jll]] +deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl"] +git-tree-sha1 = "ec1debd61c300961f98064cfb21287613ad7f303" +uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0" +version = "2025.2.0+0" + +[[deps.InteractiveUtils]] +deps = ["Markdown"] +uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" +version = "1.11.0" + +[[deps.Interpolations]] +deps = ["Adapt", "AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"] +git-tree-sha1 = "c6c24bc9db44d9ad66af947398380233900e2bcd" +uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" +version = "0.15.2" +weakdeps = ["Unitful"] + + [deps.Interpolations.extensions] + InterpolationsUnitfulExt = "Unitful" + +[[deps.IntervalArithmetic]] +deps = ["CRlibm", "CoreMath", "MacroTools", "OpenBLASConsistentFPCSR_jll", "Printf", "Random", "RoundingEmulator"] +git-tree-sha1 = "ff294afb9a15d31d8d7422da138844641a73135f" +uuid = "d1acc4aa-44c8-5952-acd4-ba5d80a2a253" +version = "1.0.11" + + [deps.IntervalArithmetic.extensions] + IntervalArithmeticArblibExt = "Arblib" + IntervalArithmeticDiffRulesExt = "DiffRules" + IntervalArithmeticForwardDiffExt = "ForwardDiff" + IntervalArithmeticIntervalSetsExt = "IntervalSets" + IntervalArithmeticIrrationalConstantsExt = "IrrationalConstants" + IntervalArithmeticLinearAlgebraExt = "LinearAlgebra" + IntervalArithmeticRecipesBaseExt = "RecipesBase" + IntervalArithmeticSparseArraysExt = "SparseArrays" + + [deps.IntervalArithmetic.weakdeps] + Arblib = "fb37089c-8514-4489-9461-98f9c8763369" + DiffRules = "b552c78f-8df3-52c6-915a-8e097449b14b" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + IrrationalConstants = "92d709cd-6900-40b7-9082-c6be49f344b6" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + RecipesBase = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + +[[deps.IntervalSets]] +git-tree-sha1 = "0db6aea5b64caa1c47e9fdd27394f0296f05e8bf" +uuid = "8197267c-284f-5f27-9208-e0e47529a953" +version = "0.7.15" +weakdeps = ["Makie", "Random", "RecipesBase", "Statistics"] + + [deps.IntervalSets.extensions] + IntervalSetsMakieExt = "Makie" + IntervalSetsRandomExt = "Random" + IntervalSetsRecipesBaseExt = "RecipesBase" + IntervalSetsStatisticsExt = "Statistics" + +[[deps.InverseFunctions]] +git-tree-sha1 = "5cc6ad3e2bfc75a11eed92632ee341d37f4a4536" +uuid = "3587e190-3f89-42d0-90ee-14403ec27112" +version = "0.1.18" +weakdeps = ["Dates", "Test"] + + [deps.InverseFunctions.extensions] + InverseFunctionsDatesExt = "Dates" + InverseFunctionsTestExt = "Test" + +[[deps.InvertedIndices]] +git-tree-sha1 = "6da3c4316095de0f5ee2ebd875df8721e7e0bdbe" +uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" +version = "1.3.1" + +[[deps.IrrationalConstants]] +git-tree-sha1 = "d22e8bdb3f03c300a103ff23c0dd5a654c6701de" +uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" +version = "0.2.7" + +[[deps.Isoband]] +deps = ["isoband_jll"] +git-tree-sha1 = "f9b6d97355599074dc867318950adaa6f9946137" +uuid = "f1662d9f-8043-43de-a69a-05efc1cc6ff4" +version = "0.1.1" + +[[deps.IterTools]] +git-tree-sha1 = "123311cf9834c6ee6a8347bba9af68f255615391" +uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e" +version = "1.11.0" + +[[deps.IteratorInterfaceExtensions]] +git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" +uuid = "82899510-4779-5014-852e-03e436cf321d" +version = "1.0.0" + +[[deps.JLD2]] +deps = ["ChunkCodecCore", "ChunkCodecLibZlib", "ChunkCodecLibZstd", "FileIO", "MacroTools", "Mmap", "OrderedCollections", "PrecompileTools", "ScopedValues"] +git-tree-sha1 = "9ce2e7c49ae4a7035b7d60db3a553b1f6c16875d" +uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819" +version = "0.6.7" +weakdeps = ["UnPack"] + + [deps.JLD2.extensions] + UnPackExt = "UnPack" + +[[deps.JLLWrappers]] +deps = ["Artifacts", "Preferences"] +git-tree-sha1 = "7204148362dafe5fe6a273f855b8ccbe4df8173e" +uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" +version = "1.8.0" + +[[deps.JSON]] +deps = ["Dates", "Mmap", "Parsers", "Unicode"] +git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" +uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +version = "0.21.4" + +[[deps.JSON3]] +deps = ["Dates", "Mmap", "Parsers", "PrecompileTools", "StructTypes", "UUIDs"] +git-tree-sha1 = "34a52631602d7233eb1dca1a358ae82b656f9f2a" +uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" +version = "1.14.4" + + [deps.JSON3.extensions] + JSON3ArrowExt = ["ArrowTypes"] + + [deps.JSON3.weakdeps] + ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" + +[[deps.JWTs]] +deps = ["Downloads", "JSON", "OpenSSL_jll", "SHA"] +git-tree-sha1 = "4c08f5525d1c33736880b50cd8f9880dda6c51df" +uuid = "d850fbd6-035d-5a70-a269-1ca2e636ac6c" +version = "1.1.0" + +[[deps.JpegTurbo]] +deps = ["CEnum", "FileIO", "ImageCore", "JpegTurbo_jll", "TOML"] +git-tree-sha1 = "9496de8fb52c224a2e3f9ff403947674517317d9" +uuid = "b835a17e-a41a-41e7-81f0-2f016b05efe0" +version = "0.1.6" + +[[deps.JpegTurbo_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e06b451acfb1c6fa5ea753b5042207226271f455" +uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8" +version = "3.2.1+0" + +[[deps.JuliaFormatter]] +deps = ["CommonMark", "Glob", "JuliaSyntax", "PrecompileTools", "TOML", "Test"] +git-tree-sha1 = "30e776e13cc3f73c925242f7fa95cf12ab45a4d4" +uuid = "98e50ef6-434e-11e9-1051-2b60c6c9e899" +version = "2.14.9" + +[[deps.JuliaInterpreter]] +deps = ["CodeTracking", "InteractiveUtils", "Random"] +git-tree-sha1 = "c35411a62b74a0288934ffcfad4fa8dd09b72630" +uuid = "aa1ae85d-cabe-5617-a682-6adf51b2e16a" +version = "0.12.2" + +[[deps.JuliaSyntax]] +git-tree-sha1 = "0d4b3dab95018bcf3925204475693d9f09dc45b8" +uuid = "70703baa-626e-46a2-a12c-08ffd08c73b4" +version = "1.0.2" + +[[deps.KernelDensity]] +deps = ["Distributions", "DocStringExtensions", "FFTA", "Interpolations", "StatsBase"] +git-tree-sha1 = "19fa81989298fc2fb103fee29b03c5284f17e8a5" +uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b" +version = "0.6.13" + +[[deps.LAME_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "059aabebaa7c82ccb853dd4a0ee9d17796f7e1bc" +uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d" +version = "3.100.3+0" + +[[deps.LERC_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6d7c65411dda4bfa0beb7490476122b4f805cf31" +uuid = "88015f11-f218-50d7-93a8-a6af411a945d" +version = "4.3.0+0" + +[[deps.LLVMOpenMP_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e5b100780d4d30d63b4618d7930d48af409c1772" +uuid = "1d63c593-3942-5779-bab2-d838dc0a180e" +version = "23.1.1+0" + +[[deps.LaTeXStrings]] +git-tree-sha1 = "f88f3ccef05a6a72a0cf0ed417c8fd68530f4ab2" +uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" +version = "1.4.1" + +[[deps.LayoutPointers]] +deps = ["ArrayInterface", "LinearAlgebra", "ManualMemory", "SIMDTypes", "Static", "StaticArrayInterface"] +git-tree-sha1 = "a9eaadb366f5493a5654e843864c13d8b107548c" +uuid = "10f19ff3-798f-405d-979b-55457f8fc047" +version = "0.1.17" + +[[deps.LazilyInitializedFields]] +git-tree-sha1 = "0f2da712350b020bc3957f269c9caad516383ee0" +uuid = "0e77f7df-68c5-4e49-93ce-4cd80f5598bf" +version = "1.3.0" + +[[deps.LazyArtifacts]] +deps = ["Artifacts", "Pkg"] +uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3" +version = "1.11.0" + +[[deps.LazyModules]] +git-tree-sha1 = "a560dd966b386ac9ae60bdd3a3d3a326062d3c3e" +uuid = "8cdb02fc-e678-4876-92c5-9defec4f444e" +version = "0.3.1" + +[[deps.LeftChildRightSiblingTrees]] +deps = ["AbstractTrees"] +git-tree-sha1 = "95ba48564903b43b2462318aa243ee79d81135ff" +uuid = "1d6d02ad-be62-4b6b-8a6d-2f90e265016e" +version = "0.2.1" + +[[deps.LibCURL]] +deps = ["LibCURL_jll", "MozillaCACerts_jll"] +uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" +version = "0.6.4" + +[[deps.LibCURL_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] +uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" +version = "8.6.0+0" + +[[deps.LibGit2]] +deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] +uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" +version = "1.11.0" + +[[deps.LibGit2_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] +uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" +version = "1.7.2+0" + +[[deps.LibSSH2_jll]] +deps = ["Artifacts", "Libdl", "MbedTLS_jll"] +uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" +version = "1.11.0+1" + +[[deps.Libdl]] +uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" +version = "1.11.0" + +[[deps.Libepoxy_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Xorg_libX11_jll"] +git-tree-sha1 = "94d068f57b4241dd090693b6aba63416892298de" +uuid = "42c93a91-0102-5b3f-8f9d-e41de60ac950" +version = "1.5.11+0" + +[[deps.Libffi_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "c8da7e6a91781c41a863611c7e966098d783c57a" +uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490" +version = "3.4.7+0" + +[[deps.Libglvnd_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll", "Xorg_libXext_jll"] +git-tree-sha1 = "d36c21b9e7c172a44a10484125024495e2625ac0" +uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29" +version = "1.7.1+1" + +[[deps.Libiconv_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "be484f5c92fad0bd8acfef35fe017900b0b73809" +uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" +version = "1.18.0+0" + +[[deps.Libmount_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b8a91037379e1fd661e9b5ff3d7a770424b1f9f2" +uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9" +version = "2.42.4+0" + +[[deps.Libtiff_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "LERC_jll", "Libdl", "XZ_jll", "Zlib_jll", "Zstd_jll"] +git-tree-sha1 = "aebd334d06cee9f24cea70bd19a39749daf73881" +uuid = "89763e89-9b03-5906-acba-b20f662cd828" +version = "4.7.3+0" + +[[deps.Libuuid_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "9e887184f306b28dbfcff88cefbb0ec80f1aa9e0" +uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700" +version = "2.42.4+0" + +[[deps.Libz]] +deps = ["BufferedStreams", "Random", "Test"] +git-tree-sha1 = "bf1510e80f1e0dba2297b05b59a3a7c8175a9517" +uuid = "2ec943e9-cfe8-584d-b93d-64dcb6d567b7" +version = "1.0.1" + +[[deps.LinearAlgebra]] +deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] +uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +version = "1.11.0" + +[[deps.LittleCMS_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll"] +git-tree-sha1 = "38928f7999753af13d4e13966ae15958ff3a917a" +uuid = "d3a379c0-f9a3-5b72-a4c0-6bf4d2e8af0f" +version = "2.19.1+0" + +[[deps.Loess]] +deps = ["Distances", "LinearAlgebra", "Statistics", "StatsAPI", "StatsFuns"] +git-tree-sha1 = "aac61f60ed2b1561ae1bbef4e6d7b75c27f1f9e3" +uuid = "4345ca2d-374a-55d4-8d30-97f9976e7612" +version = "0.6.6" + +[[deps.LogExpFunctions]] +deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"] +git-tree-sha1 = "13ca9e2586b89836fd20cccf56e57e2b9ae7f38f" +uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" +version = "0.3.29" + + [deps.LogExpFunctions.extensions] + LogExpFunctionsChainRulesCoreExt = "ChainRulesCore" + LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables" + LogExpFunctionsInverseFunctionsExt = "InverseFunctions" + + [deps.LogExpFunctions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + +[[deps.Logging]] +uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" +version = "1.11.0" + +[[deps.LoggingExtras]] +deps = ["Dates", "Logging"] +git-tree-sha1 = "f00544d95982ea270145636c181ceda21c4e2575" +uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36" +version = "1.2.0" + +[[deps.LoopVectorization]] +deps = ["ArrayInterface", "CPUSummary", "CloseOpenIntervals", "DocStringExtensions", "HostCPUFeatures", "IfElse", "LayoutPointers", "LinearAlgebra", "OffsetArrays", "PolyesterWeave", "PrecompileTools", "SIMDTypes", "SLEEFPirates", "Static", "StaticArrayInterface", "ThreadingUtilities", "UnPack", "VectorizationBase"] +git-tree-sha1 = "7a8449291a67c97435ec4d704ca08a548097305c" +uuid = "bdcacae8-1622-11e9-2a5c-532679323890" +version = "0.12.175" + + [deps.LoopVectorization.extensions] + ForwardDiffExt = ["ChainRulesCore", "ForwardDiff"] + ForwardDiffNNlibExt = ["ForwardDiff", "NNlib"] + SpecialFunctionsExt = "SpecialFunctions" + + [deps.LoopVectorization.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + NNlib = "872c559c-99b0-510c-b3b7-b6c96a88d5cd" + SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b" + +[[deps.LoweredCodeUtils]] +deps = ["CodeTracking", "Compiler", "JuliaInterpreter"] +git-tree-sha1 = "b3383cd2b17d8ad4ab7becf07cea43ad692c58bf" +uuid = "6f1432cf-f94c-5a45-995e-cdbf5db27b0b" +version = "3.10.2" + +[[deps.MIMEs]] +git-tree-sha1 = "c64d943587f7187e751162b3b84445bbbd79f691" +uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65" +version = "1.1.0" + +[[deps.MKL_jll]] +deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "oneTBB_jll"] +git-tree-sha1 = "282cadc186e7b2ae0eeadbd7a4dffed4196ae2aa" +uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7" +version = "2025.2.0+0" + +[[deps.MSI_src]] +deps = ["Accessors", "Base64", "CSV", "CairoMakie", "CodecBase", "ColorSchemes", "Colors", "ContinuousWavelets", "DataFrames", "Dates", "FileIO", "Genie", "GenieFramework", "HistogramThresholding", "ImageBinarization", "ImageComponentAnalysis", "ImageContrastAdjustment", "ImageCore", "ImageFiltering", "ImageMorphology", "ImageSegmentation", "Images", "Interpolations", "JLD2", "JSON", "Libz", "LinearAlgebra", "Loess", "Mmap", "NativeFileDialog", "NaturalSort", "PackageCompiler", "Parameters", "PlotlyBase", "Printf", "ProgressMeter", "SavitzkyGolay", "Serialization", "Setfield", "SparseArrays", "Statistics", "StatsBase", "StipplePlotly", "UUIDs"] +path = "../JuliaMSI" +uuid = "8f395f85-3b9c-4f7f-bf7e-12345678abcd" +version = "0.1.0" + +[[deps.MacroTools]] +git-tree-sha1 = "1e0228a030642014fe5cfe68c2c0a818f9e3f522" +uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" +version = "0.5.16" + +[[deps.Makie]] +deps = ["Animations", "Base64", "CRC32c", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "Contour", "Dates", "DelaunayTriangulation", "Distributions", "DocStringExtensions", "Downloads", "FFMPEG_jll", "FileIO", "FilePaths", "FixedPointNumbers", "Format", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageBase", "ImageIO", "InteractiveUtils", "Interpolations", "IntervalSets", "InverseFunctions", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MacroTools", "MakieCore", "Markdown", "MathTeXEngine", "Observables", "OffsetArrays", "PNGFiles", "Packing", "PlotUtils", "PolygonOps", "PrecompileTools", "Printf", "REPL", "Random", "RelocatableFolders", "Scratch", "ShaderAbstractions", "Showoff", "SignedDistanceFields", "SparseArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "TriplotBase", "UnicodeFun", "Unitful"] +git-tree-sha1 = "1d7d16f0e02ec063becd7a140f619b2ffe5f2b11" +uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" +version = "0.22.10" + +[[deps.MakieCore]] +deps = ["ColorTypes", "GeometryBasics", "IntervalSets", "Observables"] +git-tree-sha1 = "c3159eb1e3aa3e409edbb71f4035ed8b1fc16e23" +uuid = "20f20a25-4f0e-4fdf-b5d1-57303727442b" +version = "0.9.5" + +[[deps.ManualMemory]] +git-tree-sha1 = "bcaef4fc7a0cfe2cba636d84cda54b5e4e4ca3cd" +uuid = "d125e4d3-2237-4719-b19c-fa641b8a4667" +version = "0.1.8" + +[[deps.MappedArrays]] +git-tree-sha1 = "0ee4497a4e80dbd29c058fcee6493f5219556f40" +uuid = "dbb5928d-eab1-5f90-85c2-b9b0edb7c900" +version = "0.4.3" + +[[deps.Markdown]] +deps = ["Base64"] +uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" +version = "1.11.0" + +[[deps.MarkdownAST]] +deps = ["AbstractTrees", "Markdown"] +git-tree-sha1 = "93c718d892e73931841089cdc0e982d6dd9cc87b" +uuid = "d0879d2d-cac2-40c8-9cee-1863dc0c7391" +version = "0.1.3" + +[[deps.MathTeXEngine]] +deps = ["AbstractTrees", "Automa", "DataStructures", "FreeTypeAbstraction", "GeometryBasics", "LaTeXStrings", "REPL", "RelocatableFolders", "UnicodeFun"] +git-tree-sha1 = "aa1078778be5a8e5259ff04fbc3d258b3e78d464" +uuid = "0a4f8689-d25c-4efe-a92b-7142dfc1aa53" +version = "0.6.9" + +[[deps.MbedTLS]] +deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"] +git-tree-sha1 = "0e4b139a1f0f0b8c054fcdfd3be5f610cfb8c787" +uuid = "739be429-bea8-5141-9913-cc70e7f3736d" +version = "1.2.0" + +[[deps.MbedTLS_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" +version = "2.28.6+0" + +[[deps.MetaGraphs]] +deps = ["Graphs", "JLD2", "Random"] +git-tree-sha1 = "3a8f462a180a9d735e340f4e8d5f364d411da3a4" +uuid = "626554b9-1ddb-594c-aa3c-2596fe9399a5" +version = "0.8.1" + +[[deps.Millboard]] +git-tree-sha1 = "ea6a5b7e56e76d8051023faaa11d91d1d881dac3" +uuid = "39ec1447-df44-5f4c-beaa-866f30b4d3b2" +version = "0.2.5" + +[[deps.Missings]] +deps = ["DataAPI"] +git-tree-sha1 = "d9d20d6eb2a3290ba5c70a1c013b45305cc39c9e" +uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" +version = "1.2.1" + +[[deps.Mixers]] +deps = ["MacroTools"] +git-tree-sha1 = "58ec7ac60dad6e8ca4553225251dfd380e3930dd" +uuid = "2a8e4939-dab8-5edc-8f64-72a8776f13de" +version = "0.1.2" + +[[deps.Mmap]] +uuid = "a63ad114-7e13-5084-954f-fe012c677804" +version = "1.11.0" + +[[deps.ModelContextProtocol]] +deps = ["Base64", "DataStructures", "Dates", "HTTP", "JSON3", "JWTs", "Logging", "MacroTools", "OrderedCollections", "PrecompileTools", "Random", "StructTypes", "URIs", "UUIDs"] +git-tree-sha1 = "1d3cbe70aec76a0851e5087b8a40204d4fbce3fb" +uuid = "c58f755f-f2a7-4f48-bf29-4e9659b78499" +version = "0.6.1" + +[[deps.MosaicViews]] +deps = ["MappedArrays", "OffsetArrays", "PaddedViews", "StackViews"] +git-tree-sha1 = "7b86a5d4d70a9f5cdf2dacb3cbe6d251d1a61dbe" +uuid = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389" +version = "0.3.4" + +[[deps.MozillaCACerts_jll]] +uuid = "14a3606d-f60d-562e-9121-12d972cd8159" +version = "2023.12.12" + +[[deps.MuladdMacro]] +deps = ["PrecompileTools"] +git-tree-sha1 = "283bf85d4a767481dd924dff0eee1735e95f449e" +uuid = "46d2c3a1-f734-5fdb-9937-b9b9aeba4221" +version = "0.2.7" + +[[deps.NaNMath]] +deps = ["OpenLibm_jll"] +git-tree-sha1 = "676c0f1c1c34224d6869675047a54b42fdc7b8c5" +uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +version = "1.1.5" + +[[deps.NativeFileDialog]] +deps = ["FilePathsBase", "NativeFileDialog_jll"] +git-tree-sha1 = "6964c902c838b214cb4e8b4a94ca45e585c9d47b" +uuid = "e1fe445b-aa65-4df4-81c1-2041507f0fd4" +version = "0.2.1" + +[[deps.NativeFileDialog_jll]] +deps = ["Artifacts", "GTK3_jll", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "916d2db66748820c8e8bc3329a2a23c42c1520de" +uuid = "94d9ae2c-efc7-56f8-9a02-54c47b797961" +version = "1.1.6+3" + +[[deps.NaturalSort]] +git-tree-sha1 = "eda490d06b9f7c00752ee81cfa451efe55521e21" +uuid = "c020b1a1-e9b0-503a-9c33-f039bfc54a85" +version = "1.0.0" + +[[deps.NearestNeighbors]] +deps = ["AbstractTrees", "Distances", "StaticArrays"] +git-tree-sha1 = "576eb4656529c12e77a46b17c23103dfba9fa570" +uuid = "b8a86587-4115-5ab1-83bc-aa920d37bbce" +version = "0.4.29" + +[[deps.Netpbm]] +deps = ["FileIO", "ImageCore", "ImageMetadata"] +git-tree-sha1 = "d92b107dbb887293622df7697a2223f9f8176fcd" +uuid = "f09324ee-3d7c-5217-9330-fc30815ba969" +version = "1.1.1" + +[[deps.Nettle]] +deps = ["Libdl", "Nettle_jll"] +git-tree-sha1 = "6fa48cbae828267848ee32c1bb31d1652e210d7d" +uuid = "49dea1ee-f6fa-5aa6-9a11-8816cee7d4b9" +version = "1.0.0" + +[[deps.Nettle_jll]] +deps = ["Artifacts", "GMP_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "2759db33ad6145e162d49d86360b350c9c79354f" +uuid = "4c82536e-c426-54e4-b420-14f461c4ed8b" +version = "3.10.2+0" + +[[deps.NetworkOptions]] +uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" +version = "1.2.0" + +[[deps.Nullables]] +git-tree-sha1 = "8f87854cc8f3685a60689d8edecaa29d2251979b" +uuid = "4d1e1d77-625e-5b40-9113-a560ec7a8ecd" +version = "1.0.0" + +[[deps.Observables]] +git-tree-sha1 = "7438a59546cf62428fc9d1bc94729146d37a7225" +uuid = "510215fc-4207-5dde-b226-833fc4488ee2" +version = "0.5.5" + +[[deps.OffsetArrays]] +git-tree-sha1 = "750d0f2b5aac238d50dfee5f7a44fae3175a3305" +uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881" +version = "1.18.0" +weakdeps = ["Adapt"] + + [deps.OffsetArrays.extensions] + OffsetArraysAdaptExt = "Adapt" + +[[deps.Ogg_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "b6aa4566bb7ae78498a5e68943863fa8b5231b59" +uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051" +version = "1.3.6+0" + +[[deps.OpenBLASConsistentFPCSR_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "38a93f17e431141c6470bb67a88952a7c4f0e928" +uuid = "6cdc7f73-28fd-5e50-80fb-958a8875b1af" +version = "0.3.34+0" + +[[deps.OpenBLAS_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] +uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" +version = "0.3.27+1" + +[[deps.OpenEXR]] +deps = ["Colors", "FileIO", "OpenEXR_jll"] +git-tree-sha1 = "97db9e07fe2091882c765380ef58ec553074e9c7" +uuid = "52e1d378-f018-4a11-a4be-720524705ac7" +version = "0.3.3" + +[[deps.OpenEXR_jll]] +deps = ["Artifacts", "Imath_jll", "JLLWrappers", "Libdl", "OpenJPH_jll", "Zlib_jll", "Zstd_jll", "libdeflate_jll"] +git-tree-sha1 = "afa66dc1246b28b68600d053715e00a379268980" +uuid = "18a262bb-aa17-5467-a713-aee519bc75cb" +version = "3.5.3+0" + +[[deps.OpenJPH_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libtiff_jll"] +git-tree-sha1 = "1b1f3cabb1130670812b848f4623d69d578ea805" +uuid = "95196869-6d61-5868-8eee-c38c33804e0c" +version = "0.32.0+0" + +[[deps.OpenJpeg_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libtiff_jll", "LittleCMS_jll", "libpng_jll"] +git-tree-sha1 = "215a6666fee6d6b3a6e75f2cc22cb767e2dd393a" +uuid = "643b3616-a352-519d-856d-80112ee9badc" +version = "2.5.5+0" + +[[deps.OpenLibm_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "05823500-19ac-5b8b-9628-191a04bc5112" +version = "0.8.5+0" + +[[deps.OpenSSH_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "OpenSSL_jll", "Zlib_jll"] +git-tree-sha1 = "1f640b82a627df3dbbaaff756a201a9ceb10dd1f" +uuid = "9bd350c2-7e96-507f-8002-3f2e150b4e1b" +version = "10.6.1+0" + +[[deps.OpenSSL]] +deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "NetworkOptions", "OpenSSL_jll", "Sockets"] +git-tree-sha1 = "571a7f66ba42342ee37b46e5b927d3883983b3c1" +uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c" +version = "1.11.0" + +[[deps.OpenSSL_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "20dd6a885a6fe8b07584d3eb8073133ad04c72e3" +uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" +version = "3.5.9+0" + +[[deps.OpenSpecFun_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1346c9208249809840c91b26703912dff463d335" +uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" +version = "0.5.6+0" + +[[deps.Opus_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e2bb57a313a74b8104064b7efd01406c0a50d2ff" +uuid = "91d4177d-7536-5919-b921-800302f37372" +version = "1.6.1+0" + +[[deps.OrderedCollections]] +git-tree-sha1 = "94ba93778373a53bfd5a0caaf7d809c445292ff4" +uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" +version = "1.8.2" + +[[deps.PCRE2_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "efcefdf7-47ab-520b-bdef-62a2eaa19f15" +version = "10.42.0+1" + +[[deps.PDMats]] +deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"] +git-tree-sha1 = "123266c25174ef6c8d4718920abc206452cf8de6" +uuid = "90014a1f-27ba-587c-ab20-58faa44d9150" +version = "0.11.41" +weakdeps = ["StatsBase"] + + [deps.PDMats.extensions] + StatsBaseExt = "StatsBase" + +[[deps.PNGFiles]] +deps = ["Base64", "CEnum", "ImageCore", "IndirectArrays", "OffsetArrays", "libpng_jll"] +git-tree-sha1 = "32b657a0d57c310a1a172bfc8c8cf68c5e674323" +uuid = "f57f5aa1-a3ce-4bc8-8ab9-96f992907883" +version = "0.4.5" + +[[deps.PackageCompiler]] +deps = ["Artifacts", "FileWatching", "Glob", "LazyArtifacts", "Libdl", "Pkg", "Printf", "RelocatableFolders", "SHA", "Scratch", "TOML", "UUIDs", "p7zip_jll"] +git-tree-sha1 = "2ae7775a207e94fd829174c2bb1d319670c37589" +uuid = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d" +version = "2.4.5" + +[[deps.Packing]] +deps = ["GeometryBasics"] +git-tree-sha1 = "bc5bf2ea3d5351edf285a06b0016788a121ce92c" +uuid = "19eb6ba3-879d-56ad-ad62-d5c202156566" +version = "0.5.1" + +[[deps.PaddedViews]] +deps = ["OffsetArrays"] +git-tree-sha1 = "0fac6313486baae819364c52b4f483450a9d793f" +uuid = "5432bcbf-9aad-5242-b902-cca2824c8663" +version = "0.5.12" + +[[deps.Pango_jll]] +deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1912a9f1b9ca55005b03ba075f8e19993583e237" +uuid = "36c8627f-9965-5494-a995-c6b170f724f3" +version = "1.58.2+0" + +[[deps.Parameters]] +deps = ["OrderedCollections", "UnPack"] +git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe" +uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a" +version = "0.12.3" + +[[deps.Parsers]] +deps = ["Dates", "PrecompileTools", "UUIDs"] +git-tree-sha1 = "2facd7b5863092567d54590997caf8f6db8e0b1e" +uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" +version = "2.8.11" + +[[deps.Pixman_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "LLVMOpenMP_jll", "Libdl"] +git-tree-sha1 = "e4a6721aa89e62e5d4217c0b21bd714263779dda" +uuid = "30392449-352a-5448-841d-b1acce4e97dc" +version = "0.46.4+0" + +[[deps.Pkg]] +deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "Random", "SHA", "TOML", "Tar", "UUIDs", "p7zip_jll"] +uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +version = "1.11.0" +weakdeps = ["REPL"] + + [deps.Pkg.extensions] + REPLExt = "REPL" + +[[deps.PkgVersion]] +deps = ["Pkg"] +git-tree-sha1 = "f9501cc0430a26bc3d156ae1b5b0c1b47af4d6da" +uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688" +version = "0.3.3" + +[[deps.PlotUtils]] +deps = ["ColorSchemes", "Colors", "Dates", "PrecompileTools", "Printf", "Reexport", "Statistics"] +git-tree-sha1 = "ddcc36fd83fb4cd459a53c891981697bde0d3de6" +uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043" +version = "1.5.1" + +[[deps.PlotlyBase]] +deps = ["ColorSchemes", "Colors", "Dates", "DelimitedFiles", "DocStringExtensions", "JSON", "LaTeXStrings", "Logging", "Parameters", "Pkg", "REPL", "Requires", "Statistics", "UUIDs"] +git-tree-sha1 = "6256ab3ee24ef079b3afa310593817e069925eeb" +uuid = "a03496cd-edff-5a9b-9e67-9cda94a718b5" +version = "0.8.23" + + [deps.PlotlyBase.extensions] + DataFramesExt = "DataFrames" + DistributionsExt = "Distributions" + IJuliaExt = "IJulia" + JSON3Ext = "JSON3" + + [deps.PlotlyBase.weakdeps] + DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" + Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f" + IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" + JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" + +[[deps.PolyesterWeave]] +deps = ["BitTwiddlingConvenienceFunctions", "CPUSummary", "IfElse", "Static", "ThreadingUtilities"] +git-tree-sha1 = "645bed98cd47f72f67316fd42fc47dee771aefcd" +uuid = "1d0040c9-8b98-4ee7-8388-3f51789ca0ad" +version = "0.2.2" + +[[deps.PolygonOps]] +git-tree-sha1 = "77b3d3605fc1cd0b42d95eba87dfcd2bf67d5ff6" +uuid = "647866c9-e3ac-4575-94e7-e3d426903924" +version = "0.1.2" + +[[deps.Polynomials]] +deps = ["LinearAlgebra", "OrderedCollections", "RecipesBase", "Requires", "Setfield", "SparseArrays"] +git-tree-sha1 = "2660ba4e0e9354cf0f3deeefb61531bbdac5495d" +uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45" +version = "4.0.21" + + [deps.Polynomials.extensions] + PolynomialsChainRulesCoreExt = "ChainRulesCore" + PolynomialsFFTWExt = "FFTW" + PolynomialsMakieCoreExt = "MakieCore" + PolynomialsMutableArithmeticsExt = "MutableArithmetics" + + [deps.Polynomials.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" + MakieCore = "20f20a25-4f0e-4fdf-b5d1-57303727442b" + MutableArithmetics = "d8a4904e-b15c-11e9-3269-09a3773c0cb0" + +[[deps.PooledArrays]] +deps = ["DataAPI", "Future"] +git-tree-sha1 = "36d8b4b899628fb92c2749eb488d884a926614d3" +uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" +version = "1.4.3" + +[[deps.PrecompileTools]] +deps = ["Preferences"] +git-tree-sha1 = "5aa36f7049a63a1528fe8f7c3f2113413ffd4e1f" +uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +version = "1.2.1" + +[[deps.Preferences]] +deps = ["TOML"] +git-tree-sha1 = "aef1987d90dcc2e2cbd919ad10b2d25bcce4f418" +uuid = "21216c6a-2e73-6563-6e65-726566657250" +version = "1.6.1" + +[[deps.PrettyTables]] +deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "REPL", "Reexport", "StringManipulation", "StyledStrings", "Tables"] +git-tree-sha1 = "eeac4c9337f876c3c32b8da732141953567f57c9" +uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" +version = "3.5.1" + + [deps.PrettyTables.extensions] + PrettyTablesExcelExt = "XLSX" + PrettyTablesTypstryExt = "Typstry" + PrettyTablesWriteDocxExt = "WriteDocx" + + [deps.PrettyTables.weakdeps] + Typstry = "f0ed7684-a786-439e-b1e3-3b82803b501e" + WriteDocx = "d049ceea-54ee-41d7-a26f-ba29db3b6599" + XLSX = "fdbf4ff8-1666-58a4-91e7-1b58723a45e0" + +[[deps.Primes]] +deps = ["IntegerMathUtils"] +git-tree-sha1 = "25cdd1d20cd005b52fc12cb6be3f75faaf59bb9b" +uuid = "27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae" +version = "0.5.7" + +[[deps.Printf]] +deps = ["Unicode"] +uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" +version = "1.11.0" + +[[deps.ProgressMeter]] +deps = ["Printf"] +git-tree-sha1 = "ce5ba3edfdeba107a721748d53b5f5887f415853" +uuid = "92933f4c-e287-5a05-a399-4b506db050ca" +version = "1.13.0" + + [deps.ProgressMeter.extensions] + ProgressMeterDistributedExt = "Distributed" + ProgressMeterIJuliaExt = "IJulia" + + [deps.ProgressMeter.weakdeps] + Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" + IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a" + +[[deps.PtrArrays]] +git-tree-sha1 = "4fbbafbc6251b883f4d2705356f3641f3652a7fe" +uuid = "43287f4e-b6f4-7ad1-bb20-aadabca52c3d" +version = "1.4.0" + +[[deps.QOI]] +deps = ["ColorTypes", "FileIO", "FixedPointNumbers"] +git-tree-sha1 = "472daaa816895cb7aee81658d4e7aec901fa1106" +uuid = "4b34888f-f399-49d4-9bb3-47ed5cae4e65" +version = "1.0.2" + +[[deps.QuadGK]] +deps = ["DataStructures", "LinearAlgebra"] +git-tree-sha1 = "5e8e8b0ab68215d7a2b14b9921a946fee794749e" +uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc" +version = "2.11.3" + + [deps.QuadGK.extensions] + QuadGKEnzymeExt = "Enzyme" + + [deps.QuadGK.weakdeps] + Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" + +[[deps.Quaternions]] +deps = ["LinearAlgebra", "Random", "RealDot"] +git-tree-sha1 = "4d8c1b7c3329c1885b857abb50d08fa3f4d9e3c8" +uuid = "94ee1d12-ae83-5a48-8b1c-48b8ff168ae0" +version = "0.7.7" + +[[deps.REPL]] +deps = ["InteractiveUtils", "Markdown", "Sockets", "StyledStrings", "Unicode"] +uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" +version = "1.11.0" + +[[deps.Random]] +deps = ["SHA"] +uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +version = "1.11.0" + +[[deps.RangeArrays]] +git-tree-sha1 = "b9039e93773ddcfc828f12aadf7115b4b4d225f5" +uuid = "b3c3ace0-ae52-54e7-9d0b-2c1406fd6b9d" +version = "0.3.2" + +[[deps.Ratios]] +deps = ["Requires"] +git-tree-sha1 = "1342a47bf3260ee108163042310d26f2be5ec90b" +uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439" +version = "0.4.5" +weakdeps = ["FixedPointNumbers"] + + [deps.Ratios.extensions] + RatiosFixedPointNumbersExt = "FixedPointNumbers" + +[[deps.RealDot]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9" +uuid = "c1ae055f-0cd5-4b69-90a6-9a35b1a98df9" +version = "0.1.0" + +[[deps.RecipesBase]] +deps = ["PrecompileTools"] +git-tree-sha1 = "5c3d09cc4f31f5fc6af001c250bf1278733100ff" +uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" +version = "1.3.4" + +[[deps.Reexport]] +git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" +uuid = "189a3867-3050-52da-a836-e630ba90ab69" +version = "1.2.2" + +[[deps.RegionTrees]] +deps = ["LinearAlgebra", "StaticArrays"] +git-tree-sha1 = "dc16a55411988d414054933b3fc02d60ec198e44" +uuid = "dee08c22-ab7f-5625-9660-a9af2021b33f" +version = "0.3.4" + +[[deps.RegistryInstances]] +deps = ["LazilyInitializedFields", "Pkg", "TOML", "Tar"] +git-tree-sha1 = "ffd19052caf598b8653b99404058fce14828be51" +uuid = "2792f1a3-b283-48e8-9a74-f99dce5104f3" +version = "0.1.0" + +[[deps.RelocatableFolders]] +deps = ["SHA", "Scratch"] +git-tree-sha1 = "ffdaf70d81cf6ff22c2b6e733c900c3321cab864" +uuid = "05181044-ff0b-4ac5-8273-598c1e38db00" +version = "1.0.1" + +[[deps.RemoteREPL]] +deps = ["Logging", "OpenSSH_jll", "REPL", "ReplMaker", "Serialization", "Sockets", "UUIDs"] +git-tree-sha1 = "4dc40bec45f3c2dc8648e50438753a6be1b87f40" +uuid = "1bd9f7bb-701c-4338-bec7-ac987af7c555" +version = "0.3.1" + +[[deps.ReplMaker]] +deps = ["REPL", "Unicode"] +git-tree-sha1 = "c080cfd9997a4c0f6e2d7bf6711d0424340180a7" +uuid = "b873ce64-0db9-51f5-a568-4457d8e49576" +version = "0.2.8" + +[[deps.Requires]] +deps = ["UUIDs"] +git-tree-sha1 = "62389eeff14780bfe55195b7204c0d8738436d64" +uuid = "ae029012-a4dd-5104-9daa-d747884805df" +version = "1.3.1" + +[[deps.Revise]] +deps = ["CRC32c", "CodeTracking", "FileWatching", "JuliaInterpreter", "LibGit2", "LoweredCodeUtils", "OrderedCollections", "Preferences", "REPL", "Serialization", "UUIDs"] +git-tree-sha1 = "da47b1bd8be0a3f80073d9b8bf0c614a3c474d58" +uuid = "295af30f-e4ad-537b-8983-00126c2a3abe" +version = "3.18.0" +weakdeps = ["Distributed"] + + [deps.Revise.extensions] + DistributedExt = "Distributed" + +[[deps.Rmath]] +deps = ["Random", "Rmath_jll"] +git-tree-sha1 = "5b3d50eb374cea306873b371d3f8d3915a018f0b" +uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa" +version = "0.9.0" + +[[deps.Rmath_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6d40b2fe70437b01397d2a4d5b020008da4e7019" +uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f" +version = "0.5.2+0" + +[[deps.Roots]] +deps = ["Accessors", "CommonSolve", "Printf"] +git-tree-sha1 = "15f266d7b3039ca0608d2c53bb32225b96932310" +uuid = "f2b01f46-fcfa-551c-844a-d8ac1e96c665" +version = "3.0.14" + + [deps.Roots.extensions] + RootsChainRulesCoreExt = "ChainRulesCore" + RootsForwardDiffExt = "ForwardDiff" + RootsIntervalRootFindingExt = "IntervalRootFinding" + RootsSymPyExt = "SymPy" + RootsSymPyPythonCallExt = "SymPyPythonCall" + RootsUnitfulExt = "Unitful" + + [deps.Roots.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + IntervalRootFinding = "d2bf35a9-74e0-55ec-b149-d360ff49b807" + SymPy = "24249f21-da20-56a4-8eb1-6a02cf4ae2e6" + SymPyPythonCall = "bc8888f7-b21e-4b7c-a06a-5d9c9496438c" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.Rotations]] +deps = ["LinearAlgebra", "Quaternions", "Random", "StaticArrays"] +git-tree-sha1 = "5680a9276685d392c87407df00d57c9924d9f11e" +uuid = "6038ab10-8711-5258-84ad-4b1120ba62dc" +version = "1.7.1" +weakdeps = ["RecipesBase"] + + [deps.Rotations.extensions] + RotationsRecipesBaseExt = "RecipesBase" + +[[deps.RoundingEmulator]] +git-tree-sha1 = "40b9edad2e5287e05bd413a38f61a8ff55b9557b" +uuid = "5eaf0fd0-dfba-4ccb-bf02-d820a40db705" +version = "0.2.1" + +[[deps.SHA]] +uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" +version = "0.7.0" + +[[deps.SIMD]] +deps = ["PrecompileTools"] +git-tree-sha1 = "0651e0ac84b2027c5f227c058d37f81b5be373bd" +uuid = "fdea26ae-647d-5447-a871-4b548cad5224" +version = "3.8.2" + +[[deps.SIMDTypes]] +git-tree-sha1 = "330289636fb8107c5f32088d2741e9fd7a061a5c" +uuid = "94e857df-77ce-4151-89e5-788b33177be4" +version = "0.1.0" + +[[deps.SLEEFPirates]] +deps = ["IfElse", "Static", "VectorizationBase"] +git-tree-sha1 = "72312aa278823c0e99ce31186e22d917d2d11f99" +uuid = "476501e8-09a2-5ece-8869-fb82de89a1fa" +version = "0.6.46" + +[[deps.SavitzkyGolay]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "7bbc5949a42f53f4fca1a0157c72f9d3f78050d1" +uuid = "c4bf5708-b6a6-4fbe-bcd0-6850ed671584" +version = "0.9.1" + +[[deps.SciMLPublic]] +deps = ["PrecompileTools"] +git-tree-sha1 = "74685afb51732a464fbce79a72708f7c4203ceb7" +uuid = "431bcebd-1456-4ced-9d72-93c2757fff0b" +version = "1.3.0" + +[[deps.ScopedValues]] +deps = ["HashArrayMappedTries", "Logging"] +git-tree-sha1 = "67a144433c4ce877ee6d1ada69a124d6b1ecf7be" +uuid = "7e506255-f358-4e82-b7e4-beb19740aa63" +version = "1.6.2" + +[[deps.Scratch]] +deps = ["Dates"] +git-tree-sha1 = "9b81b8393e50b7d4e6d0a9f14e192294d3b7c109" +uuid = "6c6a2e73-6563-6170-7368-637461726353" +version = "1.3.0" + +[[deps.SentinelArrays]] +deps = ["Dates", "Random"] +git-tree-sha1 = "4910c2c2f334d74735b7a8fd02f837ead352576a" +uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" +version = "1.4.11" + +[[deps.Serialization]] +uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" +version = "1.11.0" + +[[deps.Setfield]] +deps = ["ConstructionBase", "Future", "MacroTools", "StaticArraysCore"] +git-tree-sha1 = "89880a2cca5cabc68c9023f58e544beda1d2fc1f" +uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46" +version = "1.2.0" + +[[deps.ShaderAbstractions]] +deps = ["ColorTypes", "FixedPointNumbers", "GeometryBasics", "LinearAlgebra", "Observables", "StaticArrays"] +git-tree-sha1 = "57aa595158717ef165e6f5ab639fe2e3178c0a2b" +uuid = "65257c39-d410-5151-9873-9b3e5be5013e" +version = "0.5.1" + +[[deps.SharedArrays]] +deps = ["Distributed", "Mmap", "Random", "Serialization"] +uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" +version = "1.11.0" + +[[deps.Showoff]] +deps = ["Dates"] +git-tree-sha1 = "8238217340ad0aaabe11afe39c1098b5bc9f4c8e" +uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f" +version = "1.1.1" + +[[deps.SignedDistanceFields]] +deps = ["Statistics"] +git-tree-sha1 = "3949ad92e1c9d2ff0cd4a1317d5ecbba682f4b92" +uuid = "73760f76-fbc4-59ce-8f25-708e95d2df96" +version = "0.4.1" + +[[deps.SimpleBufferStream]] +git-tree-sha1 = "f305871d2f381d21527c770d4788c06c097c9bc1" +uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7" +version = "1.2.0" + +[[deps.SimpleImageMetadata]] +git-tree-sha1 = "ec017517738d90aa43f682cbab22fe74cb156608" +uuid = "67d14529-f57e-4d48-b504-d486213b7963" +version = "0.1.0" + +[[deps.SimpleTraits]] +deps = ["InteractiveUtils", "MacroTools"] +git-tree-sha1 = "7ddb0b49c109481b046972c0e4ab02b2127d6a75" +uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d" +version = "0.9.6" + +[[deps.SimpleWeightedGraphs]] +deps = ["Graphs", "LinearAlgebra", "Markdown", "SparseArrays"] +git-tree-sha1 = "93f0ac4ed92a34bf859f1e64813a9f41925a3447" +uuid = "47aef6b3-ad0c-573a-a1e2-d07658019622" +version = "1.6.0" + +[[deps.Sixel]] +deps = ["Dates", "FileIO", "ImageCore", "IndirectArrays", "OffsetArrays", "REPL", "libsixel_jll"] +git-tree-sha1 = "2c79185e5261b159474903598c571ddd9f12ff7b" +uuid = "45858cf5-a6b0-47a3-bbea-62219f50df47" +version = "0.1.6" + +[[deps.Sockets]] +uuid = "6462fe0b-24de-5631-8697-dd941f90decc" +version = "1.11.0" + +[[deps.SortingAlgorithms]] +deps = ["DataStructures"] +git-tree-sha1 = "13cd91cc9be159e3f4d95b857fa2aa383b53772a" +uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" +version = "1.2.3" + +[[deps.SparseArrays]] +deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] +uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +version = "1.11.0" + +[[deps.SpecialFunctions]] +deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] +git-tree-sha1 = "88ef0d98204515bc53dd4aaea5f7788882d1b66c" +uuid = "276daf66-3868-5448-9aa4-cd146d93841b" +version = "2.9.1" +weakdeps = ["ChainRulesCore"] + + [deps.SpecialFunctions.extensions] + SpecialFunctionsChainRulesCoreExt = "ChainRulesCore" + +[[deps.StackViews]] +deps = ["OffsetArrays"] +git-tree-sha1 = "be1cf4eb0ac528d96f5115b4ed80c26a8d8ae621" +uuid = "cae243ae-269e-4f55-b966-ac2d0dc13c15" +version = "0.1.2" + +[[deps.Static]] +deps = ["CommonWorldInvalidations", "IfElse", "PrecompileTools", "SciMLPublic"] +git-tree-sha1 = "474a5283ad435618090122872eea6a8165ea6bcf" +uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3" +version = "1.4.6" + +[[deps.StaticArrayInterface]] +deps = ["ArrayInterface", "Compat", "IfElse", "LinearAlgebra", "PrecompileTools", "SciMLPublic", "Static"] +git-tree-sha1 = "2a635e15d5035c53b345077c947f31ff91744078" +uuid = "0d7ed370-da01-4f52-bd93-41d350b8b718" +version = "1.10.0" +weakdeps = ["OffsetArrays", "StaticArrays"] + + [deps.StaticArrayInterface.extensions] + StaticArrayInterfaceOffsetArraysExt = "OffsetArrays" + StaticArrayInterfaceStaticArraysExt = "StaticArrays" + +[[deps.StaticArrays]] +deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"] +git-tree-sha1 = "8a8a52f887f38d44014e24ee46b8a7311c625f6d" +uuid = "90137ffa-7385-5640-81b9-e52037218182" +version = "1.9.24" +weakdeps = ["ChainRulesCore", "Statistics"] + + [deps.StaticArrays.extensions] + StaticArraysChainRulesCoreExt = "ChainRulesCore" + StaticArraysStatisticsExt = "Statistics" + +[[deps.StaticArraysCore]] +git-tree-sha1 = "bf7e2d0d9ed9ac2a652fd598c0f784910cc759f2" +uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" +version = "1.4.5" + +[[deps.Statistics]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "e2b53ce13a53367e96601081e33d34746b571bad" +uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" +version = "1.11.5" +weakdeps = ["SparseArrays"] + + [deps.Statistics.extensions] + SparseArraysExt = ["SparseArrays"] + +[[deps.StatsAPI]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "178ed29fd5b2a2cfc3bd31c13375ae925623ff36" +uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" +version = "1.8.0" + +[[deps.StatsBase]] +deps = ["AliasTables", "DataAPI", "DataStructures", "IrrationalConstants", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] +git-tree-sha1 = "adb9da019510162e67a4493fc235c23203d8b09e" +uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" +version = "0.34.13" + +[[deps.StatsFuns]] +deps = ["HypergeometricFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"] +git-tree-sha1 = "0aa97471d55945556e8d2859568b8317cef98351" +uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c" +version = "1.5.3" +weakdeps = ["ChainRulesCore", "InverseFunctions"] + + [deps.StatsFuns.extensions] + StatsFunsChainRulesCoreExt = "ChainRulesCore" + StatsFunsInverseFunctionsExt = "InverseFunctions" + +[[deps.Stipple]] +deps = ["Dates", "FilePathsBase", "Genie", "GenieSession", "GenieSessionFileSession", "JSON3", "Logging", "MacroTools", "Mixers", "Observables", "OrderedCollections", "Parameters", "Pkg", "PrecompileTools", "Random", "Reexport", "Requires", "StructTypes", "Tables"] +git-tree-sha1 = "9455fc54d50b4a6e6cb986eda7e8a0d09938ba06" +uuid = "4acbeb90-81a0-11ea-1966-bdaff8155998" +version = "0.28.23" +weakdeps = ["DataFrames", "JSON", "OffsetArrays"] + + [deps.Stipple.extensions] + StippleDataFramesExt = "DataFrames" + StippleJSONExt = "JSON" + StippleOffsetArraysExt = "OffsetArrays" + +[[deps.StipplePivotTable]] +deps = ["Stipple", "StippleUI", "Tables"] +git-tree-sha1 = "98d96b177125630eb5d273b3e705aec22bb4ec86" +uuid = "adab0226-ee3c-44de-8f2f-393b1bf1e936" +version = "0.4.3" + +[[deps.StipplePlotly]] +deps = ["DataFrames", "Genie", "Requires", "Stipple"] +git-tree-sha1 = "05cc51d2268f430b0f8dada1ccc330d1a9d20c3f" +uuid = "ec984513-233d-481d-95b0-a3b58b97af2b" +version = "0.13.16" +weakdeps = ["PlotlyBase"] + + [deps.StipplePlotly.extensions] + StipplePlotlyPlotlyBaseExt = "PlotlyBase" + +[[deps.StippleTable]] +deps = ["Stipple", "StippleUI"] +git-tree-sha1 = "00f81f719413a6cd232888adab4b1c9610412d3c" +uuid = "5bb4b094-0818-496d-ae94-fd777e10e8ba" +version = "1.1.0" + +[[deps.StippleTabs]] +deps = ["Stipple", "StippleUI"] +git-tree-sha1 = "b50f0b38163bb240489e20dfd15a96d506719fcd" +uuid = "29f11006-3202-4091-a17b-0a26282d76dd" +version = "1.2.0" + +[[deps.StippleUI]] +deps = ["Colors", "Dates", "Genie", "OrderedCollections", "PrecompileTools", "Stipple", "Tables"] +git-tree-sha1 = "fb442128bab27a90c9356f9e5ed39dada2b3d207" +uuid = "a3c5d34a-b254-4859-a8fa-b86abb7e84a3" +version = "0.23.7" +weakdeps = ["DataFrames"] + + [deps.StippleUI.extensions] + StippleUIDataFramesExt = "DataFrames" + +[[deps.StringEncodings]] +deps = ["Libiconv_jll"] +git-tree-sha1 = "b765e46ba27ecf6b44faf70df40c57aa3a547dcb" +uuid = "69024149-9ee7-55f6-a4c4-859efe599b68" +version = "0.3.7" + +[[deps.StringManipulation]] +deps = ["PrecompileTools", "StyledStrings"] +git-tree-sha1 = "9e3a02d73a8f0a9be04e677dbef758aab40f8bea" +uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e" +version = "0.6.1" + +[[deps.StructArrays]] +deps = ["ConstructionBase", "DataAPI", "Tables"] +git-tree-sha1 = "4daaddbe37aa80b4551bf7c56adf53e7cfcdf35a" +uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" +version = "0.7.4" + + [deps.StructArrays.extensions] + AdaptExt = "Adapt" + GPUArraysCoreExt = "GPUArraysCore" + KernelAbstractionsExt = "KernelAbstractions" + LinearAlgebraExt = "LinearAlgebra" + SparseArraysExt = "SparseArrays" + StaticArraysExt = "StaticArrays" + + [deps.StructArrays.weakdeps] + Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" + GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" + KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + +[[deps.StructTypes]] +deps = ["Dates", "UUIDs"] +git-tree-sha1 = "fd6a55e88450cb4256e49103a5a243f065c7b781" +uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" +version = "1.11.1" + +[[deps.StyledStrings]] +uuid = "f489334b-da3d-4c2e-b8f0-e476e12c162b" +version = "1.11.0" + +[[deps.SuiteSparse]] +deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"] +uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" + +[[deps.SuiteSparse_jll]] +deps = ["Artifacts", "Libdl", "libblastrampoline_jll"] +uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" +version = "7.7.0+0" + +[[deps.TOML]] +deps = ["Dates"] +uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" +version = "1.0.3" + +[[deps.TableTraits]] +deps = ["IteratorInterfaceExtensions"] +git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" +uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" +version = "1.0.1" + +[[deps.Tables]] +deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "OrderedCollections", "TableTraits"] +git-tree-sha1 = "a94d9bdda1b7bed0046cea645639ab3f62196fac" +uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" +version = "1.14.0" + +[[deps.Tar]] +deps = ["ArgTools", "SHA"] +uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" +version = "1.10.0" + +[[deps.TensorCore]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" +uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" +version = "0.1.1" + +[[deps.Test]] +deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] +uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" +version = "1.11.0" + +[[deps.TextWrap]] +git-tree-sha1 = "43044b737fa70bc12f6105061d3da38f881a3e3c" +uuid = "b718987f-49a8-5099-9789-dcd902bef87d" +version = "1.0.2" + +[[deps.ThreadingUtilities]] +deps = ["ManualMemory"] +git-tree-sha1 = "e12924c87b5476110130841e973ba9b9f20ae599" +uuid = "8290d209-cae3-49c0-8002-c8c24d57dab5" +version = "0.5.7" + +[[deps.TiffImages]] +deps = ["CodecZstd", "ColorTypes", "DataStructures", "DocStringExtensions", "FileIO", "FixedPointNumbers", "IndirectArrays", "Inflate", "Mmap", "OffsetArrays", "PkgVersion", "PrecompileTools", "ProgressMeter", "SIMD", "UUIDs"] +git-tree-sha1 = "9ca5f1f2d42f80df4b8c9f6ab5a64f438bbd9976" +uuid = "731e570b-9d59-4bfa-96dc-6df516fadf69" +version = "0.11.9" + +[[deps.TiledIteration]] +deps = ["OffsetArrays", "StaticArrayInterface"] +git-tree-sha1 = "1176cc31e867217b06928e2f140c90bd1bc88283" +uuid = "06e1c1a7-607b-532d-9fad-de7d9aa2abac" +version = "0.5.0" + +[[deps.TranscodingStreams]] +git-tree-sha1 = "0c45878dcfdcfa8480052b6ab162cdd138781742" +uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" +version = "0.11.3" + +[[deps.TriplotBase]] +git-tree-sha1 = "4d4ed7f294cda19382ff7de4c137d24d16adc89b" +uuid = "981d1d27-644d-49a2-9326-4793e63143c3" +version = "0.1.0" + +[[deps.URIParser]] +deps = ["Unicode"] +git-tree-sha1 = "53a9f49546b8d2dd2e688d216421d050c9a31d0d" +uuid = "30578b45-9adc-5946-b283-645ec420af67" +version = "0.4.1" + +[[deps.URIs]] +deps = ["Serialization"] +git-tree-sha1 = "eb3b85ca904a1d1647b15acc091b113b8874b648" +uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" +version = "1.7.3" + +[[deps.UUIDs]] +deps = ["Random", "SHA"] +uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" +version = "1.11.0" + +[[deps.UnPack]] +git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b" +uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" +version = "1.0.2" + +[[deps.Unicode]] +uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" +version = "1.11.0" + +[[deps.UnicodeFun]] +deps = ["REPL"] +git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf" +uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1" +version = "0.4.1" + +[[deps.Unitful]] +deps = ["Dates", "LinearAlgebra", "Random"] +git-tree-sha1 = "1f0f9f401753701a7e4113b5056ca38d33875b55" +uuid = "1986cc42-f94f-5a68-af5c-568840ba703d" +version = "1.29.0" + + [deps.Unitful.extensions] + ConstructionBaseUnitfulExt = "ConstructionBase" + ForwardDiffExt = "ForwardDiff" + InverseFunctionsUnitfulExt = "InverseFunctions" + LatexifyExt = ["Latexify", "LaTeXStrings"] + NaNMathExt = "NaNMath" + PrintfExt = "Printf" + + [deps.Unitful.weakdeps] + ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" + Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" + NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" + Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" + +[[deps.VectorizationBase]] +deps = ["ArrayInterface", "CPUSummary", "HostCPUFeatures", "IfElse", "LayoutPointers", "Libdl", "LinearAlgebra", "SIMDTypes", "Static", "StaticArrayInterface"] +git-tree-sha1 = "807a234dc5e6132dd6cf4c9317ca0917c4001ab3" +uuid = "3d5dd08c-fd9d-11e8-17fa-ed2836048c2f" +version = "0.21.74" + +[[deps.Wavelets]] +deps = ["DSP", "LinearAlgebra", "Reexport", "SpecialFunctions", "Statistics"] +git-tree-sha1 = "e50c5e157177002ebe6bd921596db92ae9e0c73b" +uuid = "29a6e085-ba6d-5f35-a997-948ac2efa89a" +version = "0.10.2" + + [deps.Wavelets.extensions] + WaveletsGPUExt = ["GPUArrays", "KernelAbstractions"] + + [deps.Wavelets.weakdeps] + GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7" + KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" + +[[deps.Wayland_jll]] +deps = ["Artifacts", "EpollShim_jll", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll"] +git-tree-sha1 = "96478df35bbc2f3e1e791bc7a3d0eeee559e60e9" +uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89" +version = "1.24.0+0" + +[[deps.WeakRefStrings]] +deps = ["DataAPI", "InlineStrings", "Parsers"] +git-tree-sha1 = "0716e01c3b40413de5dedbc9c5c69f27cddfddfc" +uuid = "ea10d353-3f73-51f8-a26c-33c1cb351aa5" +version = "1.4.3" + +[[deps.WebP]] +deps = ["CEnum", "ColorTypes", "FileIO", "FixedPointNumbers", "ImageCore", "libwebp_jll"] +git-tree-sha1 = "aa1ca3c47f119fbdae8770c29820e5e6119b83f2" +uuid = "e3aaa7dc-3e4b-44e0-be63-ffb868ccd7c1" +version = "0.1.3" + +[[deps.WoodburyMatrices]] +deps = ["LinearAlgebra", "SparseArrays"] +git-tree-sha1 = "248a7031b3da79a127f14e5dc5f417e26f9f6db7" +uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6" +version = "1.1.0" + +[[deps.WorkerUtilities]] +git-tree-sha1 = "cd1659ba0d57b71a464a29e64dbc67cfe83d54e7" +uuid = "76eceee3-57b5-4d4a-8e66-0e911cebbf60" +version = "1.6.1" + +[[deps.XML2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"] +git-tree-sha1 = "80d3930c6347cfce7ccf96bd3bafdf079d9c0390" +uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" +version = "2.13.9+0" + +[[deps.XZ_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e52eca002a11c30a858185efdfb15311e1c7a6bf" +uuid = "ffd25f8a-64ca-5728-b0f7-c24cf3aae800" +version = "5.8.4+0" + +[[deps.Xorg_libX11_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll", "Xorg_xtrans_jll"] +git-tree-sha1 = "ce91b54a5f90c4f27df6950706234b34e49cf79e" +uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc" +version = "1.8.14+0" + +[[deps.Xorg_libXau_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "aa1261ebbac3ccc8d16558ae6799524c450ed16b" +uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec" +version = "1.0.13+0" + +[[deps.Xorg_libXcomposite_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXfixes_jll"] +git-tree-sha1 = "025180ce2163cdd71ba6e5a227bd06cf203b559c" +uuid = "3c9796d7-64a0-5134-86ad-79f8eb684845" +version = "0.4.7+0" + +[[deps.Xorg_libXcursor_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"] +git-tree-sha1 = "6c74ca84bbabc18c4547014765d194ff0b4dc9da" +uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724" +version = "1.2.4+0" + +[[deps.Xorg_libXdamage_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXfixes_jll"] +git-tree-sha1 = "45917154defafcbff585d6c04f323b5797da1ecf" +uuid = "0aeada51-83db-5f97-b67e-184615cfc6f6" +version = "1.1.7+0" + +[[deps.Xorg_libXdmcp_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "52858d64353db33a56e13c341d7bf44cd0d7b309" +uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05" +version = "1.1.6+0" + +[[deps.Xorg_libXext_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "1a4a26870bf1e5d26cd585e38038d399d7e65706" +uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3" +version = "1.3.8+0" + +[[deps.Xorg_libXfixes_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "75e00946e43621e09d431d9b95818ee751e6b2ef" +uuid = "d091e8ba-531a-589c-9de9-94069b037ed8" +version = "6.0.2+0" + +[[deps.Xorg_libXi_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll", "Xorg_libXfixes_jll"] +git-tree-sha1 = "704274ca960c42049fd9bda089fc4be32af5cdca" +uuid = "a51aa0fd-4e3c-5386-b890-e753decda492" +version = "1.8.5+0" + +[[deps.Xorg_libXinerama_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll"] +git-tree-sha1 = "0ba01bc7396896a4ace8aab67db31403c71628f4" +uuid = "d1454406-59df-5ea1-beac-c340f2130bc3" +version = "1.1.7+0" + +[[deps.Xorg_libXrandr_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll", "Xorg_libXrender_jll"] +git-tree-sha1 = "6c174ef70c96c76f4c3f4d3cfbe09d018bcd1b53" +uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484" +version = "1.5.6+0" + +[[deps.Xorg_libXrender_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "a54cf54677c9f6eac0d97e9d757c233b56bc21b9" +uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa" +version = "0.9.13+0" + +[[deps.Xorg_libXtst_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXext_jll", "Xorg_libXfixes_jll", "Xorg_libXi_jll"] +git-tree-sha1 = "f99e310334c5825925d569083dd6da01aa1338c8" +uuid = "b6f176f1-7aea-5357-ad67-1d3e565ea1c6" +version = "1.2.6+0" + +[[deps.Xorg_libxcb_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libXau_jll", "Xorg_libXdmcp_jll"] +git-tree-sha1 = "bfcaf7ec088eaba362093393fe11aa141fa15422" +uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b" +version = "1.17.1+0" + +[[deps.Xorg_libxkbfile_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libX11_jll"] +git-tree-sha1 = "ed756a03e95fff88d8f738ebc2849431bdd4fd1a" +uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a" +version = "1.2.0+0" + +[[deps.Xorg_xkbcomp_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxkbfile_jll"] +git-tree-sha1 = "9a5e6e8f1a7c40941465c04840145e527f0d6b4b" +uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4" +version = "1.5.0+0" + +[[deps.Xorg_xkeyboard_config_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_xkbcomp_jll"] +git-tree-sha1 = "df77b22eb77051b3d0ef30aab979684f7482c66f" +uuid = "33bec58e-1273-512f-9401-5d533626f822" +version = "2.48.0+0" + +[[deps.Xorg_xtrans_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "a63799ff68005991f9d9491b6e95bd3478d783cb" +uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10" +version = "1.6.0+0" + +[[deps.YAML]] +deps = ["Base64", "Dates", "Printf", "StringEncodings"] +git-tree-sha1 = "9c685a6e94e255019e2bf9486318147cd42fe34a" +uuid = "ddb6d928-2868-570f-bddf-ab3f9cf99eb6" +version = "0.4.17" + +[[deps.Zlib_jll]] +deps = ["Libdl"] +uuid = "83775a58-1f1d-513f-b197-d71354ab007a" +version = "1.2.13+1" + +[[deps.Zstd_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "446b23e73536f84e8037f5dce465e92275f6a308" +uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" +version = "1.5.7+1" + +[[deps.at_spi2_atk_jll]] +deps = ["ATK_jll", "Artifacts", "JLLWrappers", "Libdl", "XML2_jll", "Xorg_libX11_jll", "at_spi2_core_jll"] +git-tree-sha1 = "249ab7c4da34d86d3d66b524705b1c07fe96b815" +uuid = "de012916-1e3f-58c2-8f29-df3ef51d412d" +version = "2.38.0+0" + +[[deps.at_spi2_core_jll]] +deps = ["Artifacts", "Dbus_jll", "Glib_jll", "JLLWrappers", "Libdl", "Xorg_libXtst_jll"] +git-tree-sha1 = "72357d5b7866595601cb78528221c9ec6ab7e4ce" +uuid = "0fc3237b-ac94-5853-b45c-d43d59a06200" +version = "2.60.6+0" + +[[deps.gdk_pixbuf_jll]] +deps = ["Artifacts", "Glib_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Xorg_libX11_jll", "libpng_jll"] +git-tree-sha1 = "54fdde8cc7d9350412f75aaa98b1d57f9d4efca2" +uuid = "da03df04-f53b-5353-a52f-6a8b0620ced0" +version = "2.44.8+0" + +[[deps.iso_codes_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "ceb470fa62d88b32ee747929e19e16d5d75dc556" +uuid = "bf975903-5238-5d20-8243-bc370bc1e7e5" +version = "4.20.1+1" + +[[deps.isoband_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "51b5eeb3f98367157a7a12a1fb0aa5328946c03c" +uuid = "9a68df92-36a6-505f-a73e-abb412b6bfb4" +version = "0.2.3+0" + +[[deps.libaom_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "21e05cef1411bfe6b22a1ca8cbdc64a297d4b447" +uuid = "a4ae2306-e953-59d6-aa16-d00cac43593b" +version = "3.15.3+0" + +[[deps.libass_jll]] +deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "cb007192783c56d8249db4cf0e3495001edfe414" +uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0" +version = "0.17.5+0" + +[[deps.libblastrampoline_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" +version = "5.11.0+0" + +[[deps.libdeflate_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "11c07205bc3b3b7833b8fb36beb4e4764d0126a7" +uuid = "46979653-d7f6-5232-b59e-dd310c4598de" +version = "1.26.0+1" + +[[deps.libfdk_aac_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "646634dd19587a56ee2f1199563ec056c5f228df" +uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280" +version = "2.0.4+0" + +[[deps.libpng_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "1fcd6cf05d23adab0b5ffc496d020537215751dc" +uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f" +version = "1.6.59+1" + +[[deps.libsixel_jll]] +deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "libpng_jll"] +git-tree-sha1 = "e067c8bae65bb40866552296a2d5b4dc65b8928f" +uuid = "075b6546-f08a-558a-be8f-8157d0f608a5" +version = "1.80.702+0" + +[[deps.libvorbis_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll"] +git-tree-sha1 = "11e1772e7f3cc987e9d3de991dd4f6b2602663a5" +uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a" +version = "1.3.8+0" + +[[deps.libwebp_jll]] +deps = ["Artifacts", "Giflib_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libglvnd_jll", "Libtiff_jll", "libpng_jll"] +git-tree-sha1 = "52d3b9475133c3bc8c0a7f90f18bfc8cdb5a443a" +uuid = "c5f90fcd-3b7e-5836-afba-fc50a0988cb2" +version = "1.6.1+0" + +[[deps.libzip_jll]] +deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "OpenSSL_jll", "XZ_jll", "Zlib_jll", "Zstd_jll"] +git-tree-sha1 = "c4b294e893e8ebbb8788b68b1d56737c0f01557b" +uuid = "337d8026-41b4-5cde-a456-74a10e5b31d1" +version = "1.12.1+0" + +[[deps.nghttp2_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" +version = "1.59.0+0" + +[[deps.oneTBB_jll]] +deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl"] +git-tree-sha1 = "ed2d8d4ad96c03d3abe3382cdbbdea9489b63636" +uuid = "1317d2d5-d96f-522e-a858-c73665f53c3e" +version = "2023.1.0+0" + +[[deps.p7zip_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" +version = "17.4.0+2" + +[[deps.x264_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "14cc7083fc6dff3cc44f2bc435ee96d06ed79aa7" +uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a" +version = "10164.0.1+0" + +[[deps.x265_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "e7b67590c14d487e734dcb925924c5dc43ec85f3" +uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76" +version = "4.1.0+0" + +[[deps.xkbcommon_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"] +git-tree-sha1 = "a1fc6507a40bf504527d0d4067d718f8e179b2b8" +uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd" +version = "1.13.0+0" diff --git a/Project.toml b/Project.toml new file mode 100644 index 0000000..77fe104 --- /dev/null +++ b/Project.toml @@ -0,0 +1,34 @@ +name = "JuliaMSI_MCP" +uuid = "146f587d-e8c9-4fce-8feb-186b5b7e0eb5" +authors = ["JuliaMSI"] +version = "0.1.0" + +[deps] +CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" +DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" +JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" +ModelContextProtocol = "c58f755f-f2a7-4f48-bf29-4e9659b78499" +MSI_src = "8f395f85-3b9c-4f7f-bf7e-12345678abcd" +Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +SHA = "ea8e919c-243c-51af-8825-aaa63cd721ce" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" +UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" + +[sources] +MSI_src = {path = "../JuliaMSI"} + +[compat] +CSV = "0.10" +DataFrames = "1.7" +JSON3 = "1" +ModelContextProtocol = "0.6" +MSI_src = "0.1" +julia = "1.11" + +[extras] +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[targets] +test = ["Test"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..5683705 --- /dev/null +++ b/README.md @@ -0,0 +1,557 @@ +# JuliaMSI_MCP + +Servidor [Model Context Protocol](https://modelcontextprotocol.io) (MCP) para el motor de +**Mass Spectrometry Imaging** [JuliaMSI](../JuliaMSI). Expone la sesión persistente, la +extracción de imágenes iónicas, el pipeline de preprocesamiento streaming y el acceso +aleatorio a espectros como herramientas que un LLM (Claude Desktop, VS Code/Copilot, +OpenCode, etc.) puede invocar de forma reproducible. + +> Estado: **Fase 1–3 del plan implementadas y probadas** (sesión persistente, capa de +> planificación + ejecución asíncrona, catálogo completo de tools/resources/prompts). +> La Fase 4 (Streamable HTTP + resiliencia de memoria) también está integrada; falta +> endurecer autenticación y empaquetado AOT para producción. + +--- + +## 1. Arquitectura + +``` +┌───────────────────────────────────────────────────────────────────────────┐ +│ Cliente LLM (host MCP) │ +│ Claude Desktop · VS Code · OpenCode · Cursor │ +└───────────────────────────────────┬───────────────────────────────────────┘ + │ JSON-RPC 2.0 (stdio o Streamable HTTP) +┌───────────────────────────────────▼───────────────────────────────────────┐ +│ Servidor MCP — JuliaMSI_MCP │ +│ │ +│ SessionState (Ref lógica) RunSpec registry Task registry │ +│ ─ MSIData persistente ─ hash de contenido ─ Threads.@spawn │ +│ ─ lock + dataset_id ─ validación ─ polling/cancel │ +│ │ +│ Tools síncronas · Tools de planificación · Tools de ejecución │ +│ Resources msi:// · Prompts de flujo │ +└───────────────────────────────────┬───────────────────────────────────────┘ + │ llamadas directas en proceso (sin IPC) +┌───────────────────────────────────▼───────────────────────────────────────┐ +│ Motor JuliaMSI (src/ de JuliaMSI) │ +│ imzML + .cache binaria · mmap + madvise · Bloom filters · LRU │ +│ get_mz_slice · get_multiple_mz_slices · process_dataset! │ +└───────────────────────────────────────────────────────────────────────────┘ +``` + +### Las cuatro capas + +| Capa | Archivo | Responsabilidad | +|------|---------|-----------------| +| **Sesión** | `src/session.jl` | Abrir/cerrar `MSIData`, conservarlo entre llamadas, calcular `dataset_id`, liberar memoria al SO (`GC.gc(true)` + `malloc_trim`). | +| **Planificación** | `src/runspec.jl` | Validar parámetros y crear un `RunSpec` inmutable con hash SHA-256 determinista, ligado al `dataset_id`. No ejecuta cómputo. | +| **Ejecución** | `src/tasks.jl` | Lanzar el RunSpec en una `Threads.@spawn`, registrar estado/progreso, cancelación cooperativa, polling y resultados. | +| **Artefactos** | `src/artifacts.jl` | Las matrices completas van a disco (CSV, PGM, Matrix Market); al LLM se le devuelven estadísticas y un *preview* downsampleado. | + +### Decisiones de diseño relevantes + +- **`stdout` limpio para stdio.** El motor JuliaMSI imprime trazas de depuración con + `println`; el servidor redirige el `stdout` global a `stderr` y entrega al transporte + el handle original de `stdout` (`install_output_guard`). Así el canal JSON-RPC nunca + se corrompe. +- **Un dataset a la vez.** Es el modelo natural de `MSIData`; abrir otro cierra y limpia + el anterior. Los planes quedan ligados al `dataset_id` y se rechazan si el dataset + cambió. +- **Planificar ≠ ejecutar.** El LLM recibe un `runspec_id` auditable; reejecutar el mismo + plan reutiliza la tarea existente salvo `force=true`. +- **Resultados acotados.** Una matriz 2000×2000 en JSON son ~32 MB. Por eso el resultado + incluye `stats`, `preview` (≤256 px) y rutas a artefactos; `include_matrix` es opt-in y + tiene topes de tamaño. +- **Memoria.** `msi_close_dataset` y las tareas de streaming/analytics ejecutan + `GC.gc(true/false)` + `malloc_trim(0)` en Linux para devolver arenas de glibc al kernel. + +--- + +## 2. Requisitos + +- Julia **1.11+** (probado con 1.11.7). +- Un checkout del motor JuliaMSI con su `Project.toml` (por defecto `../JuliaMSI`). +- Dependencias de JuliaMSI ya instaladas (el proyecto las resuelve vía `Pkg`). + +La integración usa una dependencia de ruta (`[sources] MSI_src = {path = "../JuliaMSI"}`), +así que **no se copia** el código del motor: los cambios en JuliaMSI se reflejan al +reiniciar el servidor. + +--- + +## 3. Instalación + +```bash +cd /home/pixel/Documents/2026/JuliaMSI_MCP + +# Opción A: layout hermano por defecto (../JuliaMSI) +julia --project=. scripts/setup.jl + +# Opción B: ruta explícita al checkout del motor +JULIA_MSI_PATH=/ruta/a/JuliaMSI julia --project=. scripts/setup.jl +``` + +`scripts/setup.jl` hace `Pkg.develop(path=...)`, `instantiate` y `precompile`. + +### Proyecto autocontenido (opcional) + +La integración usa el checkout local del motor (`../JuliaMSI`) para que los cambios en +JuliaMSI se reflejen sin duplicar 10 000 líneas. Si necesitas distribuir el servidor sin +el resto del repo del motor: + +```bash +mkdir -p vendor/JuliaMSI +cp -r ../JuliaMSI/src ../JuliaMSI/Project.toml vendor/JuliaMSI/ +# edita [sources] en Project.toml: +# MSI_src = {path = "vendor/JuliaMSI"} +julia --project=. -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()' +``` + +También puedes apuntar a cualquiera de los remotos del motor con +`Pkg.add(url="https://github.com/Pixelguy14/Julia_msi_GUI")` (o el mirror de Codeberg) y +usar el nombre `MSI_src` en `[deps]`, aunque la dependencia de ruta es la más cómoda +durante el desarrollo. + +### Parches recomendados para JuliaMSI + +Durante la validación (incluidos datasets reales) se encontraron tres bugs del motor. +Los parches están en `patches/` y **ya están aplicados** al checkout local `../JuliaMSI`: + +1. **`juliamsi-fix-nonmmap.patch`** — lectura sin mmap: + - `load_imzml_lazy` creaba un `MSIData` temporal para escribir la caché compartiendo + el vector de handles reales; su finalizador cerraba los handles del dataset + (`Bad file descriptor`). Ahora el objeto temporal usa `IO[]`. + - `_iterate_uncompressed_fast` leía en buffers `Vector{Float64}` aunque el `.ibd` + fuera Float32, consumiendo el doble de bytes. Ahora usa el tipo real de la fuente. +2. **`juliamsi-fix-mask-io.patch`** — máscaras ROI: + - `load_and_prepare_mask` llamaba `Gray.(img)` y fallaba con TIFF que cargan como + `TiffImages.WidePixel` (p. ej. la imagen óptica de referencia del dataset HR2MSI). + Ahora usa el canal de color embebido. + - `process_image_pipeline` creaba un elemento estructurante par con el valor por + defecto `smoothing=2`, que ImageMorphology rechaza + (`connectivity must be odd-sized`). Ahora normaliza a un tamaño impar ≥ 3. + +**Estado upstream (nov 2026):** las tres correcciones ya están integradas en el commit +`bc71b9c` del motor, presente en la rama `rel/Windows_Mac_Recompatibility` (Codeberg, +GitHub y nube-gran) y en `main` de **GitHub**. `main` de **Codeberg** y de **nube-gran** +todavía no las incluye, así que los parches siguen siendo útiles como respaldo para +quien clone esas ramas por defecto: + +```bash +cd /ruta/a/JuliaMSI +git apply /home/pixel/Documents/2026/JuliaMSI_MCP/patches/juliamsi-fix-nonmmap.patch +git apply /home/pixel/Documents/2026/JuliaMSI_MCP/patches/juliamsi-fix-mask-io.patch +``` + +Recomendación: fusionar `rel/Windows_Mac_Recompatibility` en `main` en Codeberg y +nube-gran para poder eliminar la carpeta `patches/`. La ruta con mmap (por defecto) no +se ve afectada por el primer parche. + +Verificación rápida: + +```bash +julia --project=. -e 'using JuliaMSI_MCP; println(JuliaMSI_MCP.SERVER_VERSION)' +``` + +--- + +## 4. Ejecución + +### stdio (recomendado para escritorio) + +```bash +julia --project=. --threads=auto bin/run_server.jl +``` + +`--threads=auto` es importante: el motor paraleliza espectros y el servidor lanza tareas +en segundo plano. + +### Streamable HTTP + +```bash +julia --project=. --threads=auto bin/run_server.jl --http --host 127.0.0.1 --port 3000 +``` + +Por defecto escucha solo en localhost sin autenticación. Para proteger el endpoint se +puede exigir un token compartido: + +```bash +julia --project=. --threads=auto bin/run_server.jl --http --port 3000 --token S3CR3T +# o bien: JULIA_MSI_MCP_TOKEN=S3CR3T ... --http +``` + +Los clientes deben enviar `Authorization: Bearer S3CR3T`. Para exponerlo fuera de la +máquina, pon un reverse proxy con TLS delante (el token compartido **no** sustituye a TLS). + +### Arranque rápido con sysimage (AOT, Fase 4) + +Para eliminar el JIT de la primera llamada, compila una imagen de sistema: + +```bash +julia scripts/build_sysimage.jl # genera build/sys_mcp.so +julia --project=. --threads=auto --sysimage=build/sys_mcp.so bin/run_server.jl +``` + +`scripts/build_sysimage.jl` crea un entorno desechable, desarrolla el motor y +`JuliaMSI_MCP`, y ejecuta `scripts/sysimage_warmup.jl` (apertura, espectro, slices, +streaming y registro de tools) para precargar el código nativo. La construcción tarda +varios minutos y el `.so` es específico de la máquina. + +### Configuración de clientes (cópialas a la ubicación que espera cada cliente): + +- `config/claude_desktop_config.json` → Claude Desktop (`mcpServers`). En Linux: + `~/.config/Claude/claude_desktop_config.json`; en Windows: + `%APPDATA%\Claude\claude_desktop_config.json`. +- `config/vscode_mcp.json` → VS Code / Copilot. Cópialo como `.vscode/mcp.json` en el + workspace (o ejecuta *MCP: Add Server*). +- `config/opencode.json` → OpenCode V2 (clave `mcp.servers`). Cópialo como + `opencode.json` en la raíz del proyecto, o fusiónalo con + `~/.config/opencode/opencode.json` para uso global. + +Todas asumen este layout: + +``` +julia --project=/home/pixel/Documents/2026/JuliaMSI_MCP --threads=auto \ + /home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl +``` + +Variables de entorno útiles: + +| Variable | Efecto | +|----------|--------| +| `JULIA_NUM_THREADS=auto` | Hilos del motor (también `--threads=auto`). | +| `JULIA_MSI_MCP_ARTIFACTS=/ruta` | Directorio de artefactos (por defecto `/artifacts`). | +| `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` | Días de vida de los artefactos antes de podarlos al arrancar (default 7). | +| `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` | Presupuesto total de artefactos en bytes (default 0 = sin límite). | +| `JULIA_MSI_MCP_TOKEN` | Token compartido para `--http` (equivale a `--token`). | +| `JULIA_MSI_MCP_KEEP_STDOUT=1` | Desactiva la redirección de `stdout` (solo para depurar en local). | + +--- + +## 5. Catálogo de herramientas + +### Sesión y datos + +| Tool | Tipo | Descripción | +|------|------|-------------| +| `msi_open_dataset` | síncrona | Abre/cambia dataset imzML/mzML; crea o usa `.cache`; opcional `precompute_analytics`. | +| `msi_close_dataset` | síncrona | Cierra handles, vacía caché y devuelve RAM al SO. | +| `msi_dataset_info` | síncrona | Estado de la sesión (dimensiones, rango m/z, mmap, RSS, hilos). | +| `msi_get_dataset_stats` | síncrona | Estadísticas por espectro (TIC/BPI/NumPoints/rango m/z). | + +### Espectros + +| Tool | Tipo | Descripción | +|------|------|-------------| +| `msi_get_spectrum_at_coord` | síncrona | Espectro en `(x, y)` con caché LRU. `representation=peaks` o `profile`. | +| `msi_get_spectrum_by_index` | síncrona | Espectro por índice lineal (útil para mzML no-imaging). | + +### Imágenes iónicas + +| Tool | Tipo | Descripción | +|------|------|-------------| +| `msi_get_mz_slice` | síncrona | Imagen iónica inmediata para una masa. | +| `msi_get_multiple_mz_slices` | síncrona | Hasta 50 masas en una sola pasada (inversión de jerarquía). | +| `msi_plan_ion_image` | planificación | Valida y genera `runspec_id` para una masa. | +| `msi_plan_multiple_slices` | planificación | Genera `runspec_id` para un panel de hasta 5000 masas (1 pasada I/O). | + +### Preprocesamiento y analíticas + +| Tool | Tipo | Descripción | +|------|------|-------------| +| `msi_plan_preprocessing` | planificación | Pipeline streaming (`process_dataset!`) → matriz dispersa. | +| `msi_plan_streaming_pipeline` | planificación | Alias del anterior. | +| `msi_plan_analytics` | planificación | Escaneo TIC/BPI/Bloom filters en segundo plano. | + +### Ejecución asíncrona + +| Tool | Tipo | Descripción | +|------|------|-------------| +| `msi_execute_runspec` | ejecución | Lanza el plan en background y devuelve `task_id` (reutiliza tareas salvo `force`). | +| `msi_get_task_status` | síncrona | Estado, progreso, tiempos y resumen. | +| `msi_get_task_result` | síncrona | Resultado completo (stats, preview, artefactos, matrices opt-in). | +| `msi_cancel_task` | síncrona | Cancelación cooperativa. | +| `msi_list_tasks` | síncrona | Lista tareas recientes (filtro por estado). | +| `msi_list_plans` | síncrona | Lista RunSpecs recientes. | + +### Mantenimiento + +| Tool | Tipo | Descripción | +|------|------|-------------| +| `msi_clean_artifacts` | síncrona | Poda artefactos por antigüedad y/o presupuesto de bytes (con `dry_run`). | + +### Resources + +| URI | Contenido | +|-----|-----------| +| `msi://dataset/metadata` | Metadatos de la sesión activa. | +| `msi://dataset/stats` | Agregados + primeras 100 filas (no dispara el escaneo). | +| `msi://tasks/{task_id}/status` | Estado de una tarea. | +| `msi://tasks/{task_id}/result` | Resultado de una tarea. | + +### Prompts + +| Prompt | Uso | +|--------|-----| +| `analyze_region_of_interest` | Forces confirmation of mass, tolerance and mask before planning. | +| `standard_pipeline` | Open → plan → execute → poll → summarize workflow. | +| `diagnose_task` | Interprets task states/errors and proposes corrective actions. | + +> Los prompts y su contenido están en inglés (el idioma principal del proyecto). Nombres +> anteriores del compendio: `analizar_region_de_interes`, `pipeline_estandar`, +> `diagnostico_de_tarea`. + +--- + +## 6. Flujo típico (lo que hace el LLM) + +```text +msi_open_dataset(file_path="/datos/muestra.imzML", precompute_analytics=false) + │ + ├─(dataset grande)─► msi_plan_analytics ─► msi_execute_runspec ─► poll + │ +msi_plan_ion_image(mass=756.55, tolerance=0.1, mask_path="/datos/roi.png") + │ → {"runspec_id": "a1b2…", "kind": "ion_image", …} + ▼ +msi_execute_runspec(runspec_id="a1b2…", wait_seconds=0) + │ → {"task_id": "uuid", "status": "queued"} + ▼ +msi_get_task_status(task_id="uuid") # repetir hasta completed + ▼ +msi_get_task_result(task_id="uuid") + │ → stats, preview, artifacts.csv/pgm + ▼ +msi_close_dataset() +``` + +Resultado de una imagen iónica (resumido): + +```json +{ + "kind": "ion_image", + "mass": 756.55, + "tolerance": 0.1, + "shape": [200, 150], + "stats": { + "max": 14322.5, + "mean": 812.4, + "nonzero": 18450, + "base_peak_coord": [87, 42], + "centroid_coord": [91.2, 40.7] + }, + "preview": {"dims": [96, 72], "rows": [[...]]}, + "artifacts": { + "csv": {"path": ".../ion_mz_756.55.csv", "uri": "file://..."}, + "pgm": {"path": ".../ion_mz_756.55.pgm", "uri": "file://..."} + } +} +``` + +--- + +## 7. Manejo de errores + +Los handlers nunca tumban el bucle JSON-RPC: toda excepción se convierte en +`CallToolResult(is_error=true)` con este cuerpo: + +```json +{ + "error": { + "code": -32602, + "type": "InvalidParams", + "message": "Coordinates (99, 1) are outside the image bounds 4×3.", + "suggested_action": "Validate coordinates before retrying.", + "details": {"image_dims": [4, 3]} + } +} +``` + +| Tipo | Código | Origen típico | Acción sugerida | +|------|--------|---------------|-----------------| +| `InvalidParams` | `-32602` | masa/tolerancia/máscara/coordenadas | corregir argumentos | +| `SessionError` | `-32010` | no hay dataset abierto | `msi_open_dataset` | +| `ResourceNotFound` | `-32002` | task_id/URI inexistente | listar tareas/planes | +| `InternalError` | `-32603` | I/O, `.cache` corrupta, OOM | revisar stderr; borrar `.cache`; usar streaming | + +--- + +## 8. Pruebas + +```bash +julia --project=. -e 'using Pkg; Pkg.test()' +``` + +La suite genera un **imzML sintético válido** (4×3, Float32, 5 picos/espectro, un pico +fuerte en 300 Da) y cubre: + +- utilidades (hash canónico, JSON seguro, preview, estadísticas), +- apertura/cierre de sesión y `.cache`, +- espectro por coordenada e índice, +- extracción iónica síncrona y múltiple, +- validación de planes y binding al dataset, +- flujo asíncrono completo (plan → execute → status → result), +- analíticas y pipeline streaming, +- resources, prompts y cambio de dataset. + +Resultado actual: **107 tests OK** (~22 s en un equipo de desarrollo). + +También hay un smoke test real por stdio en `test/smoke_stdio.py` (genera el dataset +sintético, arranca el servidor y recorre initialize → tools → plan → execute → result). + +--- + +## 9. Validación con datasets reales + +Validado con los datos de `Cinvestav_2025/Analisis` (equipo de 12 hilos, 14 GB RAM, +disco local; los tiempos varían con la caché de página). + +### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imagen) + +| Métrica | Resultado | +|---------|-----------| +| Espectros / dimensiones | 34 840 / 260 × 134 | +| Tamaño | `.ibd` 815 MB, `.imzML` 56 MB (con `.cache`) | +| Apertura | 2.0–3.5 s usando la `.cache` binaria | +| Escaneo de analíticas | 6.8–12.9 s | +| Espectro `(130,67)` | 966 puntos, BPI 4 026.3, pico base 798.5387 | +| Ion image `798.5387 ± 0.15` | 1.8 s, máx 14 274.8, 21 920 píxeles con señal, pico base (167,105) | +| 4–5 masas en una pasada | 2.2 s sin máscara / 3.7 s con máscara | +| Máscara ROI (óptica → PGM) | 36 % del área; el TIFF óptico directo da ~43 % tras el parche | +| Streaming (12 571 espectros enmascarados) | 3.9 s; matriz 420 × 34 840; 1 424 362 nnz; `.mtx` 44 MB | +| Streaming (34 840 espectros, sin máscara) | 5.75 s de motor (10.3 s de pared); matriz 500 × 34 840; 3 822 821 nnz (78.1 %); ~61 MB RAM | +| Bins más intensos | 580.6, 443.8, 716.2 m/z | + +> La diferencia entre “motor” y “pared” en la primera corrida se debe sobre todo a la +> compilación JIT de la ruta de analíticas/streaming y al polling cada 1 s; en llamadas +> posteriores el tiempo de pared se acerca al del motor. Es el argumento principal para +> el sysimage AOT de la Fase 4. + +El pipeline streaming mantiene la RAM acotada: incluso con 34 840 espectros, el motor +solo conserva un espectro por hilo y ensambla una `SparseMatrixCSC`. + +### `mzML/` (perfiles no-imaging) + +| Archivo | Espectros | Apertura | Analíticas | +|---------|-----------|----------|------------| +| `T9_A1.mzML` | 10 | 0.06 s | 0.15–1.2 s | +| `Cytochrome_C.mzML` | 32 | 0.07 s | 0.15 s | +| `Col_1.mzML` | 800 | 0.17 s | 0.07 s | + +- `msi_get_spectrum_by_index` y `msi_get_dataset_stats` funcionan correctamente. +- Las tools de imagen (`msi_get_mz_slice`, `msi_plan_ion_image`, …) se rechazan con + `InvalidParams` porque el dataset no tiene `coordinate_map` ni dimensiones espaciales. + +### Reproducir + +```bash +# Smoke test genérico (detecta imaging vs. mzML automáticamente) +python3 test/smoke_stdio.py --dataset /ruta/archivo.imzML + +# Validación más completa (analíticas + ion image + múltiples masas + streaming opcional) +JULIA_MSI_MCP_REAL_STREAMING=1 julia --project=. test/real_datasets.jl \ + /ruta/archivo.imzML /ruta/archivo.mzML +``` + +--- + +## 10. Estructura del repositorio + +``` +JuliaMSI_MCP/ +├── Project.toml # deps + [sources] MSI_src → ../JuliaMSI +├── Manifest.toml +├── .github/workflows/ci.yml # CI (test + smoke) +├── bin/run_server.jl # entrypoint stdio / --http [--token] +├── scripts/ +│ ├── setup.jl # Pkg.develop + instantiate + precompile +│ ├── build_sysimage.jl # imagen de sistema AOT (Fase 4) +│ └── sysimage_warmup.jl # workload de precompilación +├── patches/ # parches de respaldo para el motor (ver §3) +├── src/ +│ ├── JuliaMSI_MCP.jl # módulo e includes +│ ├── util.jl # JSON seguro, hashes, previews +│ ├── errors.jl # MCPToolError + mapeo JSON-RPC +│ ├── session.jl # MSIData persistente + cleanup +│ ├── runspec.jl # planificación y validación +│ ├── tasks.jl # ejecución asíncrona + registro +│ ├── artifacts.jl # CSV/PGM/MatrixMarket + retención +│ ├── resources.jl # msi:// +│ ├── prompts.jl # flujos guiados (inglés) +│ ├── server.jl # build_server / run_stdio / run_http (+ token) +│ └── tools/ # dataset, spectra, imaging, planning, tasks, maintenance +├── config/ # Claude Desktop, VS Code, OpenCode +├── test/ +│ ├── synthetic.jl # generador imzML de prueba +│ ├── runtests.jl +│ ├── smoke_stdio.py # smoke test end-to-end por stdio +│ └── real_datasets.jl # validación reproducible con datasets reales +├── build/ # sysimage generado (ignorado por git) +└── artifacts/ # resultados (ignorado por git) +``` + +--- + +## 11. Relación con el compendio arquitectónico + +| Sección del compendio | Implementación MCP | +|-----------------------|--------------------| +| A.1 `MSIData`, LRU, atómicos | sesión persistente + `GetSpectrum` | +| A.2 slices / inversión de jerarquía | `msi_get_multiple_mz_slices`, `msi_plan_multiple_slices` | +| A.3 parser dual + `.cache` | `msi_open_dataset` (delegado al motor) | +| A.4 handle pool | `--threads=auto`; el motor abre un handle por hilo | +| A.5 Bloom filters | rechazo aplicado por `get_mz_slice` | +| A.6 mmap + `madvise` | `use_mmap=true` y `preview` acotado | +| A.7–A.8 preprocessing/streaming | `msi_plan_preprocessing`, `process_dataset!` | +| A.10 máscaras ROI | `mask_path` en planes y slices | +| A.11 sysimage AOT | `scripts/build_sysimage.jl` + `--sysimage` (ver §4) | +| A.12 `malloc_trim` | `release_os_memory!` en cierre y tareas pesadas | +| B.1 STDIO/HTTP | `run_stdio`, `run_http` (con token compartido opcional) | +| B.2 tools | 20 tools registradas | +| B.3 resources | `msi://dataset/*`, `msi://tasks/*` | +| B.4 errores/cleanup | `errors.jl` + hooks + retención de artefactos | + +--- + +## 12. Solución de problemas + +| Síntoma | Causa / solución | +|---------|------------------| +| `GLMakie failed to precompile` al instanciar | GLMakie es una dependencia del proyecto GUI del motor; el núcleo `MSI_src` (y por tanto el servidor MCP) ya no lo carga gracias a `PlottingStubs.jl`. Es inofensivo para el servidor. | +| El servidor arranca pero el cliente no ve tools | Revisa que el cliente lance `bin/run_server.jl` con `--project=...` y `--threads=auto`; los logs de arranque van a `stderr`. | +| `Dataset file not found` / `.ibd not found` | Usa rutas absolutas y mantén `.imzML` + `.ibd` con el mismo basename. | +| Primer slice tarda mucho | Se está ejecutando el escaneo de analíticas. Usa `msi_plan_analytics` + `msi_execute_runspec` en segundo plano. | +| `.cache` corrupta tras un crash | Borra `.imzML.cache`; el parser XML se regenera. | +| Error de permisos al abrir | El motor escribe `.imzML.cache` junto al dataset; copia el `.imzML`+`.ibd` a un directorio escribible. | +| RSS no baja tras cerrar | `msi_close_dataset` ya llama a `malloc_trim` en Linux; si usas musl/Alpine no existe y la memoria la recupera el kernel por presión. | +| `stdout` contaminado al depurar | No uses `println` en el proceso servidor; usa `stderr` o `@info`. `JULIA_MSI_MCP_KEEP_STDOUT=1` desactiva el guard (solo local). | + +## 13. Limitaciones conocidas y próximos pasos + +1. **Un dataset por proceso** (por diseño del motor). Para multiplexar datasets haría + falta un pool de sesiones o un proceso por dataset. +2. **Cancelación cooperativa**: no se puede interrumpir un `pread`/pasada de disco en + curso; la tarea se detiene en el siguiente checkpoint. +3. **`msi_get_dataset_stats` y slices síncronos pueden bloquear** durante el primer + escaneo de analíticas. Para datasets grandes, usar `msi_plan_analytics` + ejecución. +4. **Tasks MCP nativas (SEP-1686/2663)**: se usa un registro de tareas propio, compatible + con cualquier cliente. Se puede añadir `task_support=:optional` y `task_detach` cuando + se quiera publicar el estado por `tasks/get` del SDK. +5. **Huella base de memoria**: `using MSI_src` ya no carga el stack de plotting + (CairoMakie/GLMakie) gracias a `PlottingStubs.jl`, pero `Images` (para máscaras) sigue + dejando el proceso en ~1.6 GB RSS. Separar el core de datos de `ImageProcessing` + reduciría arranque y RAM. +6. **TLS**: el token compartido de HTTP protege el endpoint, pero el cifrado en tránsito + sigue dependiendo de un reverse proxy (Caddy/nginx) con TLS. + +Resuelto en Fase 4: retención de artefactos (`msi_clean_artifacts` + política al +arranque), autenticación HTTP por token compartido, script de sysimage AOT +(`scripts/build_sysimage.jl`) y CI (`../.github/workflows/ci.yml`). + +Roadmap sugerido (restante): + +- [ ] Publicar tareas/progreso por el mecanismo nativo de MCP (`task_support=:optional`, + `tasks/get`, `notifications/progress`). +- [ ] Notificación `notifications/resources/updated` para `msi://tasks/{id}/status`. +- [ ] Verificar el arranque con `--sysimage=build/sys_mcp.so` y medir la mejora de TTFX. +- [ ] Unit/integration en CI sobre un dataset de referencia real (benchmarks del repo). +- [ ] `Dockerfile`/systemd para despliegue headless. diff --git a/bin/run_server.jl b/bin/run_server.jl new file mode 100644 index 0000000..a903e1d --- /dev/null +++ b/bin/run_server.jl @@ -0,0 +1,78 @@ +#!/usr/bin/env julia +# --------------------------------------------------------------------------- +# JuliaMSI MCP server entry point. +# +# julia --project=/path/to/JuliaMSI_MCP --threads=auto bin/run_server.jl +# julia --project=/path/to/JuliaMSI_MCP --threads=auto bin/run_server.jl --http --port 3000 +# --------------------------------------------------------------------------- + +using JuliaMSI_MCP + +function usage() + println(stderr, """ +JuliaMSI MCP server $(JuliaMSI_MCP.SERVER_VERSION) + +Usage: + julia --project= --threads=auto bin/run_server.jl [options] + +Options: + --http Serve MCP over Streamable HTTP instead of stdio + --host Bind address for --http (default 127.0.0.1) + --port Port for --http (default 3000) + --token Require `Authorization: Bearer ` (HTTP only; + also JULIA_MSI_MCP_TOKEN) + --version Print the version and exit + -h, --help Show this help +""") +end + +function main(args) + http = false + host = "127.0.0.1" + port = 3000 + token = nothing + i = 1 + while i <= length(args) + a = args[i] + if a == "--http" + http = true + elseif a == "--host" + i += 1 + i <= length(args) || (usage(); return 2) + host = args[i] + elseif a == "--port" + i += 1 + i <= length(args) || (usage(); return 2) + port = try + parse(Int, args[i]) + catch + println(stderr, "Invalid --port value: $(args[i])") + return 2 + end + elseif a == "--token" + i += 1 + i <= length(args) || (usage(); return 2) + token = args[i] + elseif a == "--version" + println(JuliaMSI_MCP.SERVER_VERSION) + return 0 + elseif a in ("-h", "--help") + usage() + return 0 + else + println(stderr, "Unknown argument: $(a)") + usage() + return 2 + end + i += 1 + end + + if http + run_http(host=host, port=port, token=token) + else + run_stdio() + end + return 0 +end + +exit(main(ARGS)) diff --git a/config/claude_desktop_config.json b/config/claude_desktop_config.json new file mode 100644 index 0000000..de44bfa --- /dev/null +++ b/config/claude_desktop_config.json @@ -0,0 +1,16 @@ +{ + "mcpServers": { + "juliamsi": { + "command": "julia", + "args": [ + "--project=/home/pixel/Documents/2026/JuliaMSI_MCP", + "--threads=auto", + "/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl" + ], + "env": { + "JULIA_NUM_THREADS": "auto", + "JULIA_MSI_MCP_ARTIFACTS": "/home/pixel/Documents/2026/JuliaMSI_MCP/artifacts" + } + } + } +} diff --git a/config/opencode.json b/config/opencode.json new file mode 100644 index 0000000..03384d1 --- /dev/null +++ b/config/opencode.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "servers": { + "juliamsi": { + "type": "local", + "command": [ + "julia", + "--project=/home/pixel/Documents/2026/JuliaMSI_MCP", + "--threads=auto", + "/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl" + ], + "cwd": "/home/pixel/Documents/2026/JuliaMSI_MCP", + "environment": { + "JULIA_NUM_THREADS": "auto", + "JULIA_MSI_MCP_ARTIFACTS": "/home/pixel/Documents/2026/JuliaMSI_MCP/artifacts" + } + } + } + } +} diff --git a/config/vscode_mcp.json b/config/vscode_mcp.json new file mode 100644 index 0000000..40259cf --- /dev/null +++ b/config/vscode_mcp.json @@ -0,0 +1,17 @@ +{ + "servers": { + "juliamsi": { + "type": "stdio", + "command": "julia", + "args": [ + "--project=/home/pixel/Documents/2026/JuliaMSI_MCP", + "--threads=auto", + "/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl" + ], + "env": { + "JULIA_NUM_THREADS": "auto", + "JULIA_MSI_MCP_ARTIFACTS": "/home/pixel/Documents/2026/JuliaMSI_MCP/artifacts" + } + } + } +} diff --git a/implementation_plan.md b/implementation_plan.md new file mode 100644 index 0000000..d0851da --- /dev/null +++ b/implementation_plan.md @@ -0,0 +1,96 @@ +🗺️ Plan de Implementación por Fases +Fase 1: Servidor MCP Mínimo con Sesión Persistente (1-2 semanas) + +Objetivo: Validar el handshake y la comunicación básica, eliminando el TTFX de Julia mediante una sesión persistente. + + Configurar el proyecto de Julia e instalar ModelContextProtocol.jl. + + Implementar msi_open_dataset y msi_close_dataset. La sesión debe mantener una Ref{Union{MSIData, Nothing}} para conservar el dataset cargado entre llamadas. + + Implementar msi_get_spectrum_at_coord como una tool síncrona de prueba. + + Configurar el transporte stdio y verificar la conexión con Claude Desktop o VS Code. El objetivo es confirmar que el servidor arranca, negocia capacidades y responde a un tools/call. + +Entregable: Un servidor que permite abrir un .imzML, consultar un espectro y cerrar la sesión sin recargar el dataset. +Fase 2: Núcleo Asíncrono con Tasks (2-3 semanas) + +Objetivo: Implementar el patrón de planificación/ejecución con tareas en segundo plano. + + Definir la estructura RunSpec (inmutable, con un campo hash calculado a partir de los parámetros validados). + + Implementar msi_plan_ion_image y msi_plan_preprocessing. Estas tools solo validan y generan el RunSpec; no ejecutan cómputo pesado. + + Implementar msi_execute_runspec. Al recibir un runspec_hash, lanza una Task de Julia (Threads.@spawn) que ejecuta la función correspondiente (get_mz_slice o run_streaming_pipeline). Devuelve un task_id de inmediato. + + Implementar msi_get_task_status. Consulta el estado de la Task usando el task_id. El SDK de Julia permite exponer el estado de las tareas a través de tasks/get. + + Probar el flujo completo: planificar → ejecutar → polling → obtener resultado. + +Entregable: Un servidor que puede lanzar la extracción de una imagen iónica de forma asíncrona y notificar al LLM cuando termina. +Fase 3: Expansión del Catálogo (2-3 semanas) + +Objetivo: Cubrir las capacidades principales del motor JuliaMSI. + + Añadir msi_plan_multiple_slices para la inversión de jerarquía de búsqueda (A.2), que es computacionalmente más costosa. + + Añadir msi_plan_streaming_pipeline para el motor de preprocesamiento streaming (A.8). + + Implementar los Resources (msi://dataset/metadata, msi://dataset/stats, msi://tasks/{id}/status). + + Registrar los Prompts (analyze_region_of_interest, standard_pipeline). + +Entregable: Un servidor MCP con el conjunto completo de tools asíncronas, resources y prompts para flujos de trabajo de MSI. +Fase 4: Transporte Remoto y Resiliencia (1-2 semanas) + +Objetivo: Habilitar el acceso desde clientes remotos y garantizar la estabilidad en sesiones prolongadas. + + Habilitar el transporte Streamable HTTP (soportado por el SDK) para conexiones desde la nube o clústeres HPC. + + Integrar el hook de limpieza post-ejecución en msi_close_dataset y al finalizar cada Task pesada: GC.gc(true) + ccall(:malloc_trim, ...) (A.12) para devolver la memoria al SO. + + Añadir manejo de errores estructurado: mapear excepciones de Julia (OutOfMemoryError, IOError) a códigos de error JSON-RPC y sugerir acciones al LLM (por ejemplo, "use el pipeline streaming en lugar de la matriz densa"). + +Entregable: Un servidor MCP listo para producción, estable en sesiones largas y accesible de forma remota. + +--- + +## ✅ Estado de implementación (noviembre 2026) + +| Fase | Estado | Evidencia | +|------|--------|-----------| +| 1. Sesión persistente + tools básicas | ✅ | `src/session.jl`, `msi_open_dataset`, `msi_close_dataset`, `msi_get_spectrum_at_coord`; pruebas en `test/runtests.jl`. | +| 2. Núcleo asíncrono con Tasks | ✅ | `RunSpec` con hash SHA-256 (`src/runspec.jl`), `msi_plan_*`, `msi_execute_runspec`, `msi_get_task_status` (`src/tasks.jl`). | +| 3. Catálogo completo | ✅ | 19 tools, 4 resources/plantillas (`msi://dataset/*`, `msi://tasks/*`) y 3 prompts (`src/resources.jl`, `src/prompts.jl`). | +| 4. HTTP + resiliencia | 🟢 | Transporte Streamable HTTP (`run_http`) con token compartido opcional (`--token`/`JULIA_MSI_MCP_TOKEN`), `GC.gc(true)` + `malloc_trim` (`release_os_memory!`), errores estructurados (`src/errors.jl`), retención de artefactos (`msi_clean_artifacts` + política al arranque), script de sysimage AOT (`scripts/build_sysimage.jl`) y CI (`.github/workflows/ci.yml`). Pendiente: verificar el arranque con sysimage y publicar tareas/progreso por el mecanismo nativo de MCP. | + +Extras no previstos en el plan original: `msi_get_dataset_stats`, `msi_get_spectrum_by_index`, +`msi_plan_analytics`, `msi_list_plans`, `msi_list_tasks`, `msi_cancel_task`, generación +de artefactos CSV/PGM/MatrixMarket y un smoke test end-to-end (`test/smoke_stdio.py`). + +Verificación: `julia --project=. -e 'using Pkg; Pkg.test()'` → **100/100 tests OK**. + +Durante la integración se detectaron y corrigieron tres bugs del motor: dos en la ruta +sin mmap (handles cerrados por el finalizador del objeto temporal de caché y buffers +Float64 sobre datos Float32) y uno en el procesamiento de máscaras (TIFF `WidePixel` y +elemento estructurante par). Los parches están en `patches/juliamsi-fix-nonmmap.patch` y +`patches/juliamsi-fix-mask-io.patch`, y ya están aplicados al checkout local `../JuliaMSI`. + +Validación con datos reales de `Cinvestav_2025/Analisis`: HR2MSI bladder (34 840 +espectros, 260×134, analíticas en ~7 s, ion image ~2 s, 4–5 masas en una pasada ~2–4 s) +y mzML (T9_A1, Cytochrome_C, Col_1) con rechazo correcto de las tools de imagen para +datos no-imaging. + +Última corrida completa (sin máscara, `--threads` por defecto): + +- streaming de **34 840 espectros en 5.75 s**; +- matriz **500 × 34 840**, **3 822 821 nnz** (78.1 % dispersa), ~61 MB de RAM; +- `wall_seconds=10.3` (incluye overhead de polling y JIT del primer llamado). + +**Posición en el plan:** Fases 1–3 completas; Fase 4 implementada (HTTP+token, retención de +artefactos, script AOT y CI). Quedan como refinamiento: verificar el arranque con el +sysimage generado, y publicar tareas/progreso por el mecanismo nativo de MCP +(`task_support=:optional` / `tasks/get`). + +Nota sobre los parches: las tres correcciones del motor ya están upstream en el commit +`bc71b9c` (rama `rel/Windows_Mac_Recompatibility` y `main` de GitHub). `main` de Codeberg +y de nube-gran aún no las incluyen, por lo que `patches/` se conserva como respaldo. diff --git a/patches/juliamsi-fix-mask-io.patch b/patches/juliamsi-fix-mask-io.patch new file mode 100644 index 0000000..b533af1 --- /dev/null +++ b/patches/juliamsi-fix-mask-io.patch @@ -0,0 +1,35 @@ +diff --git a/src/ImageProcessing.jl b/src/ImageProcessing.jl +index d47ea6a..2518406 100644 +--- a/src/ImageProcessing.jl ++++ b/src/ImageProcessing.jl +@@ -31,8 +31,15 @@ function load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int}) + # Load the image + img = Images.load(mask_path) + +- # Convert to grayscale if it's a color image +- gray_img = Gray.(img) ++ # Convert to grayscale. Most images are already Colorant arrays, but TIFFs ++ # with extra samples (e.g. the optical reference images shipped with MSI ++ # datasets) load as TiffImages.WidePixel, for which Gray.(img) has no method. ++ # Fall back to the embedded color channel in that case. ++ gray_img = if eltype(img) <: Colorant ++ Gray.(img) ++ else ++ Gray.([getproperty(p, :color) for p in img]) ++ end + + # Binarize using Otsu's method - white regions become 'true' + binary_img = binarize(gray_img, Otsu()) +@@ -101,7 +108,11 @@ function process_image_pipeline(gray_img; + + # --- Step 4: Smooth Edges --- + # A morphological closing with a small disk smooths outlines. +- smoothing_kernel = ones(Bool, (smoothing, smoothing)) ++ # ImageMorphology requires odd-sized structuring elements; the historical ++ # default smoothing=2 produced a 2×2 matrix and threw "connectivity must be ++ # odd-sized". Normalize to the next odd size (minimum 3). ++ smooth_size = max(3, isodd(smoothing) ? smoothing : smoothing + 1) ++ smoothing_kernel = ones(Bool, (smooth_size, smooth_size)) + smoothed_img = closing(holes_filled_img, smoothing_kernel) + + # --- Return all intermediate steps for visualization --- diff --git a/patches/juliamsi-fix-nonmmap.patch b/patches/juliamsi-fix-nonmmap.patch new file mode 100644 index 0000000..bc736c4 --- /dev/null +++ b/patches/juliamsi-fix-nonmmap.patch @@ -0,0 +1,40 @@ +diff --git a/src/MSIData.jl b/src/MSIData.jl +index 1e88fa3..ed8851c 100644 +--- a/src/MSIData.jl ++++ b/src/MSIData.jl +@@ -1532,9 +1532,12 @@ end + function _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing}) + spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate + +- # Intialize local buffers for this thread's sequential iteration +- mz_buf = Vector{Float64}() +- int_buf = Vector{Float64}() ++ # Initialize local buffers for this thread's sequential iteration. ++ # IMPORTANT: the element type must match the on-disk format. Using Float64 ++ # buffers here made `read!` consume twice as many bytes for Float32 datasets ++ # and misinterpret them as Float64 garbage (breaking use_mmap=false). ++ mz_buf = Vector{source.mz_format}() ++ int_buf = Vector{source.intensity_format}() + + for i in spectrum_indices + meta = data.spectra_metadata[i] +diff --git a/src/imzML.jl b/src/imzML.jl +index a144893..f8071e2 100644 +--- a/src/imzML.jl ++++ b/src/imzML.jl +@@ -559,8 +559,13 @@ function load_imzml_lazy(file_path::String; cache_size::Int=100, use_mmap::Bool= + mz_is_compressed, int_is_compressed, global_mode) + + @debug "Metadata parsing complete. Saving cache for next time..." +- # We create a temporary MSIData just for save_metadata_cache +- tmp_source = ImzMLSource(ibd_handles, default_mz_format, default_intensity_format, mmap_data, any_comp) ++ # We create a temporary MSIData just for save_metadata_cache. ++ # IMPORTANT: do NOT share the real `ibd_handles` vector here. MSIData ++ # installs a finalizer that closes every handle in `source.ibd_handles`; ++ # when this temporary object is garbage-collected it would close the ++ # handles owned by the real dataset (breaking use_mmap=false reads with ++ # "Bad file descriptor"). The cache writer only needs the formats. ++ tmp_source = ImzMLSource(IO[], default_mz_format, default_intensity_format, nothing, any_comp) + tmp_msi = MSIData(tmp_source, spectra_metadata, instrument_meta, (width, height), nothing, cache_size) + save_metadata_cache(tmp_msi, cache_path) + end diff --git a/scripts/build_sysimage.jl b/scripts/build_sysimage.jl new file mode 100644 index 0000000..659849e --- /dev/null +++ b/scripts/build_sysimage.jl @@ -0,0 +1,52 @@ +#!/usr/bin/env julia +# --------------------------------------------------------------------------- +# Build a custom system image (AOT) for the JuliaMSI MCP server. +# +# This bakes JuliaMSI_MCP + MSI_src (and their reachable code) into a native +# shared object so the server starts without the first-call JIT latency. +# +# julia scripts/build_sysimage.jl +# +# Environment: +# JULIA_MSI_PATH Path to the JuliaMSI engine checkout (default ../JuliaMSI) +# JULIA_MSI_MCP_SYSIMAGE Output path (default build/sys_mcp.so) +# +# Run the server with the image afterwards: +# julia --project=. --threads=auto --sysimage=build/sys_mcp.so bin/run_server.jl +# --------------------------------------------------------------------------- + +using Pkg + +const MCP_DIR = normpath(joinpath(@__DIR__, "..")) +const ENGINE = get(ENV, "JULIA_MSI_PATH", normpath(joinpath(MCP_DIR, "..", "JuliaMSI"))) +const EXT = Sys.iswindows() ? ".dll" : Sys.isapple() ? ".dylib" : ".so" +const OUT = get(ENV, "JULIA_MSI_MCP_SYSIMAGE", joinpath(MCP_DIR, "build", "sys_mcp" * EXT)) + +isfile(joinpath(ENGINE, "Project.toml")) || + error("JuliaMSI engine not found at $(ENGINE). Set JULIA_MSI_PATH to the checkout.") + +println("--- JuliaMSI_MCP system image build ---") +println("engine : ", ENGINE) +println("output : ", OUT) + +mkpath(dirname(OUT)) + +# Use a throwaway environment so the runtime project stays lean. The engine is +# developed first so its package name/uuid (MSI_src) resolves for JuliaMSI_MCP. +Pkg.activate(; temp=true) +Pkg.develop(PackageSpec(path=ENGINE)) +Pkg.develop(PackageSpec(path=MCP_DIR)) +Pkg.add("PackageCompiler") + +using PackageCompiler + +create_sysimage( + [:JuliaMSI_MCP], + sysimage_path = OUT, + precompile_execution_file = joinpath(@__DIR__, "sysimage_warmup.jl"), + incremental = true, +) + +println("--- System image written to: ", OUT, " ---") +println("Run the server with:") +println(" julia --project=$(MCP_DIR) --threads=auto --sysimage=$(OUT) $(joinpath(MCP_DIR, "bin", "run_server.jl"))") diff --git a/scripts/setup.jl b/scripts/setup.jl new file mode 100644 index 0000000..7abade2 --- /dev/null +++ b/scripts/setup.jl @@ -0,0 +1,26 @@ +#!/usr/bin/env julia +# --------------------------------------------------------------------------- +# One-time setup: point Pkg at the local JuliaMSI engine and instantiate. +# +# JULIA_MSI_PATH=/path/to/JuliaMSI julia scripts/setup.jl +# +# By default the sibling `../JuliaMSI` directory (relative to this project) is +# used, matching the default layout of the development workspace. +# --------------------------------------------------------------------------- + +using Pkg + +project_dir = dirname(@__DIR__) +default_engine = normpath(joinpath(project_dir, "..", "JuliaMSI")) +engine = get(ENV, "JULIA_MSI_PATH", default_engine) + +if !isfile(joinpath(engine, "Project.toml")) + error("JuliaMSI engine not found at $(engine). Set JULIA_MSI_PATH to the JuliaMSI checkout.") +end + +println("Using JuliaMSI engine at: $(abspath(engine))") +Pkg.develop(PackageSpec(path=abspath(engine))) +Pkg.instantiate() +Pkg.precompile() +println("Setup complete. Start the server with:") +println(" julia --project=$(project_dir) --threads=auto $(joinpath(project_dir, "bin", "run_server.jl"))") diff --git a/scripts/sysimage_warmup.jl b/scripts/sysimage_warmup.jl new file mode 100644 index 0000000..efa6b14 --- /dev/null +++ b/scripts/sysimage_warmup.jl @@ -0,0 +1,58 @@ +# scripts/sysimage_warmup.jl +# --------------------------------------------------------------------------- +# Precompile warm-up workload for the JuliaMSI MCP server sysimage. +# +# This file is executed by PackageCompiler (scripts/build_sysimage.jl) inside a +# subprocess that already has `JuliaMSI_MCP` baked in. It exercises every +# engine/MCP code path the server uses, so the resulting system image contains +# native code for them instead of paying JIT on first use. +# --------------------------------------------------------------------------- + +using JuliaMSI_MCP +const J = JuliaMSI_MCP + +tmp = mktempdir() +ENV["JULIA_MSI_MCP_ARTIFACTS"] = joinpath(tmp, "artifacts") + +include(joinpath(@__DIR__, "..", "test", "synthetic.jl")) +imzml_path = write_synthetic_imzml(tmp; width=3, height=3) + +# Persistent session + metadata. +J.open_dataset(imzml_path; precompute_analytics=true) + +# Random-access spectrum query. +mz, intensity = J.MSI_src.GetSpectrum(J.require_data(), 1) + +# Ion image (sync execution path). +J._run_ion_image( + J._sync_runspec(:ion_image, Dict( + "mass" => 300.0, "tolerance" => 0.5, "mask_path" => nothing, + "include_matrix" => true, "preview_max_dim" => 32, "output_name" => "warm")), + J._sync_task(:ion_image), J.require_data()) + +# Multiple slices (hierarchy inversion). +J._run_multiple_slices( + J._sync_runspec(:multiple_slices, Dict( + "masses" => [100.0, 300.0, 500.0], "tolerance" => 0.5, "mask_path" => nothing, + "include_matrix" => false, "preview_max_dim" => 32, "output_name" => "warm")), + J._sync_task(:multiple_slices), J.require_data()) + +# Streaming preprocessing (Sprint 2). +J._run_streaming_pipeline( + J._sync_runspec(:streaming_pipeline, Dict( + "steps" => [ + Dict("name" => "smoothing", "params" => Dict("method" => "savitzky_golay", "window" => 5, "order" => 2)), + Dict("name" => "normalization", "params" => Dict("method" => "tic")), + Dict("name" => "peak_picking", "params" => Dict("method" => "profile", "snr_threshold" => 3.0)), + ], + "num_bins" => 50, "min_peaks_per_bin" => 1, "frequency_threshold" => 0.0, + "reference_peaks" => Float64[], "mask_path" => nothing, + "include_matrix" => false, "output_name" => "warm")), + J._sync_task(:streaming_pipeline), J.require_data()) + +J.close_dataset() + +# Register tools/resources/prompts so the schema builders are compiled too. +J.build_server() + +println("sysimage warmup complete") diff --git a/src/JuliaMSI_MCP.jl b/src/JuliaMSI_MCP.jl new file mode 100644 index 0000000..8741a52 --- /dev/null +++ b/src/JuliaMSI_MCP.jl @@ -0,0 +1,56 @@ +module JuliaMSI_MCP + +# --------------------------------------------------------------------------- +# JuliaMSI_MCP — Model Context Protocol server for the JuliaMSI engine. +# +# Layers: +# * session : one persistent MSIData per server process +# * planning : validated, content-addressed RunSpecs +# * execution : background Julia tasks + polling +# * artifacts : compact results + on-disk full data +# --------------------------------------------------------------------------- + +using JSON3 +using SHA +using Dates +using Printf +using Statistics +using SparseArrays +using CSV +using DataFrames +using UUIDs: uuid4 + +import MSI_src +using ModelContextProtocol + +include("util.jl") +include("errors.jl") +include("session.jl") +include("artifacts.jl") +include("runspec.jl") +include("tasks.jl") + +include("tools/dataset.jl") +include("tools/spectra.jl") +include("tools/imaging.jl") +include("tools/planning.jl") +include("tools/tasks.jl") +include("tools/maintenance.jl") + +include("resources.jl") +include("prompts.jl") +include("server.jl") + +export build_server, + run_stdio, + run_http, + open_dataset, + close_dataset, + session_metadata, + release_os_memory!, + RunSpec, + EngineTask, + SERVER_NAME, + SERVER_VERSION + +end # module diff --git a/src/artifacts.jl b/src/artifacts.jl new file mode 100644 index 0000000..3c19e7b --- /dev/null +++ b/src/artifacts.jl @@ -0,0 +1,263 @@ +# src/artifacts.jl +# --------------------------------------------------------------------------- +# Result persistence. +# +# Ion images and feature matrices must never be dumped into the JSON-RPC channel +# verbatim: a 2000×2000 float matrix is ~32 MB of JSON and stalls the model. +# Tools return compact statistics + a downsampled preview, and the full data is +# written to disk under `artifacts//`. +# --------------------------------------------------------------------------- + +const ARTIFACT_LOCK = ReentrantLock() + +"""Root directory for generated files (override with `JULIA_MSI_MCP_ARTIFACTS`).""" +function artifact_root() + root = get(ENV, "JULIA_MSI_MCP_ARTIFACTS", "") + if isempty(root) + root = joinpath(pkgdir(@__MODULE__), "artifacts") + end + root = abspath(expanduser(root)) + lock(ARTIFACT_LOCK) do + isdir(root) || mkpath(root) + end + return root +end + +function artifact_dir(task_id::AbstractString; label::AbstractString="") + dir = joinpath(artifact_root(), safe_filename(task_id, "task")) + if !isempty(label) + dir = joinpath(dir, safe_filename(label, "output")) + end + lock(ARTIFACT_LOCK) do + isdir(dir) || mkpath(dir) + end + return dir +end + +""" + artifact_retention_config() -> (max_age_days, max_total_bytes) + +Read the retention policy from the environment. Both knobs default to disabled: +- `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` (default 7): remove task dirs older than this. +- `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` (default 0): trim oldest dirs until the root is + under this many bytes (0 disables the size budget). +""" +function artifact_retention_config() + max_age_days = try + parse(Float64, get(ENV, "JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS", "7")) + catch + 7.0 + end + max_total_bytes = try + parse(Float64, get(ENV, "JULIA_MSI_MCP_ARTIFACT_MAX_BYTES", "0")) + catch + 0.0 + end + return max_age_days, max_total_bytes +end + +function _dir_size_bytes(path::AbstractString) + total = 0 + try + for (root, _dirs, files) in walkdir(path) + for f in files + p = joinpath(root, f) + try + total += filesize(p) + catch + end + end + end + catch + end + return total +end + +""" + prune_artifacts!(; max_age_days=0.0, max_total_bytes=0.0, dry_run=false) + +Delete artifact task-directories older than `max_age_days` (0 disables age-based +pruning) and, if `max_total_bytes > 0`, remove oldest-first until the artifact root +fits the budget. Only top-level task directories (one per task) are considered. + +Returns a summary dict with `removed`, `freed_bytes`, `remaining_bytes` and `dry_run`. +""" +function prune_artifacts!(; max_age_days::Real=0.0, max_total_bytes::Real=0.0, + dry_run::Bool=false) + root = artifact_root() + removed = 0 + freed = 0 + + lock(ARTIFACT_LOCK) do + entries = sort!([(mtime(p), p) for p in readdir(root; join=true) if isdir(p)]; + by=first) # oldest first + handled = Set{String}() + + # Age-based pruning. + if max_age_days > 0 + for (mt, path) in entries + if time() - mt > max_age_days * 86400 + freed += _dir_size_bytes(path) + dry_run || rm(path; recursive=true, force=true) + push!(handled, path) + removed += 1 + end + end + end + + # Size budget: oldest-first until the root fits. + if max_total_bytes > 0 + for (_, path) in entries + path in handled && continue + _dir_size_bytes(root) <= max_total_bytes && break + freed += _dir_size_bytes(path) + dry_run || rm(path; recursive=true, force=true) + push!(handled, path) + removed += 1 + end + end + end + + remaining_bytes = _dir_size_bytes(root) + return Dict{String,Any}( + "removed" => removed, + "freed_bytes" => freed, + "remaining_bytes" => remaining_bytes, + "dry_run" => dry_run, + "root" => root, + ) +end + +function artifact_record(path::AbstractString) + isfile(path) || return nothing + return Dict{String,Any}( + "path" => String(path), + "uri" => "file://" * String(path), + "name" => basename(path), + "bytes" => filesize(path), + "mime_type" => if endswith(lowercase(path), ".csv") + "text/csv" + elseif endswith(lowercase(path), ".pgm") + "image/x-portable-graymap" + elseif endswith(lowercase(path), ".mtx") + "text/plain" + elseif endswith(lowercase(path), ".json") + JSON_MIME + else + "application/octet-stream" + end, + ) +end + +function write_json_file(path::AbstractString, payload) + open(path, "w") do io + JSON3.write(io, jsonable(payload)) + end + return artifact_record(path) +end + +"""Write an intensity matrix as CSV with a `y\\x` header row.""" +function write_matrix_csv(path::AbstractString, mat::AbstractMatrix{<:Real}) + h, w = size(mat) + open(path, "w") do io + print(io, "y\\x") + for x in 1:w + print(io, ",", x) + end + println(io) + for y in 1:h + print(io, y) + for x in 1:w + v = Float64(mat[y, x]) + print(io, ",", isfinite(v) ? repr(v) : "0.0") + end + println(io) + end + end + return artifact_record(path) +end + +"""Write a normalized 8-bit grayscale PGM (viewable in most image apps).""" +function write_matrix_pgm(path::AbstractString, mat::AbstractMatrix{<:Real}) + h, w = size(mat) + vmax = 0.0 + @inbounds for v in mat + f = Float64(v) + isfinite(f) && f > vmax && (vmax = f) + end + scale = vmax > 0 ? 255.0 / vmax : 0.0 + open(path, "w") do io + write(io, "P5\n# JuliaMSI_MCP ion image (normalized to max)\n$(w) $(h)\n255\n") + buf = Vector{UInt8}(undef, h * w) + k = 1 + # PGM is row-major; Julia matrices are column-major. + for y in 1:h, x in 1:w + v = Float64(mat[y, x]) + buf[k] = (!isfinite(v) || v <= 0) ? 0x00 : round(UInt8, clamp(v * scale, 0.0, 255.0)) + k += 1 + end + write(io, buf) + end + return artifact_record(path) +end + +"""Write a vector as a two-column CSV (`index,value`).""" +function write_vector_csv(path::AbstractString, values::AbstractVector{<:Real}; + header::AbstractString="index,value") + open(path, "w") do io + println(io, header) + for (i, v) in enumerate(values) + println(io, i, ",", repr(Float64(v))) + end + end + return artifact_record(path) +end + +"""Stream a `SparseMatrixCSC` to Matrix Market coordinate format.""" +function write_sparse_mtx(path::AbstractString, mat::SparseMatrixCSC) + m, n = size(mat) + open(path, "w") do io + write(io, "%%MatrixMarket matrix coordinate real general\n") + write(io, "$(m) $(n) $(SparseArrays.nnz(mat))\n") + rows = SparseArrays.rowvals(mat) + vals = SparseArrays.nonzeros(mat) + @inbounds for j in 1:n + for idx in SparseArrays.nzrange(mat, j) + write(io, "$(rows[idx]) $(j) $(vals[idx])\n") + end + end + end + return artifact_record(path) +end + +"""Persist a single ion image (CSV + PGM + JSON sidecar) and return the paths.""" +function persist_ion_image(dir::AbstractString, label::AbstractString, + mat::AbstractMatrix{<:Real}; extra=nothing) + base = safe_filename(label, "ion_image") + csv = write_matrix_csv(joinpath(dir, base * ".csv"), mat) + pgm = write_matrix_pgm(joinpath(dir, base * ".pgm"), mat) + sidecar = Dict{String,Any}( + "label" => String(label), + "stats" => matrix_stats(mat), + "artifacts" => Dict{String,Any}("csv" => csv, "pgm" => pgm), + ) + extra !== nothing && (sidecar["metadata"] = extra) + meta = write_json_file(joinpath(dir, base * ".json"), sidecar) + return Dict{String,Any}("csv" => csv, "pgm" => pgm, "metadata" => meta) +end + +"""Top-N bins by total intensity for a feature matrix.""" +function top_bins(mat::SparseMatrixCSC, bin_centers::AbstractVector{<:Real}; + n::Integer=20) + totals = vec(sum(mat; dims=2)) + positive = findall(>(0), totals) + isempty(positive) && return Any[] + k = min(Int(n), length(positive)) + order = positive[sortperm(totals[positive]; rev=true)[1:k]] + return [Dict{String,Any}( + "bin" => Int(i), + "mz" => compact_float(bin_centers[i]), + "total_intensity" => compact_float(totals[i]), + "spectra_with_signal" => count(>(0), mat[i, :]), + ) for i in order] +end diff --git a/src/errors.jl b/src/errors.jl new file mode 100644 index 0000000..636d2b3 --- /dev/null +++ b/src/errors.jl @@ -0,0 +1,130 @@ +# src/errors.jl +# --------------------------------------------------------------------------- +# Structured errors: Julia exceptions -> JSON-RPC-ish codes that the LLM can +# reason about, as specified in the architectural compendium (B.4). +# --------------------------------------------------------------------------- + +const ERR_INVALID_PARAMS = -32602 +const ERR_INTERNAL = -32603 +const ERR_METHOD_NOT_FOUND = -32601 +const ERR_RESOURCE_NOT_FOUND = -32002 +const ERR_SESSION = -32010 + +""" + MCPToolError(code, kind, message; suggested_action=nothing, details=nothing) + +A tool-level failure that should be reported to the model with `isError=true` +instead of crashing the server loop. +""" +struct MCPToolError <: Exception + code::Int + kind::String + message::String + suggested_action::Union{Nothing,String} + details::Union{Nothing,Dict{String,Any}} +end + +function MCPToolError(message::AbstractString; kind::AbstractString="ToolError", + code::Int=ERR_INTERNAL, + suggested_action::Union{Nothing,AbstractString}=nothing, + details=nothing) + return MCPToolError(code, String(kind), String(message), + suggested_action === nothing ? nothing : String(suggested_action), + details === nothing ? nothing : Dict{String,Any}(details)) +end + +invalid_params(message; suggested_action=nothing, details=nothing) = + MCPToolError(message; kind="InvalidParams", code=ERR_INVALID_PARAMS, + suggested_action=suggested_action, details=details) + +internal_error(message; suggested_action=nothing, details=nothing) = + MCPToolError(message; kind="InternalError", code=ERR_INTERNAL, + suggested_action=suggested_action, details=details) + +session_error(message; suggested_action=nothing) = + MCPToolError(message; kind="SessionError", code=ERR_SESSION, + suggested_action=suggested_action) + +resource_not_found(message; suggested_action=nothing) = + MCPToolError(message; kind="ResourceNotFound", code=ERR_RESOURCE_NOT_FOUND, + suggested_action=suggested_action) + +"""Map an arbitrary Julia exception to an `MCPToolError`.""" +function classify_exception(e::Exception) + e isa MCPToolError && return e + + if e isa OutOfMemoryError + return internal_error( + "Julia engine ran out of memory: $(sprint(showerror, e))"; + suggested_action="Retry with the streaming pipeline (msi_plan_preprocessing) or reduce num_bins; close and reopen the dataset to release OS memory.", + details=Dict("exception_type" => "OutOfMemoryError"), + ) + elseif e isa InterruptException + return MCPToolError("Operation cancelled"; kind="Cancelled", + code=ERR_INTERNAL, suggested_action="Re-run the plan if needed.") + elseif e isa SystemError || e isa IOError || e isa EOFError + return internal_error( + "I/O error from the JuliaMSI engine: $(sprint(showerror, e))"; + suggested_action="Check that the .imzML/.ibd files are readable and the disk is mounted; deleting the .cache file forces a clean parser pass.", + details=Dict("exception_type" => string(typeof(e))), + ) + elseif e isa ArgumentError || e isa DomainError || e isa BoundsError + return invalid_params(sprint(showerror, e); + suggested_action="Validate coordinates, mass ranges and tool arguments before retrying.", + details=Dict("exception_type" => string(typeof(e)))) + end + + return internal_error(sprint(showerror, e); + suggested_action="Inspect the server stderr log for the Julia stack trace.", + details=Dict("exception_type" => string(typeof(e)))) +end + +"""Build the structured error payload sent back through the tool result.""" +function error_payload(e; context::Union{Nothing,Dict{String,Any}}=nothing) + err = classify_exception(e) + payload = Dict{String,Any}( + "error" => Dict{String,Any}( + "code" => err.code, + "type" => err.kind, + "message" => err.message, + ), + ) + if err.suggested_action !== nothing + payload["error"]["suggested_action"] = err.suggested_action + end + if err.details !== nothing + payload["error"]["details"] = err.details + end + context !== nothing && (payload["context"] = context) + return payload +end + +"""Convert any exception into a `CallToolResult` with `isError=true`.""" +function error_result(e; context=nothing) + payload = error_payload(e; context=context) + return ModelContextProtocol.CallToolResult( + content = [Dict{String,Any}("type" => "text", "text" => json_text(payload))], + is_error = true, + ) +end + +""" + guarded(f) + +Run a tool handler body, converting any exception into a structured error +result. The server loop must never die because of a bad argument or a corrupt +dataset. +""" +function guarded(f::Function; context=nothing) + try + return f() + catch e + if !(e isa MCPToolError) + @error "Tool handler failed" exception=(e, catch_backtrace()) + end + return error_result(e; context=context) + end +end + +"""Wrap a handler with `guarded`, preserving the one-arg MCP convention.""" +guarded_handler(f::Function) = params -> guarded(() -> f(params)) diff --git a/src/prompts.jl b/src/prompts.jl new file mode 100644 index 0000000..9c061a1 --- /dev/null +++ b/src/prompts.jl @@ -0,0 +1,116 @@ +# src/prompts.jl +# --------------------------------------------------------------------------- +# Reusable workflow prompts. These guide the model through the plan -> execute +# -> poll -> inspect cycle without hard-coding any particular dataset. +# --------------------------------------------------------------------------- + +import ModelContextProtocol: user, assistant + +const PROMPT_ANALYZE_REGION = MCPPrompt( + name = "analyze_region_of_interest", + description = "Guides a reproducible region-of-interest (ROI) analysis: confirm mass, tolerance and mask, then plan, execute and inspect the result.", + arguments = [ + PromptArgument(name = "dataset_path", description = "Absolute path to the .imzML (or .mzML) file.", required = true), + PromptArgument(name = "region", description = "Description of the tissue or region of interest.", required = false), + PromptArgument(name = "mass_hint", description = "Candidate m/z value or compound of interest (optional).", required = false), + ], + messages = [ + PromptMessage(role = user, content = TextContent(text = """ +You are an expert mass spectrometry imaging (MSI) assistant operating the JuliaMSI +MCP server. The dataset to analyze is: {dataset_path}. +Region of interest: {?region?{region}} +Candidate mass: {?mass_hint?{mass_hint}} +If any of these fields is empty, ask the user for it before continuing. + +Before running expensive work, collect and confirm: +1. Target mass (m/z, in Daltons) and tolerance (Da; convert ppm to Da if needed). +2. Whether a mask image (PNG/TIFF/BMP) is available to restrict the ROI. +3. Whether the user wants a single mass (msi_get_mz_slice or + msi_plan_ion_image) or a panel (msi_plan_multiple_slices). + +Recommended workflow: +- msi_dataset_info to check the session; if no dataset is open, use msi_open_dataset. +- For a large dataset with analytics not ready, plan msi_plan_analytics and run it + in the background first. +- Create the plan with msi_plan_ion_image (or msi_plan_multiple_slices). +- Execute with msi_execute_runspec and keep the task_id. +- Poll msi_get_task_status until the task is terminal, then call msi_get_task_result. +- Summarize: m/z, tolerance, dimensions, max/mean intensity, base-peak coordinate, + artifact paths (CSV/PGM) and any range warnings. + +Do not invent mass values. If the user has not provided one, propose candidates and +ask for confirmation. Interpret structured errors (the suggested_action field) and +fix the request before retrying. +""")), + ], +) + +const PROMPT_STANDARD_PIPELINE = MCPPrompt( + name = "standard_pipeline", + description = "Reproducible streaming preprocessing workflow: open, plan, execute, poll and summarize the sparse feature matrix.", + arguments = [ + PromptArgument(name = "dataset_path", description = "Absolute path to the .imzML/.mzML dataset.", required = true), + PromptArgument(name = "goal", description = "Biological or analytical goal of the preprocessing run.", required = false), + ], + messages = [ + PromptMessage(role = user, content = TextContent(text = """ +Act as an MSI analyst and run a reproducible preprocessing pipeline on: +{dataset_path} +Declared goal: {?goal?{goal}} +If no goal is declared, assume general exploration and confirm that with the user. + +Follow this order and stop if a step fails: +1. msi_open_dataset with use_mmap=true (keep precompute_analytics=false). +2. msi_dataset_info and record num_spectra, image_dims and m/z range. +3. msi_plan_preprocessing with an explicit pipeline, for example: + - smoothing: savitzky_golay, window 9, order 2 + - baseline_correction: snip, iterations 100 + - normalization: tic + - peak_picking: profile, snr_threshold 3.0 + Use num_bins 2000, min_peaks_per_bin 3 and frequency_threshold 0.05. + On very large datasets or low-RAM machines, keep the streaming engine and leave + include_matrix=false. +4. msi_execute_runspec with the runspec_id and wait_seconds=0. +5. Poll msi_get_task_status (at most ~30 times, with a short pause between polls) + until completed/failed/cancelled. +6. msi_get_task_result: report matrix_shape, nonzeros, density, bin_mz_range, + top_bins and the artifact paths (.mtx and bin_centers.csv). +7. Finish with msi_close_dataset to release file handles and OS memory. + +The final summary must include the exact parameters, runspec_id, task_id, matrix +size and a short interpretation of the most intense bins. +""")), + ], +) + +const PROMPT_DIAGNOSE_TASK = MCPPrompt( + name = "diagnose_task", + description = "Instructs the model to diagnose a failed or slow task using status, structured errors and process memory.", + arguments = [ + PromptArgument(name = "task_id", description = "Identifier of the task to diagnose.", required = true), + ], + messages = [ + PromptMessage(role = user, content = TextContent(text = """ +Diagnose task {task_id} on the JuliaMSI MCP server. + +1. Read msi_get_task_status with include_summary=true and, when available, the + resource msi://tasks/{task_id}/status. +2. If status=failed, inspect error.code, error.type, error.message, + error.suggested_action and error.details. Translate the error into a probable cause. +3. If status=running for a long time, check progress, duration_seconds and the RSS + reported by msi_dataset_info. If RSS is near the machine limit, propose cancelling + (msi_cancel_task) and retrying with the streaming pipeline or fewer bins. +4. If status=completed, validate the result with msi_get_task_result: check dimensions, + density, top_bins and artifacts; flag anomalies (all-zero matrix, 100% density, + empty bins). +5. Finish with a list of concrete actions and, when appropriate, a corrected plan. + +Common failure categories: +- SessionError: no dataset is open -> msi_open_dataset. +- InvalidParams: wrong mass/tolerance/mask or a dataset different from the one used + for the plan -> replan. +- I/O: missing .ibd, permissions, corrupt .cache -> delete .cache and reopen. +- OutOfMemoryError: reduce num_bins, use a mask or switch to the streaming pipeline. +""")), + ], +) diff --git a/src/resources.jl b/src/resources.jl new file mode 100644 index 0000000..70333c2 --- /dev/null +++ b/src/resources.jl @@ -0,0 +1,111 @@ +# src/resources.jl +# --------------------------------------------------------------------------- +# Read-only MCP resources (msi:// URI scheme). +# --------------------------------------------------------------------------- + +function _dataset_metadata_resource() + return session_metadata() +end + +function _dataset_stats_resource() + meta = session_metadata() + if meta["open"] != true + return Dict{String,Any}("open" => false, "hint" => meta["hint"]) + end + data = lock(SESSION.lock) do + SESSION.data + end + data === nothing && return Dict{String,Any}("open" => false) + if !MSI_src.is_set(data.analytics_ready) + return Dict{String,Any}( + "open" => true, + "analytics_ready" => false, + "hint" => "Analytics have not been computed. Call msi_plan_analytics + msi_execute_runspec (recommended) or msi_get_dataset_stats.", + ) + end + stats_df = MSI_src.get_spectrum_stats(data) + stats_df === nothing && return Dict{String,Any}("open" => true, "analytics_ready" => false) + aggregate = Dict{String,Any}() + for col in ("TIC", "BPI", "NumPoints") + v = Float64.(stats_df[!, col]) + aggregate[col] = Dict{String,Any}( + "min" => compact_float(minimum(v)), + "max" => compact_float(maximum(v)), + "mean" => compact_float(Statistics.mean(v)), + "median" => compact_float(Statistics.median(v)), + ) + end + n = min(100, nrow(stats_df)) + rows = Any[] + for i in 1:n + push!(rows, Dict{String,Any}( + "spectrum_id" => Int(stats_df[i, "SpectrumID"]), + "tic" => compact_float(stats_df[i, "TIC"]), + "bpi" => compact_float(stats_df[i, "BPI"]), + "base_peak_mz" => compact_float(stats_df[i, "BasePeakMZ"]), + "num_points" => Int(stats_df[i, "NumPoints"]), + "min_mz" => compact_float(stats_df[i, "MinMZ"]), + "max_mz" => compact_float(stats_df[i, "MaxMZ"]), + "mode" => string(stats_df[i, "Mode"]), + )) + end + min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0) + max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0) + return Dict{String,Any}( + "open" => true, + "dataset_id" => meta["dataset_id"], + "analytics_ready" => true, + "num_spectra" => nrow(stats_df), + "mz_range" => Any[compact_float(min_mz), compact_float(max_mz)], + "aggregate" => aggregate, + "rows_returned" => length(rows), + "rows" => rows, + "hint" => "Showing the first 100 spectra. Use msi_get_dataset_stats for more rows or the CSV artifact of msi_plan_analytics.", + ) +end + +const DATASET_METADATA_RESOURCE = MCPResource( + uri = "msi://dataset/metadata", + name = "Dataset metadata", + description = "State of the active dataset: path, dimensions, spectra count, m/z range, mmap/cache status and process memory.", + mime_type = JSON_MIME, + data_provider = () -> _dataset_metadata_resource(), +) + +const DATASET_STATS_RESOURCE = MCPResource( + uri = "msi://dataset/stats", + name = "Dataset statistics", + description = "Aggregated per-spectrum statistics (TIC, BPI, points, m/z bounds) plus the first 100 rows. Does not trigger the analytics scan.", + mime_type = JSON_MIME, + data_provider = () -> _dataset_stats_resource(), +) + +const TASK_STATUS_TEMPLATE = ResourceTemplate( + name = "task_status", + uri_template = "msi://tasks/{task_id}/status", + description = "Status, progress and timestamps of a background task.", + mime_type = JSON_MIME, + data_provider = (uri, vars) -> begin + id = String(vars["task_id"]) + try + task_status_payload(get_task(id)) + catch e + error_payload(e; context=Dict{String,Any}("uri" => string(uri))) + end + end, +) + +const TASK_RESULT_TEMPLATE = ResourceTemplate( + name = "task_result", + uri_template = "msi://tasks/{task_id}/result", + description = "Full structured result of a completed task (statistics, preview, artifact paths).", + mime_type = JSON_MIME, + data_provider = (uri, vars) -> begin + id = String(vars["task_id"]) + try + task_result_payload(get_task(id)) + catch e + error_payload(e; context=Dict{String,Any}("uri" => string(uri))) + end + end, +) diff --git a/src/runspec.jl b/src/runspec.jl new file mode 100644 index 0000000..d237f1a --- /dev/null +++ b/src/runspec.jl @@ -0,0 +1,373 @@ +# src/runspec.jl +# --------------------------------------------------------------------------- +# Planning layer. +# +# A `RunSpec` is an immutable, content-addressed description of a computation. +# Planning tools validate arguments and mint a RunSpec; they never execute the +# expensive engine work. `msi_execute_runspec` is the only entry point to the +# execution layer. This keeps plans auditable and reproducible (same inputs -> +# same hash), which matters in scientific workflows. +# --------------------------------------------------------------------------- + +struct RunSpec + id::String + kind::Symbol + dataset_id::String + params::Dict{String,Any} + created_at::Float64 + summary::String +end + +const RUNSPEC_LOCK = ReentrantLock() +const RUNSPECS = Dict{String,RunSpec}() +const RUNSPEC_ORDER = String[] +const MAX_RUNSPECS = 256 + +const RUNSPEC_KINDS = (:ion_image, :multiple_slices, :streaming_pipeline, :analytics) + +# --------------------------------------------------------------------------- +# Parameter helpers (JSON3 objects behave like dictionaries) +# --------------------------------------------------------------------------- + +_pget(params, key, default=nothing) = haskey(params, key) ? params[key] : default + +function opt_string(params, key; default=nothing, allow_empty=false) + v = _pget(params, key, default) + v === nothing && return nothing + s = string(v) + if !allow_empty && isempty(strip(s)) + return default === nothing ? nothing : String(default) + end + return s +end + +function opt_float(params, key; default=nothing, min=-Inf, max=Inf) + v = _pget(params, key, default) + v === nothing && return nothing + x = try + Float64(v) + catch + throw(invalid_params("Parameter `$(key)` must be a number, got $(repr(v)).")) + end + isfinite(x) || throw(invalid_params("Parameter `$(key)` must be finite.")) + (x < min || x > max) && throw(invalid_params( + "Parameter `$(key)` = $(x) is outside the allowed range [$(min), $(max)].")) + return x +end + +function opt_int(params, key; default=nothing, min=typemin(Int), max=typemax(Int)) + v = _pget(params, key, default) + v === nothing && return nothing + x = try + Int(v) + catch + throw(invalid_params("Parameter `$(key)` must be an integer, got $(repr(v)).")) + end + (x < min || x > max) && throw(invalid_params( + "Parameter `$(key)` = $(x) is outside the allowed range [$(min), $(max)].")) + return x +end + +function opt_bool(params, key; default=false) + v = _pget(params, key, default) + v isa Bool && return v + v isa Integer && return v != 0 + v isa AbstractString && return lowercase(v) in ("true", "1", "yes", "on") + return false +end + +function opt_float_vector(params, key; default=Float64[], min_len=0, max_len=10_000) + v = _pget(params, key, nothing) + v === nothing && return Float64.(default) + v isa AbstractString && throw(invalid_params("Parameter `$(key)` must be an array of numbers.")) + values = try + Float64[Float64(x) for x in collect(v)] + catch + throw(invalid_params("Parameter `$(key)` must be an array of numbers.")) + end + all(isfinite, values) || throw(invalid_params("Parameter `$(key)` must contain only finite numbers.")) + (length(values) < min_len || length(values) > max_len) && throw(invalid_params( + "Parameter `$(key)` must contain between $(min_len) and $(max_len) values (got $(length(values))).")) + return values +end + +function validate_mask_path(params, data) + mask = opt_string(params, "mask_path"; default=nothing) + mask === nothing && return nothing + path = abspath(expanduser(mask)) + isfile(path) || throw(invalid_params( + "Mask file not found: $(path)"; + suggested_action="Pass the absolute path to a binary mask image (PNG/TIFF/BMP) with the same orientation as the image.")) + data.coordinate_map === nothing && throw(invalid_params( + "Mask-based ROI filtering requires an imaging dataset with a coordinate map (imzML).")) + return path +end + +# --------------------------------------------------------------------------- +# Registry +# --------------------------------------------------------------------------- + +function _register_runspec!(rs::RunSpec) + lock(RUNSPEC_LOCK) do + RUNSPECS[rs.id] = rs + push!(RUNSPEC_ORDER, rs.id) + while length(RUNSPEC_ORDER) > MAX_RUNSPECS + old = popfirst!(RUNSPEC_ORDER) + pop!(RUNSPECS, old, nothing) + end + end + return rs +end + +function get_runspec(id::AbstractString) + lock(RUNSPEC_LOCK) do + rs = get(RUNSPECS, String(id), nothing) + rs === nothing && throw(invalid_params( + "Unknown runspec_id: $(id)"; + suggested_action="Create a plan with msi_plan_ion_image / msi_plan_multiple_slices / msi_plan_preprocessing first. Plans expire after 256 newer plans.")) + return rs + end +end + +function list_runspecs(; limit::Integer=20) + lock(RUNSPEC_LOCK) do + ids = reverse(RUNSPEC_ORDER) + take = ids[1:min(Int(limit), length(ids))] + return [RUNSPECS[i] for i in take if haskey(RUNSPECS, i)] + end +end + +function create_runspec(kind::Symbol, params::Dict{String,Any}, summary::AbstractString) + kind in RUNSPEC_KINDS || throw(internal_error("Unimplemented RunSpec kind: $(kind)")) + dataset_id = active_dataset_id() + dataset_id === nothing && throw(session_error( + "No dataset is open."; suggested_action="Call msi_open_dataset first.")) + material = Dict{String,Any}( + "version" => 1, + "kind" => string(kind), + "dataset_id" => dataset_id, + "params" => params, + ) + id = short_hash(material, 32) + rs = RunSpec(id, kind, dataset_id, params, time(), String(summary)) + return _register_runspec!(rs) +end + +"""Human/LLM-facing description of a plan (without executing it).""" +function runspec_payload(rs::RunSpec; include_params::Bool=true) + payload = Dict{String,Any}( + "runspec_id" => rs.id, + "kind" => string(rs.kind), + "dataset_id" => rs.dataset_id, + "summary" => rs.summary, + "created_at" => Dates.format(Dates.unix2datetime(rs.created_at), "yyyy-mm-ddTHH:MM:SS"), + "next_step" => "Call msi_execute_runspec with this runspec_id, then poll msi_get_task_status.", + ) + include_params && (payload["params"] = rs.params) + return payload +end + +"""Ensure a plan is executed against the dataset it was planned for.""" +function check_runspec_dataset(rs::RunSpec) + current = active_dataset_id() + current === nothing && throw(session_error( + "No dataset is open."; suggested_action="Reopen the dataset and replan.")) + if current != rs.dataset_id + throw(invalid_params( + "This RunSpec was planned for dataset $(rs.dataset_id), but the active dataset is $(current)."; + suggested_action="Recreate the plan against the currently open dataset.", + details=Dict("runspec_dataset" => rs.dataset_id, "active_dataset" => current))) + end + return true +end + +# --------------------------------------------------------------------------- +# Validators / plan builders +# --------------------------------------------------------------------------- + +"""Ion images only make sense for imaging datasets with a spatial coordinate map.""" +function require_imaging(data) + if data.coordinate_map === nothing || data.image_dims[1] <= 0 || data.image_dims[2] <= 0 + throw(invalid_params( + "Ion-image extraction requires imaging data (an .imzML file with a coordinate map); this dataset has no spatial dimensions (.mzML or non-imaging input)."; + suggested_action="Use msi_get_spectrum_by_index and msi_get_dataset_stats for mzML/profile files, or open an .imzML dataset for spatial analysis.", + details=Dict("image_dims" => Any[data.image_dims[1], data.image_dims[2]], + "coordinate_map" => data.coordinate_map !== nothing))) + end + return true +end + +function _ion_image_params(params, data; multiple::Bool=false) + require_imaging(data) + mask_path = validate_mask_path(params, data) + tolerance = opt_float(params, "tolerance"; default=0.1, min=eps(Float64), max=1000.0) + + out = Dict{String,Any}( + "tolerance" => tolerance, + "mask_path" => mask_path, + "include_matrix" => opt_bool(params, "include_matrix"; default=false), + "preview_max_dim" => opt_int(params, "preview_max_dim"; default=96, min=16, max=256), + ) + + if multiple + masses = opt_float_vector(params, "masses"; min_len=1, max_len=5000) + masses = unique(masses) + out["masses"] = masses + out["output_name"] = safe_filename( + something(opt_string(params, "output_name"; default=nothing), "multiple_slices")) + out["_verify"] = _mz_overlap_note(masses, tolerance) + else + mass = opt_float(params, "mass"; default=nothing, min=eps(Float64), max=1.0e7) + mass === nothing && throw(invalid_params( + "Missing required parameter `mass` (Daltons)."; + suggested_action="Example: {\"mass\": 756.55, \"tolerance\": 0.1}")) + out["mass"] = mass + out["output_name"] = safe_filename( + something(opt_string(params, "output_name"; default=nothing), + "ion_mz_" * string(round(mass, digits=4)))) + out["_verify"] = _mz_overlap_note([mass], tolerance) + end + return out +end + +"""Warn (not fail) when a target lies outside the computed global m/z range.""" +function _mz_overlap_note(masses::Vector{Float64}, tolerance::Float64) + note = Dict{String,Any}("checked" => false) + data = lock(SESSION.lock) do + SESSION.data + end + data === nothing && return note + MSI_src.is_set(data.analytics_ready) || begin + note["reason"] = "analytics not computed yet; range check deferred to execution" + return note + end + min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0) + max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0) + lo, hi = min_mz - tolerance, max_mz + tolerance + outside = [m for m in masses if m < lo || m > hi] + note["checked"] = true + note["global_mz_range"] = Any[compact_float(min_mz), compact_float(max_mz)] + isempty(outside) || (note["outside_range"] = outside) + return note +end + +const ALLOWED_STEP_NAMES = Set([ + "smoothing", "baseline_correction", "normalization", "stabilization", + "intensity_transformation", "peak_picking", "calibration", +]) + +function _parse_steps(params) + raw = _pget(params, "steps", nothing) + if raw !== nothing + raw isa AbstractString && throw(invalid_params("`steps` must be an array of objects.")) + steps = Dict{String,Any}[] + for (i, item) in enumerate(collect(raw)) + item isa AbstractDict || throw(invalid_params( + "steps[$(i)] must be an object like {\"name\": \"smoothing\", \"params\": {...}}.")) + name = String(_pget(item, "name", "")) + name in ALLOWED_STEP_NAMES || throw(invalid_params( + "Unknown preprocessing step '$(name)' at steps[$(i)]."; + suggested_action="Allowed steps: " * join(sort(collect(ALLOWED_STEP_NAMES)), ", "))) + step_params = _pget(item, "params", Dict{String,Any}()) + steps = push!(steps, Dict{String,Any}("name" => name, + "params" => Dict{String,Any}(jsonable(step_params)))) + end + isempty(steps) || return steps + end + + # Convenience shorthands mirroring the compendium / app.jl names. + steps = Dict{String,Any}[] + window = opt_int(params, "smoothing_window"; default=0, min=0, max=1001) + if window > 0 + push!(steps, Dict{String,Any}("name" => "smoothing", + "params" => Dict{String,Any}("method" => "savitzky_golay", "window" => window, "order" => 2))) + end + baseline_it = opt_int(params, "baseline_iterations"; default=0, min=0, max=10_000) + if baseline_it > 0 + push!(steps, Dict{String,Any}("name" => "baseline_correction", + "params" => Dict{String,Any}("method" => "snip", "iterations" => baseline_it))) + end + norm = lowercase(String(_pget(params, "normalization", "none"))) + if norm in ("tic", "rms", "median") + push!(steps, Dict{String,Any}("name" => "normalization", + "params" => Dict{String,Any}("method" => norm))) + end + if opt_bool(params, "peak_picking"; default=true) + push!(steps, Dict{String,Any}("name" => "peak_picking", + "params" => Dict{String,Any}( + "method" => lowercase(String(_pget(params, "peak_method", "profile"))), + "snr_threshold" => Float64(opt_float(params, "snr_threshold"; default=3.0, min=0.0, max=1000.0)), + ))) + end + isempty(steps) && throw(invalid_params( + "The pipeline contains no steps."; + suggested_action="Provide `steps` or at least one of smoothing_window, baseline_iterations, normalization, peak_picking.")) + return steps +end + +function _preprocessing_params(params, data) + steps = _parse_steps(params) + return Dict{String,Any}( + "steps" => steps, + "num_bins" => opt_int(params, "num_bins"; default=2000, min=1, max=100_000), + "min_peaks_per_bin" => opt_int(params, "min_peaks_per_bin"; default=3, min=1, max=1_000_000), + "frequency_threshold" => opt_float(params, "frequency_threshold"; default=0.0, min=0.0, max=1.0), + "reference_peaks" => opt_float_vector(params, "reference_peaks"; default=Float64[], + min_len=0, max_len=100_000), + "mask_path" => validate_mask_path(params, data), + "include_matrix" => opt_bool(params, "include_matrix"; default=false), + "output_name" => safe_filename( + something(opt_string(params, "output_name"; default=nothing), "streaming_pipeline")), + ) +end + +# --------------------------------------------------------------------------- +# Planner entry points (shared by MCP tools and tests) +# --------------------------------------------------------------------------- + +function plan_ion_image(params) + data = require_data() + p = _ion_image_params(params, data; multiple=false) + note = pop!(p, "_verify") + rs = create_runspec(:ion_image, p, + "Ion image at m/z $(round(p["mass"], digits=5)) ± $(p["tolerance"]) Da") + payload = runspec_payload(rs) + payload["validation"] = note + payload["estimated_cost"] = "one full pass over the spectra (I/O bound); analytics may run on first use" + return payload +end + +function plan_multiple_slices(params) + data = require_data() + p = _ion_image_params(params, data; multiple=true) + note = pop!(p, "_verify") + rs = create_runspec(:multiple_slices, p, + "$(length(p["masses"])) ion images in a single I/O pass (± $(p["tolerance"]) Da)") + payload = runspec_payload(rs) + payload["validation"] = note + payload["estimated_cost"] = "one full pass over the spectra (hierarchy inversion; independent of the number of masses)" + return payload +end + +function plan_preprocessing(params) + data = require_data() + p = _preprocessing_params(params, data) + rs = create_runspec(:streaming_pipeline, p, + "Streaming preprocessing ($(length(p["steps"])) steps) -> sparse feature matrix ($(p["num_bins"]) bins)") + payload = runspec_payload(rs) + payload["estimated_cost"] = "one streaming pass; RAM bounded by threads × largest spectrum" + return payload +end + +function plan_analytics(params) + data = require_data() + p = Dict{String,Any}( + "include_rows" => opt_int(params, "include_rows"; default=20, min=0, max=5000), + "output_name" => safe_filename( + something(opt_string(params, "output_name"; default=nothing), "analytics")), + ) + rs = create_runspec(:analytics, p, "Per-spectrum analytics scan (TIC/BPI/min-max m/z + Bloom filters)") + payload = runspec_payload(rs) + payload["estimated_cost"] = "one full pass over the spectra; required before ion-image extraction" + return payload +end diff --git a/src/server.jl b/src/server.jl new file mode 100644 index 0000000..765fc9c --- /dev/null +++ b/src/server.jl @@ -0,0 +1,196 @@ +# src/server.jl +# --------------------------------------------------------------------------- +# MCP server assembly and entry points (stdio + Streamable HTTP). +# --------------------------------------------------------------------------- + +const SERVER_NAME = "juliamsi" +const SERVER_VERSION = "0.1.0" + +const SERVER_DESCRIPTION = """ +High-performance Mass Spectrometry Imaging engine (JuliaMSI) exposed through the +Model Context Protocol. Keeps an .imzML/.mzML dataset open between calls, plans +expensive work as immutable RunSpecs, executes it in background Julia tasks with +memory-mapped I/O, and returns compact statistics plus on-disk artifacts. +""" + +const ALL_TOOLS = MCPTool[ + OPEN_DATASET_TOOL, + CLOSE_DATASET_TOOL, + DATASET_INFO_TOOL, + DATASET_STATS_TOOL, + GET_SPECTRUM_TOOL, + GET_SPECTRUM_BY_INDEX_TOOL, + GET_MZ_SLICE_TOOL, + GET_MULTIPLE_SLICES_TOOL, + PLAN_ION_IMAGE_TOOL, + PLAN_MULTIPLE_SLICES_TOOL, + PLAN_PREPROCESSING_TOOL, + PLAN_STREAMING_PIPELINE_TOOL, + PLAN_ANALYTICS_TOOL, + EXECUTE_RUNSPEC_TOOL, + LIST_PLANS_TOOL, + TASK_STATUS_TOOL, + TASK_RESULT_TOOL, + CANCEL_TASK_TOOL, + LIST_TASKS_TOOL, + CLEAN_ARTIFACTS_TOOL, +] + +const ALL_RESOURCES = MCPResource[ + DATASET_METADATA_RESOURCE, + DATASET_STATS_RESOURCE, +] + +const ALL_RESOURCE_TEMPLATES = ResourceTemplate[ + TASK_STATUS_TEMPLATE, + TASK_RESULT_TEMPLATE, +] + +const ALL_PROMPTS = MCPPrompt[ + PROMPT_ANALYZE_REGION, + PROMPT_STANDARD_PIPELINE, + PROMPT_DIAGNOSE_TASK, +] + +"""Build (but do not start) the JuliaMSI MCP server.""" +function build_server() + return mcp_server( + name = SERVER_NAME, + version = SERVER_VERSION, + title = "JuliaMSI MCP", + description = SERVER_DESCRIPTION, + tools = ALL_TOOLS, + resources = ALL_RESOURCES, + resource_templates = ALL_RESOURCE_TEMPLATES, + prompts = ALL_PROMPTS, + ) +end + +""" + startup_maintenance() + +Run one-shot housekeeping before the server loop: apply the artifact retention +policy (age and size budgets from the environment). Errors are non-fatal. +""" +function startup_maintenance() + max_age_days, max_total_bytes = artifact_retention_config() + if max_age_days > 0 || max_total_bytes > 0 + try + summary = prune_artifacts!(max_age_days=max_age_days, max_total_bytes=max_total_bytes) + if summary["removed"] > 0 + println(stderr, "[juliamsi] pruned $(summary["removed"]) artifact dir(s), freed $(summary["freed_bytes"]) bytes") + end + catch e + @warn "Artifact pruning at startup failed" exception=(e, catch_backtrace()) + end + end + return nothing +end + +# --------------------------------------------------------------------------- +# Optional shared-token authentication for the HTTP transport. +# +# This is a single shared bearer token (not OAuth, not a substitute for TLS). +# Set JULIA_MSI_MCP_TOKEN (or pass `--token`) to require +# `Authorization: Bearer ` on every HTTP request. +# --------------------------------------------------------------------------- + +struct SharedTokenValidator <: ModelContextProtocol.TokenValidator + token::String +end + +function _secure_equals(a::AbstractString, b::AbstractString) + ba, bb = codeunits(a), codeunits(b) + length(ba) == length(bb) || return false + diff = 0x00 + @inbounds for i in eachindex(ba) + diff |= ba[i] ⊻ bb[i] + end + return diff == 0x00 +end + +function ModelContextProtocol.validate_token(validator::SharedTokenValidator, + token::AbstractString, + ::ModelContextProtocol.OAuthConfig) + if _secure_equals(validator.token, token) + return ModelContextProtocol.AuthResult(ModelContextProtocol.AuthenticatedUser( + subject="shared-token", provider="static")) + end + return ModelContextProtocol.AuthResult("Invalid token", :invalid_token) +end + +function _http_auth(token::Union{Nothing,AbstractString}) + (token === nothing || isempty(strip(String(token)))) && return nothing + config = ModelContextProtocol.OAuthConfig(issuer="juliamsi", audience="juliamsi") + return ModelContextProtocol.AuthMiddleware(config=config, + validator=SharedTokenValidator(String(token))) +end + +""" + install_output_guard() + +Send all further writes to the process-global `stdout` to `stderr`, and return +the original stdout handle. The JuliaMSI engine (and some Julia packages) print +debug/progress lines with `println`; on the MCP stdio transport those bytes would +corrupt the JSON-RPC framing. The transport keeps writing to the saved handle. +""" +function install_output_guard() + real_stdout = stdout + if get(ENV, "JULIA_MSI_MCP_KEEP_STDOUT", "0") != "1" + redirect_stdout(stderr) + end + return real_stdout +end + +""" + run_stdio(; server=build_server()) + +Run the server over stdio (Claude Desktop, VS Code, any local MCP client). +Blocks until stdin is closed. +""" +function run_stdio(; server=build_server()) + real_stdout = install_output_guard() + transport = StdioTransport(input=stdin, output=real_stdout) + startup_maintenance() + println(stderr, "[juliamsi] starting MCP server over stdio (Julia $(VERSION), $(Base.Threads.nthreads()) threads)") + try + start!(server; transport=transport) + finally + try + close_dataset() + catch e + @warn "Cleanup on shutdown failed" exception=(e, catch_backtrace()) + end + println(stderr, "[juliamsi] server stopped") + end + return nothing +end + +""" + run_http(; host="127.0.0.1", port=3000, token=nothing, server=build_server()) + +Run the server over the MCP Streamable HTTP transport. When `token` (or +`JULIA_MSI_MCP_TOKEN`) is set, every request must send `Authorization: Bearer +`. Put a TLS reverse proxy in front for anything beyond localhost. +""" +function run_http(; host::AbstractString="127.0.0.1", port::Integer=3000, + token::Union{Nothing,AbstractString}=nothing, server=build_server()) + token = something(token, get(ENV, "JULIA_MSI_MCP_TOKEN", nothing)) + auth = _http_auth(token) + transport = HttpTransport(host=String(host), port=Int(port), auth=auth) + startup_maintenance() + println(stderr, "[juliamsi] starting MCP Streamable HTTP server on http://$(host):$(port)", + auth === nothing ? "" : " (shared-token auth enabled)") + connect(transport) + try + start!(server; transport=transport) + finally + try + close_dataset() + catch e + @warn "Cleanup on shutdown failed" exception=(e, catch_backtrace()) + end + println(stderr, "[juliamsi] server stopped") + end + return nothing +end diff --git a/src/session.jl b/src/session.jl new file mode 100644 index 0000000..2433e22 --- /dev/null +++ b/src/session.jl @@ -0,0 +1,354 @@ +# src/session.jl +# --------------------------------------------------------------------------- +# Persistent JuliaMSI session. +# +# The whole point of running the MCP server inside a Julia process is to keep +# the (potentially very large) MSIData object alive between tool calls. Opening +# an imzML file costs seconds; querying a spectrum afterwards costs +# microseconds. This file owns that lifecycle. +# --------------------------------------------------------------------------- + +""" + SessionState + +Mutable, process-global MCP session. Only one dataset is open at a time (the +JuliaMSI engine is built around a single `MSIData`); call `open_dataset` again +to switch datasets, which closes and cleans the previous one. +""" +mutable struct SessionState + data::Union{Nothing,MSI_src.MSIData} + path::Union{Nothing,String} + dataset_id::Union{Nothing,String} + opened_at::Union{Nothing,Float64} + last_access::Float64 + cache_size::Int + use_mmap::Bool + xml_bytes::Int64 + ibd_bytes::Int64 + lock::ReentrantLock +end + +SessionState() = SessionState(nothing, nothing, nothing, nothing, 0.0, 300, + true, 0, 0, ReentrantLock()) + +const SESSION = SessionState() +const CLEANUP_LOCK = ReentrantLock() + +# --------------------------------------------------------------------------- +# OS-level memory release (compendium A.12) +# --------------------------------------------------------------------------- + +""" + release_os_memory!(; full::Bool=true) + +Ask Julia's GC to collect and, on glibc/Linux, ask `malloc_trim(0)` to return +free arena pages to the kernel. Without `malloc_trim`, RSS stays inflated after +closing a multi-gigabyte dataset even though Julia has freed the objects. + +Safe to call at any time; failures (musl, non-glibc, Windows, macOS) are +silently ignored. +""" +function release_os_memory!(; full::Bool=true) + lock(CLEANUP_LOCK) do + try + GC.gc(full) + catch + end + if Sys.islinux() + try + ccall(:malloc_trim, Cint, (Cint,), 0) + catch + # musl libc (Alpine) has no malloc_trim; nothing to do. + end + end + end + return nothing +end + +# --------------------------------------------------------------------------- +# Dataset identity +# --------------------------------------------------------------------------- + +function _file_signature(path::String) + isfile(path) || return (0, 0.0) + st = stat(path) + return (Int64(st.size), Float64(st.mtime)) +end + +""" + dataset_id_for(path) + +Content-ish identity of a dataset: path, XML size/mtime and IBD size/mtime. +Plans are bound to this id so a RunSpec cannot silently run against a different +file after the user opens another dataset. +""" +function dataset_id_for(path::String) + xml_size, xml_mtime = _file_signature(path) + ibd_path = replace(path, r"\.(imzML|mzML)"i => ".ibd") + ibd_size, ibd_mtime = _file_signature(ibd_path) + material = string(path, "|", xml_size, "|", xml_mtime, "|", ibd_size, "|", ibd_mtime) + return short_hash(material, 16) +end + +# --------------------------------------------------------------------------- +# Open / close +# --------------------------------------------------------------------------- + +"""Validate the file and return `(absolute_path, extension, ibd_path_or_nothing)`.""" +function _validate_dataset_path(file_path::AbstractString) + isempty(strip(String(file_path))) && throw(invalid_params("`file_path` is empty.")) + path = abspath(expanduser(String(file_path))) + isfile(path) || throw(invalid_params( + "Dataset file not found: $(path)"; + suggested_action="Pass an absolute path to an existing .imzML or .mzML file.", + details=Dict("path" => path), + )) + ext = lowercase(splitext(path)[2]) + ext in (".imzml", ".mzml") || throw(invalid_params( + "Unsupported dataset extension '$(ext)' for $(path). Supported: .imzML, .mzML."; + suggested_action="Convert the file to .imzML (with its .ibd pair) or .mzML.", + )) + ibd = nothing + if ext == ".imzml" + ibd = replace(path, r"\.imzML"i => ".ibd") + isfile(ibd) || throw(invalid_params( + "The .ibd binary file paired with $(path) was not found: $(ibd)"; + suggested_action="Keep the .imzML and .ibd files together with the same basename.", + details=Dict("expected_ibd" => ibd), + )) + end + return path, ext, ibd +end + +""" + open_dataset(file_path; cache_size=300, use_mmap=true, precompute_analytics=false) + +Open (or switch) the active dataset and return its metadata summary. +""" +function open_dataset(file_path::AbstractString; + cache_size::Integer=300, + use_mmap::Bool=true, + precompute_analytics::Bool=false) + path, ext, ibd = _validate_dataset_path(file_path) + cache_size = clamp(Int(cache_size), 0, 100_000) + + return lock(SESSION.lock) do + t0 = time_ns() + if SESSION.data !== nothing + _close_locked!() + end + + data = if ext == ".imzml" + MSI_src.load_imzml_lazy(path; cache_size=cache_size, use_mmap=use_mmap) + else + MSI_src.load_mzml_lazy(path; cache_size=cache_size) + end + + if precompute_analytics + MSI_src.precompute_analytics(data) + end + + xml_size, _ = _file_signature(path) + ibd_size, _ = ibd === nothing ? (0, 0.0) : _file_signature(ibd) + + SESSION.data = data + SESSION.path = path + SESSION.dataset_id = dataset_id_for(path) + SESSION.opened_at = time() + SESSION.last_access = time() + SESSION.cache_size = cache_size + SESSION.use_mmap = use_mmap + SESSION.xml_bytes = xml_size + SESSION.ibd_bytes = ibd_size + + meta = _metadata_locked(data) + meta["open_seconds"] = compact_float((time_ns() - t0) / 1e9) + meta["cache_file"] = isfile(path * ".cache") ? path * ".cache" : nothing + return meta + end +end + +"""Close the active dataset without acquiring the lock (internal).""" +function _close_locked!() + if SESSION.data !== nothing + try + Base.close(SESSION.data) + catch e + @warn "Error while closing MSIData" exception=(e, catch_backtrace()) + end + end + SESSION.data = nothing + SESSION.path = nothing + SESSION.dataset_id = nothing + SESSION.opened_at = nothing + SESSION.last_access = time() + SESSION.xml_bytes = 0 + SESSION.ibd_bytes = 0 + return nothing +end + +""" + close_dataset() + +Close the open dataset, drop every reference and return memory to the OS. +""" +function close_dataset() + summary = lock(SESSION.lock) do + info = session_metadata() + _close_locked!() + return info + end + release_os_memory!(full=true) + return summary +end + +# --------------------------------------------------------------------------- +# Access helpers +# --------------------------------------------------------------------------- + +"""Return the active `MSIData` or throw a structured session error.""" +function require_data() + data = lock(SESSION.lock) do + SESSION.data + end + data === nothing && throw(session_error( + "No dataset is open in this MCP session."; + suggested_action="Call msi_open_dataset with the path to an .imzML or .mzML file first.", + )) + SESSION.last_access = time() + return data +end + +"""Return the active dataset id, or `nothing`.""" +active_dataset_id() = lock(SESSION.lock) do + SESSION.dataset_id +end + +has_open_dataset() = lock(SESSION.lock) do + SESSION.data !== nothing +end + +"""Ensure per-spectrum analytics (TIC/BPI/min/max + Bloom filters) are computed.""" +function ensure_analytics!(data::MSI_src.MSIData) + MSI_src.is_set(data.analytics_ready) && return 0.0 + t0 = time_ns() + MSI_src.precompute_analytics(data) + return (time_ns() - t0) / 1e9 +end + +# --------------------------------------------------------------------------- +# Metadata +# --------------------------------------------------------------------------- + +function _source_info(data::MSI_src.MSIData) + src = data.source + if src isa MSI_src.ImzMLSource + return Dict{String,Any}( + "type" => "imzML", + "mz_format" => string(src.mz_format), + "intensity_format" => string(src.intensity_format), + "compressed" => src.is_any_compressed, + "mmap_active" => src.mmap_data !== nothing, + "open_handles" => length(src.ibd_handles), + ) + elseif src isa MSI_src.MzMLSource + return Dict{String,Any}( + "type" => "mzML", + "mz_format" => string(src.mz_format), + "intensity_format" => string(src.intensity_format), + "compressed" => false, + "mmap_active" => src.mmap_data !== nothing, + "open_handles" => length(src.file_handles), + ) + end + return Dict{String,Any}("type" => string(typeof(src))) +end + +function _instrument_info(data::MSI_src.MSIData) + im = data.instrument_metadata + im === nothing && return nothing + return Dict{String,Any}( + "instrument_model" => im.instrument_model, + "resolution" => im.resolution, + "mass_accuracy_ppm" => im.mass_accuracy_ppm, + "polarity" => im.polarity, + "calibration_status" => im.calibration_status, + "acquisition_mode" => im.acquisition_mode, + "mz_axis_type" => im.mz_axis_type, + "laser_settings" => im.laser_settings, + "vendor_preprocessing_steps" => im.vendor_preprocessing_steps, + ) +end + +function _metadata_locked(data::MSI_src.MSIData) + min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0) + max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0) + mz_range = (min_mz < max_mz && isfinite(min_mz) && isfinite(max_mz)) ? + Any[compact_float(min_mz), compact_float(max_mz)] : nothing + + width, height = data.image_dims + cached = try + lock(data.cache_lock) do + length(data.cache) + end + catch + 0 + end + + return Dict{String,Any}( + "open" => true, + "path" => SESSION.path, + "dataset_id" => SESSION.dataset_id, + "num_spectra" => length(data.spectra_metadata), + "image_dims" => Any[width, height], + "coordinate_map" => data.coordinate_map !== nothing, + "mz_range" => mz_range, + "analytics_ready" => MSI_src.is_set(data.analytics_ready), + "cache_size" => SESSION.cache_size, + "cached_spectra" => cached, + "use_mmap" => SESSION.use_mmap, + "file_bytes" => Dict{String,Any}("xml" => SESSION.xml_bytes, "ibd" => SESSION.ibd_bytes), + "source" => _source_info(data), + "instrument" => _instrument_info(data), + "opened_at" => SESSION.opened_at === nothing ? nothing : Dates.format(Dates.unix2datetime(SESSION.opened_at), "yyyy-mm-ddTHH:MM:SS"), + "uptime_seconds" => SESSION.opened_at === nothing ? nothing : compact_float(time() - SESSION.opened_at), + "process" => Dict{String,Any}( + "julia_version" => string(VERSION), + "threads" => Base.Threads.nthreads(), + "pid" => getpid(), + "rss_mb" => _rss_mb(), + ), + ) +end + +function _rss_mb() + try + for line in eachline("/proc/$(getpid())/status") + startswith(line, "VmRSS:") || continue + parts = split(line) + length(parts) >= 2 || continue + return round(parse(Float64, parts[2]) / 1024, digits=1) + end + catch + end + return nothing +end + +"""Public, lock-safe metadata snapshot (returns `open=false` when idle).""" +function session_metadata() + return lock(SESSION.lock) do + if SESSION.data === nothing + return Dict{String,Any}( + "open" => false, + "hint" => "Call msi_open_dataset to load an .imzML or .mzML dataset.", + "process" => Dict{String,Any}( + "julia_version" => string(VERSION), + "threads" => Base.Threads.nthreads(), + "pid" => getpid(), + "rss_mb" => _rss_mb(), + ), + ) + end + _metadata_locked(SESSION.data) + end +end diff --git a/src/tasks.jl b/src/tasks.jl new file mode 100644 index 0000000..bfca4bb --- /dev/null +++ b/src/tasks.jl @@ -0,0 +1,610 @@ +# src/tasks.jl +# --------------------------------------------------------------------------- +# Execution layer: background tasks + polling. +# +# `msi_execute_runspec` never blocks the JSON-RPC loop. It spawns a Julia Task +# on the thread pool and returns a task_id immediately. The client polls +# `msi_get_task_status` and finally fetches `msi_get_task_result` (or reads the +# matching MCP resource). +# --------------------------------------------------------------------------- + +mutable struct EngineTask + id::String + runspec_id::String + kind::Symbol + dataset_id::String + status::Symbol # :queued | :running | :completed | :failed | :cancelled + progress::Float64 + message::String + created_at::Float64 + started_at::Union{Nothing,Float64} + finished_at::Union{Nothing,Float64} + result::Union{Nothing,Dict{String,Any}} + error::Union{Nothing,Dict{String,Any}} + cancel_requested::Bool + task::Union{Nothing,Task} +end + +const TASK_LOCK = ReentrantLock() +const TASKS = Dict{String,EngineTask}() +const TASK_ORDER = String[] +const MAX_TASKS = 64 + +is_terminal(status::Symbol) = status in (:completed, :failed, :cancelled) + +# --------------------------------------------------------------------------- +# Registry helpers +# --------------------------------------------------------------------------- + +function _update_task!(f::Function, task::EngineTask) + lock(TASK_LOCK) do + f(task) + end + return task +end + +function _finish_task!(task::EngineTask, status::Symbol; + result=nothing, error=nothing, message=nothing) + _update_task!(task) do t + t.status = status + t.finished_at = time() + t.progress = status == :completed ? 1.0 : t.progress + result !== nothing && (t.result = result) + error !== nothing && (t.error = error) + message !== nothing && (t.message = message) + end + return task +end + +function _prune_tasks!() + # Called while holding TASK_LOCK. + while length(TASK_ORDER) > MAX_TASKS + idx = findfirst(id -> begin + t = get(TASKS, id, nothing) + t === nothing || is_terminal(t.status) + end, TASK_ORDER) + idx === nothing && break + id = TASK_ORDER[idx] + deleteat!(TASK_ORDER, idx) + pop!(TASKS, id, nothing) + end +end + +function get_task(task_id::AbstractString) + lock(TASK_LOCK) do + t = get(TASKS, String(task_id), nothing) + t === nothing && throw(invalid_params( + "Unknown task_id: $(task_id)"; + suggested_action="Use msi_list_tasks to see recent tasks. Task records are pruned after 64 newer tasks.")) + return t + end +end + +function list_tasks(; limit::Integer=20, status::Union{Nothing,AbstractString}=nothing) + lock(TASK_LOCK) do + ids = reverse(TASK_ORDER) + out = EngineTask[] + wanted = status === nothing ? nothing : Symbol(status) + for id in ids + t = get(TASKS, id, nothing) + t === nothing && continue + wanted !== nothing && t.status != wanted && continue + push!(out, t) + length(out) >= Int(limit) && break + end + return out + end +end + +# --------------------------------------------------------------------------- +# Public status/result payloads +# --------------------------------------------------------------------------- + +function _duration(t::EngineTask) + t.started_at === nothing && return nothing + stop = t.finished_at === nothing ? time() : t.finished_at + return compact_float(stop - t.started_at) +end + +function task_status_payload(t::EngineTask; include_summary::Bool=true) + payload = Dict{String,Any}( + "task_id" => t.id, + "runspec_id" => t.runspec_id, + "kind" => string(t.kind), + "status" => string(t.status), + "progress" => compact_float(t.progress), + "message" => t.message, + "created_at" => Dates.format(Dates.unix2datetime(t.created_at), "yyyy-mm-ddTHH:MM:SS"), + "started_at" => t.started_at === nothing ? nothing : Dates.format(Dates.unix2datetime(t.started_at), "yyyy-mm-ddTHH:MM:SS"), + "finished_at" => t.finished_at === nothing ? nothing : Dates.format(Dates.unix2datetime(t.finished_at), "yyyy-mm-ddTHH:MM:SS"), + "duration_seconds" => _duration(t), + "cancel_requested" => t.cancel_requested, + "result_ready" => t.status == :completed && t.result !== nothing, + ) + if t.error !== nothing + payload["error"] = t.error + end + if include_summary && t.status == :completed && t.result !== nothing + payload["result_summary"] = result_summary(t.result) + end + return payload +end + +"""Short version of a result, safe to embed in status polling responses.""" +function result_summary(result::Dict{String,Any}) + summary = Dict{String,Any}() + for key in ("kind", "mass", "tolerance", "shape", "stats", "num_slices", + "matrix_shape", "nonzeros", "density", "artifacts", "analytics", "note") + haskey(result, key) && (summary[key] = result[key]) + end + return summary +end + +function task_result_payload(t::EngineTask) + if t.status == :completed + return t.result === nothing ? Dict{String,Any}("task_id" => t.id, "status" => string(t.status)) : + merge(Dict{String,Any}("task_id" => t.id, "status" => string(t.status)), t.result) + elseif t.status == :failed + return Dict{String,Any}( + "task_id" => t.id, + "status" => string(t.status), + "error" => t.error === nothing ? Dict{String,Any}("message" => "Unknown failure") : t.error, + "hint" => "Use msi_get_task_status for the timeline, or re-plan with smaller parameters.", + ) + elseif t.status == :cancelled + return Dict{String,Any}("task_id" => t.id, "status" => string(t.status), + "message" => t.message) + end + payload = task_status_payload(t; include_summary=false) + payload["hint"] = "Task is still in progress. Poll msi_get_task_status, then retry msi_get_task_result." + return payload +end + +# --------------------------------------------------------------------------- +# Cancellation / waiting +# --------------------------------------------------------------------------- + +function cancel_task(task_id::AbstractString) + t = get_task(task_id) + lock(TASK_LOCK) do + if t.status in (:queued, :running) + t.cancel_requested = true + t.message = "cancellation requested" + if t.status == :queued + t.status = :cancelled + t.finished_at = time() + end + end + return task_status_payload(t; include_summary=false) + end +end + +_cancelled(t::EngineTask) = lock(TASK_LOCK) do + t.cancel_requested +end + +function wait_for_task(t::EngineTask; timeout::Real=0.0) + timeout <= 0 && return t + deadline = time() + Float64(timeout) + while time() < deadline + done = lock(TASK_LOCK) do + is_terminal(t.status) + end + done && break + sleep(0.05) + end + return t +end + +# --------------------------------------------------------------------------- +# Execution +# --------------------------------------------------------------------------- + +function submit_runspec(rs::RunSpec; force::Bool=false, wait_seconds::Real=0.0) + check_runspec_dataset(rs) + + local task::EngineTask + local reused::Bool + lock(TASK_LOCK) do + reused = false + if !force + for id in reverse(TASK_ORDER) + t = get(TASKS, id, nothing) + t === nothing && continue + if t.runspec_id == rs.id && t.dataset_id == rs.dataset_id && + t.status in (:queued, :running, :completed) + task = t + reused = true + break + end + end + end + if !reused + task = EngineTask( + string(uuid4()), rs.id, rs.kind, rs.dataset_id, + :queued, 0.0, "queued", time(), nothing, nothing, + nothing, nothing, false, nothing, + ) + TASKS[task.id] = task + push!(TASK_ORDER, task.id) + _prune_tasks!() + task.task = Base.Threads.@spawn _execute_task!(task, rs) + end + end + + wait_seconds > 0 && wait_for_task(task; timeout=wait_seconds) + payload = task_status_payload(task) + payload["reused"] = reused + return payload +end + +function _execute_task!(task::EngineTask, rs::RunSpec) + cancelled_before_start = lock(TASK_LOCK) do + if task.cancel_requested + task.status = :cancelled + task.finished_at = time() + task.message = "cancelled before start" + true + else + task.status = :running + task.started_at = time() + task.message = "starting $(rs.kind)" + task.progress = 0.01 + false + end + end + cancelled_before_start && return nothing + + try + _cancelled(task) && throw(InterruptException()) + data = require_data() + check_runspec_dataset(rs) + + result = _dispatch_runspec(rs, task, data) + + if _cancelled(task) + _finish_task!(task, :cancelled; message="cancelled before completion") + else + _finish_task!(task, :completed; result=result, message="completed") + end + catch e + if _cancelled(task) || e isa InterruptException + _finish_task!(task, :cancelled; message="cancelled") + else + @error "RunSpec execution failed" task_id=task.id runspec=rs.id exception=(e, catch_backtrace()) + _finish_task!(task, :failed; error=error_payload(e; context=Dict{String,Any}( + "task_id" => task.id, "runspec_id" => rs.id, "kind" => string(rs.kind))), + message=sprint(showerror, e)) + end + finally + if rs.kind in (:streaming_pipeline, :analytics) + release_os_memory!(full=false) + end + end + return nothing +end + +function _set_progress!(task::EngineTask, progress::Real, message::AbstractString) + _update_task!(task) do t + t.progress = clamp(Float64(progress), 0.0, 1.0) + t.message = String(message) + end +end + +function _dispatch_runspec(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData) + if rs.kind == :ion_image + return _run_ion_image(rs, task, data) + elseif rs.kind == :multiple_slices + return _run_multiple_slices(rs, task, data) + elseif rs.kind == :streaming_pipeline + return _run_streaming_pipeline(rs, task, data) + elseif rs.kind == :analytics + return _run_analytics(rs, task, data) + end + throw(internal_error("Unimplemented RunSpec kind: $(rs.kind)")) +end + +# --------------------------------------------------------------------------- +# Kind-specific executors +# --------------------------------------------------------------------------- + +function _matrix_rows(mat::AbstractMatrix{<:Real}) + return Any[Any[compact_float(Float64(mat[y, x])) for x in 1:size(mat, 2)] + for y in 1:size(mat, 1)] +end + +function _analytics_seconds(data, task, stage::AbstractString) + if MSI_src.is_set(data.analytics_ready) + return 0.0 + end + _set_progress!(task, 0.03, "computing per-spectrum analytics ($(stage))") + return ensure_analytics!(data) +end + +function _run_ion_image(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData) + p = rs.params + mass = Float64(p["mass"]) + tolerance = Float64(p["tolerance"]) + mask_path = p["mask_path"] + + analytics_s = _analytics_seconds(data, task, "ion image") + _cancelled(task) && throw(InterruptException()) + + _set_progress!(task, 0.45, "extracting ion image at m/z $(mass) ± $(tolerance)") + mat = MSI_src.get_mz_slice(data, mass, tolerance; mask_path=mask_path) + analytics_s += 0.0 + + _cancelled(task) && throw(InterruptException()) + _set_progress!(task, 0.80, "writing ion image artifacts") + label = safe_filename("ion_mz_" * string(round(mass, digits=4))) + dir = artifact_dir(task.id; label=p["output_name"]) + extra = Dict{String,Any}( + "mass" => mass, "tolerance" => tolerance, "mask_path" => mask_path, + "dataset_id" => rs.dataset_id, "runspec_id" => rs.id, + ) + artifacts = persist_ion_image(dir, label, mat; extra=extra) + + result = Dict{String,Any}( + "kind" => "ion_image", + "mass" => mass, + "tolerance" => tolerance, + "mask_path" => mask_path, + "shape" => Any[size(mat, 2), size(mat, 1)], + "stats" => matrix_stats(mat), + "preview" => preview_matrix(mat; max_dim=Int(p["preview_max_dim"])), + "artifacts" => artifacts, + "analytics_seconds" => compact_float(analytics_s), + "dataset_id" => rs.dataset_id, + "runspec_id" => rs.id, + ) + if p["include_matrix"] && length(mat) <= 250_000 + result["matrix"] = _matrix_rows(mat) + elseif p["include_matrix"] + result["note"] = "include_matrix was requested but the matrix has $(length(mat)) pixels; read the CSV artifact instead." + end + _set_progress!(task, 0.98, "finalizing") + return result +end + +function _run_multiple_slices(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData) + p = rs.params + masses = Float64.(p["masses"]) + tolerance = Float64(p["tolerance"]) + mask_path = p["mask_path"] + include_matrix = Bool(p["include_matrix"]) + preview_dim = Int(p["preview_max_dim"]) + max_artifacts = 100 + + analytics_s = _analytics_seconds(data, task, "multiple slices") + _cancelled(task) && throw(InterruptException()) + + _set_progress!(task, 0.35, "extracting $(length(masses)) ion images in one pass") + slice_dict = MSI_src.get_multiple_mz_slices(data, masses, tolerance; mask_path=mask_path) + + _set_progress!(task, 0.75, "writing artifacts") + dir = artifact_dir(task.id; label=p["output_name"]) + + sorted_masses = sort(unique(masses)) + slices = Dict{String,Any}[] + summary_rows = Tuple{Float64,Int,Float64,Float64,Int,Union{Nothing,Vector{Float64}}}[] + for (i, mass) in enumerate(sorted_masses) + mat = get(slice_dict, mass, nothing) + if mat === nothing + mat = get(slice_dict, Float64(mass), nothing) + end + mat === nothing && continue + st = matrix_stats(mat) + entry = Dict{String,Any}( + "mass" => mass, + "stats" => st, + ) + if i <= max_artifacts + label = safe_filename("ion_mz_" * string(round(mass, digits=4))) + entry["artifacts"] = persist_ion_image(dir, label, mat; + extra=Dict{String,Any}("mass" => mass, "tolerance" => tolerance, + "dataset_id" => rs.dataset_id, "runspec_id" => rs.id)) + end + if i <= 8 + entry["preview"] = preview_matrix(mat; max_dim=preview_dim) + end + push!(slices, entry) + push!(summary_rows, (mass, length(mat), st["max"], st["mean"], st["nonzero"], st["base_peak_coord"])) + end + + # One CSV with all per-mass stats is cheap and always written. + summary_csv = joinpath(dir, "slices_summary.csv") + open(summary_csv, "w") do io + println(io, "mass,pixels,max,mean,nonzero,base_peak_x,base_peak_y") + for (mass, npix, mx, mn, nz, bp) in summary_rows + bx = bp === nothing ? "" : bp[1] + by = bp === nothing ? "" : bp[2] + println(io, mass, ",", npix, ",", mx, ",", mn, ",", nz, ",", bx, ",", by) + end + end + + result = Dict{String,Any}( + "kind" => "multiple_slices", + "tolerance" => tolerance, + "mask_path" => mask_path, + "num_slices" => length(slices), + "slices" => slices, + "artifacts" => Dict{String,Any}( + "summary_csv" => artifact_record(summary_csv), + "directory" => dir, + ), + "artifacts_written_for" => min(length(slices), max_artifacts), + "analytics_seconds" => compact_float(analytics_s), + "dataset_id" => rs.dataset_id, + "runspec_id" => rs.id, + ) + if include_matrix && !isempty(slices) && length(slices) <= 16 + result["matrices"] = [Dict{String,Any}( + "mass" => s["mass"], + "rows" => _matrix_rows(get(slice_dict, s["mass"], zeros(Float32, 0, 0))), + ) for s in slices] + end + _set_progress!(task, 0.98, "finalizing") + return result +end + +"""Convert JSON step params into the `Dict{Symbol,Any}` shape the engine expects.""" +function _engine_step_params(params::Dict{String,Any}) + out = Dict{Symbol,Any}() + for (k, v) in params + key = Symbol(k) + if key in (:method, :peak_method, :calibration_method) && v isa AbstractString + out[key] = Symbol(v) + elseif v isa AbstractString && key in (:mode, :type) + out[key] = Symbol(v) + elseif v isa Bool || v isa Real || v isa AbstractString + out[key] = v + elseif v isa AbstractDict + out[key] = Dict{Symbol,Any}(Symbol(kk) => vv for (kk, vv) in v) + else + out[key] = v + end + end + return out +end + +function _run_streaming_pipeline(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData) + p = rs.params + steps = MSI_src.StreamingStep[] + for s in p["steps"] + push!(steps, MSI_src.StreamingStep(Symbol(s["name"]), + _engine_step_params(Dict{String,Any}(s["params"])))) + end + config = MSI_src.PipelineConfig( + steps = steps, + reference_peaks = Float64.(p["reference_peaks"]), + num_bins = Int(p["num_bins"]), + min_peaks_per_bin = Int(p["min_peaks_per_bin"]), + frequency_threshold = Float64(p["frequency_threshold"]), + ) + + masked_indices = nothing + if p["mask_path"] !== nothing + _set_progress!(task, 0.05, "preparing ROI mask") + width, height = data.image_dims + mask_matrix = MSI_src.load_and_prepare_mask(String(p["mask_path"]), (width, height)) + masked_indices = collect(MSI_src.get_masked_spectrum_indices(data, mask_matrix)) + isempty(masked_indices) && throw(invalid_params( + "The ROI mask selects zero spectra."; suggested_action="Check the mask orientation and threshold.")) + end + + _cancelled(task) && throw(InterruptException()) + _set_progress!(task, 0.15, "streaming $(length(steps)) kernel steps over $(length(data.spectra_metadata)) spectra") + feature_matrix, bin_centers = MSI_src.process_dataset!(data, config; + progress_callback = frac -> _set_progress!(task, 0.15 + 0.65 * Float64(frac), + "streaming pass $(round(Int, 100 * frac))%"), + masked_indices = masked_indices) + + _cancelled(task) && throw(InterruptException()) + _set_progress!(task, 0.85, "writing feature matrix artifacts") + dir = artifact_dir(task.id; label=p["output_name"]) + mtx = write_sparse_mtx(joinpath(dir, "feature_matrix.mtx"), feature_matrix) + bins_csv = write_vector_csv(joinpath(dir, "bin_centers.csv"), bin_centers; + header="bin,mz") + + rows, cols = size(feature_matrix) + nnz_val = SparseArrays.nnz(feature_matrix) + density = rows * cols == 0 ? 0.0 : nnz_val / (rows * cols) + processed = masked_indices === nothing ? cols : length(masked_indices) + result = Dict{String,Any}( + "kind" => "streaming_pipeline", + "matrix_shape" => Any[rows, cols], + "nonzeros" => nnz_val, + "density" => compact_float(density), + "num_bins_requested" => Int(p["num_bins"]), + "num_bins_kept" => rows, + "steps" => p["steps"], + "mask_path" => p["mask_path"], + "num_spectra_total" => cols, + "num_spectra_processed" => processed, + "bin_mz_range" => isempty(bin_centers) ? nothing : + Any[compact_float(first(bin_centers)), compact_float(last(bin_centers))], + "top_bins" => top_bins(feature_matrix, bin_centers; n=20), + "artifacts" => Dict{String,Any}( + "matrix_mtx" => mtx, + "bin_centers_csv" => bins_csv, + "directory" => dir, + ), + "dataset_id" => rs.dataset_id, + "runspec_id" => rs.id, + ) + if masked_indices !== nothing + result["note"] = "Masked run: $(processed) of $(cols) spectra were processed; columns outside the ROI are all-zero." + end + if p["include_matrix"] && nnz_val <= 20_000 + I, J, V = SparseArrays.findnz(feature_matrix) + result["sparse_triplets"] = Dict{String,Any}( + "rows" => collect(Int, I), "cols" => collect(Int, J), + "values" => [compact_float(v) for v in V], + ) + end + _set_progress!(task, 0.98, "finalizing") + return result +end + +function _run_analytics(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData) + p = rs.params + _set_progress!(task, 0.05, "scanning spectra (TIC, BPI, m/z bounds, Bloom filters)") + elapsed = ensure_analytics!(data) + _set_progress!(task, 0.85, "summarizing statistics") + + stats_df = MSI_src.get_spectrum_stats(data) + dir = artifact_dir(task.id; label=p["output_name"]) + csv_path = joinpath(dir, "spectrum_stats.csv") + stats_df === nothing || CSV.write(csv_path, stats_df) + + summary = Dict{String,Any}() + rows = Any[] + if stats_df !== nothing + for col in ("TIC", "BPI", "NumPoints") + v = Float64.(stats_df[!, col]) + summary[col] = Dict{String,Any}( + "min" => compact_float(minimum(v)), + "max" => compact_float(maximum(v)), + "mean" => compact_float(Statistics.mean(v)), + "median" => compact_float(Statistics.median(v)), + "sum" => compact_float(sum(v)), + ) + end + summary["base_peak_mz_range"] = Any[ + compact_float(minimum(stats_df[!, "BasePeakMZ"])), + compact_float(maximum(stats_df[!, "BasePeakMZ"])), + ] + n = min(Int(p["include_rows"]), nrow(stats_df)) + for i in 1:n + push!(rows, Dict{String,Any}( + "spectrum_id" => Int(stats_df[i, "SpectrumID"]), + "tic" => compact_float(stats_df[i, "TIC"]), + "bpi" => compact_float(stats_df[i, "BPI"]), + "base_peak_mz" => compact_float(stats_df[i, "BasePeakMZ"]), + "num_points" => Int(stats_df[i, "NumPoints"]), + "min_mz" => compact_float(stats_df[i, "MinMZ"]), + "max_mz" => compact_float(stats_df[i, "MaxMZ"]), + "mode" => string(stats_df[i, "Mode"]), + )) + end + end + + min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0) + max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0) + result = Dict{String,Any}( + "kind" => "analytics", + "elapsed_seconds" => compact_float(elapsed), + "num_spectra" => length(data.spectra_metadata), + "mz_range" => Any[compact_float(min_mz), compact_float(max_mz)], + "aggregate" => summary, + "rows" => rows, + "artifacts" => Dict{String,Any}( + "spectrum_stats_csv" => stats_df === nothing ? nothing : artifact_record(csv_path), + "directory" => dir, + ), + "dataset_id" => rs.dataset_id, + "runspec_id" => rs.id, + ) + _set_progress!(task, 0.98, "finalizing") + return result +end diff --git a/src/tools/dataset.jl b/src/tools/dataset.jl new file mode 100644 index 0000000..0f46262 --- /dev/null +++ b/src/tools/dataset.jl @@ -0,0 +1,153 @@ +# src/tools/dataset.jl +# --------------------------------------------------------------------------- +# Dataset lifecycle tools (synchronous, cheap). +# --------------------------------------------------------------------------- + +const _OPEN_DATASET_SCHEMA = object_schema(Dict{String,Any}( + "file_path" => prop("string", + "Absolute path to the .imzML file (its .ibd companion must exist) or to a .mzML file."), + "cache_size" => prop("integer", + "Number of spectra kept in the LRU cache for random access. Default 300.", + default=300, minimum=0, maximum=100000), + "use_mmap" => prop("boolean", + "Memory-map the .ibd file and hint MADV_SEQUENTIAL to the Linux kernel. Default true.", + default=true), + "precompute_analytics" => prop("boolean", + "Run the per-spectrum analytics scan immediately (TIC/BPI/mz bounds + Bloom filters). " * + "Set false to open fast and defer the scan to the first extraction. Default false.", + default=false), +); required=["file_path"]) + +const OPEN_DATASET_TOOL = MCPTool( + name = "msi_open_dataset", + description = """ +Open (or switch) the active mass-spectrometry imaging dataset. This is the first +call in every session: it reads the imzML header and the binary metadata cache +(.cache) and keeps the resulting MSIData object alive between tool calls. + +Returns dataset metadata: number of spectra, image dimensions, m/z range (if +analytics are ready), source formats, mmap status and how long opening took. +Only one dataset can be open at a time; opening a new one closes and cleans the +previous one. +""", + input_schema = _OPEN_DATASET_SCHEMA, + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => true), + handler = guarded_handler() do params + file_path = opt_string(params, "file_path"; default="") + isempty(file_path) && throw(invalid_params( + "`file_path` is required."; suggested_action="Pass an absolute .imzML or .mzML path.")) + meta = open_dataset(file_path; + cache_size = opt_int(params, "cache_size"; default=300, min=0, max=100_000), + use_mmap = opt_bool(params, "use_mmap"; default=true), + precompute_analytics = opt_bool(params, "precompute_analytics"; default=false)) + return tool_json(meta) + end, +) + +const _CLOSE_DATASET_SCHEMA = object_schema(Dict{String,Any}()) + +const CLOSE_DATASET_TOOL = MCPTool( + name = "msi_close_dataset", + description = """ +Close the active dataset, release every file handle and return freed memory to +the operating system (GC.gc(true) + malloc_trim on glibc/Linux). Call this when +you are done, or before opening a different dataset, to keep RSS low in long +sessions. +""", + input_schema = _CLOSE_DATASET_SCHEMA, + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + previous = close_dataset() + release_os_memory!(full=true) + return tool_json(Dict{String,Any}( + "closed" => true, + "previous_dataset" => previous, + "process" => Dict{String,Any}("rss_mb" => _rss_mb()), + )) + end, +) + +const DATASET_INFO_TOOL = MCPTool( + name = "msi_dataset_info", + description = """ +Report the state of the active session without doing heavy work: path, dataset +id, dimensions, number of spectra, whether analytics are computed, mmap and +cache status, RSS and thread count. Use it to check whether a dataset is open +before planning work. +""", + input_schema = object_schema(Dict{String,Any}()), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + return tool_json(session_metadata()) + end, +) + +const DATASET_STATS_TOOL = MCPTool( + name = "msi_get_dataset_stats", + description = """ +Return per-spectrum descriptive statistics (TIC, BPI, base-peak m/z, number of +points, m/z bounds, mode). If analytics have not been computed yet this call +runs the full scan, which can take a while on large datasets; for big files +prefer msi_plan_analytics + msi_execute_runspec so the scan runs in the +background. The resource msi://dataset/stats is only populated after that scan. +""", + input_schema = object_schema(Dict{String,Any}( + "aggregate_only" => prop("boolean", "If true, omit per-spectrum rows. Default false.", default=false), + "limit" => prop("integer", "Maximum number of per-spectrum rows to return. Default 50.", + default=50, minimum=0, maximum=5000), + )), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + data = require_data() + elapsed = ensure_analytics!(data) + stats_df = MSI_src.get_spectrum_stats(data) + if stats_df === nothing + throw(internal_error("Analytics scan finished but no statistics table was produced.")) + end + limit = opt_int(params, "limit"; default=50, min=0, max=5000) + aggregate_only = opt_bool(params, "aggregate_only"; default=false) + aggregate = Dict{String,Any}() + for col in ("TIC", "BPI", "NumPoints") + v = Float64.(stats_df[!, col]) + aggregate[col] = Dict{String,Any}( + "min" => compact_float(minimum(v)), + "max" => compact_float(maximum(v)), + "mean" => compact_float(Statistics.mean(v)), + "median" => compact_float(Statistics.median(v)), + ) + end + rows = Any[] + if !aggregate_only + n = min(limit, nrow(stats_df)) + for i in 1:n + push!(rows, Dict{String,Any}( + "spectrum_id" => Int(stats_df[i, "SpectrumID"]), + "tic" => compact_float(stats_df[i, "TIC"]), + "bpi" => compact_float(stats_df[i, "BPI"]), + "base_peak_mz" => compact_float(stats_df[i, "BasePeakMZ"]), + "num_points" => Int(stats_df[i, "NumPoints"]), + "min_mz" => compact_float(stats_df[i, "MinMZ"]), + "max_mz" => compact_float(stats_df[i, "MaxMZ"]), + "mode" => string(stats_df[i, "Mode"]), + )) + end + end + return tool_json(Dict{String,Any}( + "dataset_id" => active_dataset_id(), + "num_spectra" => nrow(stats_df), + "analytics_seconds" => compact_float(elapsed), + "aggregate" => aggregate, + "rows" => rows, + "rows_returned" => length(rows), + "hint" => "Full table available as a CSV artifact via msi_plan_analytics.", + )) + end, +) diff --git a/src/tools/imaging.jl b/src/tools/imaging.jl new file mode 100644 index 0000000..63421d5 --- /dev/null +++ b/src/tools/imaging.jl @@ -0,0 +1,99 @@ +# src/tools/imaging.jl +# --------------------------------------------------------------------------- +# Synchronous ion-image shortcuts. +# +# These execute immediately in the tool call. They are convenient for quick +# queries but block the response until the pass completes; for expensive jobs +# use the planning + task tools instead. +# --------------------------------------------------------------------------- + +function _sync_runspec(kind::Symbol, params::Dict{String,Any}) + material = Dict{String,Any}("kind" => string(kind), "params" => params, + "dataset_id" => active_dataset_id()) + return RunSpec(short_hash(material, 32), kind, active_dataset_id(), params, time(), "synchronous call") +end + +function _sync_task(kind::Symbol) + return EngineTask(string(uuid4()), "sync", kind, active_dataset_id(), + :running, 0.0, "synchronous call", time(), time(), nothing, + nothing, nothing, false, nothing) +end + +const GET_MZ_SLICE_SCHEMA = object_schema(Dict{String,Any}( + "mass" => prop("number", "Target m/z in Daltons (e.g. 756.55)."), + "tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.", + default=0.1, exclusiveMinimum=0.0), + "mask_path" => prop("string", + "Optional absolute path to a mask image; only ROI pixels are read (white = tissue)."), + "include_matrix" => prop("boolean", + "Include the full intensity matrix in the JSON response (only for matrices ≤ 250,000 pixels). Default false.", + default=false), + "preview_max_dim" => prop("integer", "Maximum preview dimension. Default 96.", + default=96, minimum=16, maximum=256), + "output_name" => prop("string", "Label for the artifact directory. Default derived from m/z."), +); required=["mass"]) + +const GET_MZ_SLICE_TOOL = MCPTool( + name = "msi_get_mz_slice", + description = """ +Extract an ion image (2D intensity matrix) for one m/z value immediately, +without planning. Applies the engine's 3-layer pre-filter (m/z range → Bloom +filter → targeted read) and, on the first extraction, runs the analytics scan. +The full matrix is written as CSV + PGM under artifacts/; the response carries +compact statistics and a downsampled preview. + +For large datasets or several masses prefer msi_plan_ion_image + +msi_execute_runspec, which runs in the background. +""", + input_schema = GET_MZ_SLICE_SCHEMA, + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + data = require_data() + p = _ion_image_params(params, data; multiple=false) + pop!(p, "_verify", nothing) + result = _run_ion_image(_sync_runspec(:ion_image, p), _sync_task(:ion_image), data) + result["synchronous"] = true + return tool_json(result) + end, +) + +const GET_MULTIPLE_SLICES_SCHEMA = object_schema(Dict{String,Any}( + "masses" => prop("array", "List of target m/z values (max 50 for the synchronous shortcut).", + items=Dict{String,Any}("type" => "number"), minItems=1, maxItems=50), + "tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.", + default=0.1, exclusiveMinimum=0.0), + "mask_path" => prop("string", "Optional absolute path to a mask image."), + "include_matrix" => prop("boolean", + "Include matrices for up to 16 slices. Default false.", default=false), + "preview_max_dim" => prop("integer", "Maximum preview dimension. Default 64.", + default=64, minimum=16, maximum=256), + "output_name" => prop("string", "Label for the artifact directory. Default multiple_slices_sync."), +); required=["masses"]) + +const GET_MULTIPLE_SLICES_TOOL = MCPTool( + name = "msi_get_multiple_mz_slices", + description = """ +Synchronous shortcut to extract several ion images in a single I/O pass using +the engine's hierarchy inversion (O(N log M) instead of M passes). Limited to 50 +masses; for larger panels use msi_plan_multiple_slices + msi_execute_runspec. +Full images are written to artifacts/; the response includes per-mass statistics +and previews for the first slices. +""", + input_schema = GET_MULTIPLE_SLICES_SCHEMA, + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + data = require_data() + p = _ion_image_params(params, data; multiple=true) + pop!(p, "_verify", nothing) + length(p["masses"]) > 50 && throw(invalid_params( + "The synchronous shortcut accepts at most 50 masses (got $(length(p["masses"])))."; + suggested_action="Use msi_plan_multiple_slices + msi_execute_runspec for large panels.")) + result = _run_multiple_slices(_sync_runspec(:multiple_slices, p), _sync_task(:multiple_slices), data) + result["synchronous"] = true + return tool_json(result) + end, +) diff --git a/src/tools/maintenance.jl b/src/tools/maintenance.jl new file mode 100644 index 0000000..dee30bd --- /dev/null +++ b/src/tools/maintenance.jl @@ -0,0 +1,37 @@ +# src/tools/maintenance.jl +# --------------------------------------------------------------------------- +# Operational hygiene: artifact retention and OS-memory release. +# --------------------------------------------------------------------------- + +const CLEAN_ARTIFACTS_TOOL = MCPTool( + name = "msi_clean_artifacts", + description = """ +Prune generated artifacts (CSV/PGM/MatrixMarket outputs) from the artifact root. +Removes task directories older than `max_age_days` and, when a byte budget is set, +deletes oldest-first until the root fits under `max_total_bytes`. Defaults come from +the environment variables JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS (default 7) and +JULIA_MSI_MCP_ARTIFACT_MAX_BYTES (default 0 = disabled). The same policy is applied +automatically at server startup. +""", + input_schema = object_schema(Dict{String,Any}( + "max_age_days" => prop("number", + "Remove directories older than this many days (0 disables age pruning).", + minimum=0.0), + "max_total_bytes" => prop("number", + "Trim oldest directories until the root is under this many bytes (0 disables).", + minimum=0.0), + "dry_run" => prop("boolean", "Preview what would be removed without deleting anything.", + default=false), + )), + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => true, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + age_default, bytes_default = artifact_retention_config() + summary = prune_artifacts!( + max_age_days = opt_float(params, "max_age_days"; default=age_default, min=0.0, max=3650.0), + max_total_bytes = opt_float(params, "max_total_bytes"; default=bytes_default, min=0.0, max=1.0e15), + dry_run = opt_bool(params, "dry_run"; default=false)) + return tool_json(summary) + end, +) diff --git a/src/tools/planning.jl b/src/tools/planning.jl new file mode 100644 index 0000000..06d2b65 --- /dev/null +++ b/src/tools/planning.jl @@ -0,0 +1,208 @@ +# src/tools/planning.jl +# --------------------------------------------------------------------------- +# Planning tools: validate arguments, mint a RunSpec, never run the engine. +# --------------------------------------------------------------------------- + +const _PLAN_METADATA = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false) + +const PLAN_ION_IMAGE_TOOL = MCPTool( + name = "msi_plan_ion_image", + description = """ +Validate an ion-image request and produce an immutable RunSpec (content hash + +parameters bound to the current dataset). Nothing heavy runs here. Then call +msi_execute_runspec with the returned runspec_id. + +Validation covers: positive mass/tolerance, mask existence, image availability +and (when analytics are ready) whether the target falls inside the global m/z +range. +""", + input_schema = object_schema(Dict{String,Any}( + "mass" => prop("number", "Target m/z in Daltons."), + "tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.", + default=0.1, exclusiveMinimum=0.0), + "mask_path" => prop("string", "Optional mask image (PNG/TIFF/BMP) restricting I/O to the ROI."), + "output_name" => prop("string", "Artifact directory label."), + "include_matrix" => prop("boolean", "Include the full matrix in the result when ≤ 250k pixels. Default false.", + default=false), + "preview_max_dim" => prop("integer", "Preview size cap. Default 96.", + default=96, minimum=16, maximum=256), + ); required=["mass"]), + annotations = _PLAN_METADATA, + handler = guarded_handler() do params + return tool_json(plan_ion_image(params)) + end, +) + +const PLAN_MULTIPLE_SLICES_TOOL = MCPTool( + name = "msi_plan_multiple_slices", + description = """ +Validate a multi-mass ion-image panel and produce a RunSpec for the engine's +hierarchy-inversion pass (all masses in ONE read of the .ibd file). Intended for +large panels (tens to thousands of m/z values). Then call msi_execute_runspec. +""", + input_schema = object_schema(Dict{String,Any}( + "masses" => prop("array", "Target m/z values in Daltons (duplicates removed; max 5000).", + items=Dict{String,Any}("type" => "number"), minItems=1, maxItems=5000), + "tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.", + default=0.1, exclusiveMinimum=0.0), + "mask_path" => prop("string", "Optional mask image restricting I/O to the ROI."), + "output_name" => prop("string", "Artifact directory label."), + "include_matrix" => prop("boolean", "Include matrices for up to 16 slices. Default false.", + default=false), + "preview_max_dim" => prop("integer", "Preview size cap. Default 96.", + default=96, minimum=16, maximum=256), + ); required=["masses"]), + annotations = _PLAN_METADATA, + handler = guarded_handler() do params + return tool_json(plan_multiple_slices(params)) + end, +) + +const _STEPS_SCHEMA = prop("array", + "Ordered preprocessing steps. Each item: {\"name\": \"smoothing\", \"params\": {\"method\": \"savitzky_golay\", \"window\": 9, \"order\": 2}}. " * + "Allowed names: smoothing, baseline_correction, normalization, stabilization/intensity_transformation, peak_picking, calibration.", + items=Dict{String,Any}( + "type" => "object", + "properties" => Dict{String,Any}( + "name" => Dict{String,Any}("type" => "string"), + "params" => Dict{String,Any}("type" => "object"), + ), + "required" => ["name"], + ), + minItems=1) + +const _PREPROCESSING_PROPERTIES = Dict{String,Any}( + "steps" => _STEPS_SCHEMA, + "smoothing_window" => prop("integer", + "Shorthand: add Savitzky-Golay smoothing with this window (0 disables). Default 0.", + default=0, minimum=0, maximum=1001), + "baseline_iterations" => prop("integer", + "Shorthand: add SNIP baseline correction with this many iterations (0 disables). Default 0.", + default=0, minimum=0, maximum=10000), + "normalization" => prop("string", "Shorthand: TIC/RMS/median normalization, or none.", + enum=["none", "tic", "rms", "median"], default="none"), + "peak_picking" => prop("boolean", + "Shorthand: run streaming peak detection before binning. Default true when no steps are given.", + default=true), + "num_bins" => prop("integer", "Number of m/z bins in the feature matrix. Default 2000.", + default=2000, minimum=1, maximum=100000), + "min_peaks_per_bin" => prop("integer", "Minimum peaks per bin kept. Default 3.", + default=3, minimum=1), + "frequency_threshold" => prop("number", + "Keep only bins present in at least this fraction of spectra (0-1). Default 0.", + default=0.0, minimum=0.0, maximum=1.0), + "reference_peaks" => prop("array", "Fixed reference m/z values for calibration steps.", + items=Dict{String,Any}("type" => "number")), + "mask_path" => prop("string", "Optional ROI mask; only masked spectra are streamed."), + "include_matrix" => prop("boolean", + "Include sparse triplets in the result when nnz ≤ 20,000. Default false.", + default=false), + "output_name" => prop("string", "Artifact directory label. Default streaming_pipeline."), +) + +const PREPROCESSING_DESCRIPTION = """ +Validate a streaming preprocessing pipeline and produce a RunSpec for the +Sprint-2 engine (`process_dataset!`): smooth → baseline → normalize → peak-pick +→ bin, with thread-local sparse accumulators and RAM bounded by +threads × largest spectrum. No dense matrix is ever materialised. + +Either pass an explicit ordered `steps` array (full control) or use the +shorthands smoothing_window / baseline_iterations / normalization / +peak_picking. Then call msi_execute_runspec and read the Matrix Market artifact +(or the top_bins summary) from the task result. +""" + +const PLAN_PREPROCESSING_TOOL = MCPTool( + name = "msi_plan_preprocessing", + description = PREPROCESSING_DESCRIPTION, + input_schema = object_schema(_PREPROCESSING_PROPERTIES), + annotations = _PLAN_METADATA, + handler = guarded_handler() do params + return tool_json(plan_preprocessing(params)) + end, +) + +const PLAN_STREAMING_PIPELINE_TOOL = MCPTool( + name = "msi_plan_streaming_pipeline", + description = PREPROCESSING_DESCRIPTION * + "\n\nThis is an alias of msi_plan_preprocessing kept for workflow compatibility.", + input_schema = object_schema(_PREPROCESSING_PROPERTIES), + annotations = _PLAN_METADATA, + handler = guarded_handler() do params + return tool_json(plan_preprocessing(params)) + end, +) + +const PLAN_ANALYTICS_TOOL = MCPTool( + name = "msi_plan_analytics", + description = """ +Plan the one-time analytics scan (per-spectrum TIC, BPI, base-peak m/z, m/z +bounds, Bloom filters). Ion-image extraction needs it; running it in the +background avoids blocking the first slice request. The result includes a CSV +artifact with the full stats table. +""", + input_schema = object_schema(Dict{String,Any}( + "include_rows" => prop("integer", "Rows to inline in the result. Default 20.", + default=20, minimum=0, maximum=5000), + "output_name" => prop("string", "Artifact directory label. Default analytics."), + )), + annotations = _PLAN_METADATA, + handler = guarded_handler() do params + return tool_json(plan_analytics(params)) + end, +) + +const EXECUTE_RUNSPEC_TOOL = MCPTool( + name = "msi_execute_runspec", + description = """ +Execute a previously planned RunSpec in a background Julia task and return a +task_id immediately. Re-using the same runspec_id returns the existing +queued/running/completed task unless `force=true`. + +Then poll msi_get_task_status, fetch msi_get_task_result, or read +msi://tasks/{task_id}/status and msi://tasks/{task_id}/result. + +Optionally set wait_seconds (0-600) to block this call briefly, handy for small +datasets where the job finishes in a second or two. +""", + input_schema = object_schema(Dict{String,Any}( + "runspec_id" => prop("string", "The content hash returned by a planning tool."), + "force" => prop("boolean", "Run again even if a matching task already exists. Default false.", + default=false), + "wait_seconds" => prop("number", + "Wait up to this many seconds for completion before returning. Default 0.", + default=0.0, minimum=0.0, maximum=600.0), + ); required=["runspec_id"]), + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + id = opt_string(params, "runspec_id"; default="") + isempty(id) && throw(invalid_params("`runspec_id` is required.")) + rs = get_runspec(id) + payload = submit_runspec(rs; + force = opt_bool(params, "force"; default=false), + wait_seconds = opt_float(params, "wait_seconds"; default=0.0, min=0.0, max=600.0)) + return tool_json(payload) + end, +) + +const LIST_PLANS_TOOL = MCPTool( + name = "msi_list_plans", + description = "List recent RunSpecs (newest first) with their kind, summary and dataset id.", + input_schema = object_schema(Dict{String,Any}( + "limit" => prop("integer", "Maximum plans to list. Default 20.", + default=20, minimum=1, maximum=200), + )), + annotations = _PLAN_METADATA, + handler = guarded_handler() do params + limit = opt_int(params, "limit"; default=20, min=1, max=200) + specs = list_runspecs(limit=limit) + return tool_json(Dict{String,Any}( + "plans" => [runspec_payload(rs; include_params=false) for rs in specs], + "count" => length(specs), + )) + end, +) diff --git a/src/tools/spectra.jl b/src/tools/spectra.jl new file mode 100644 index 0000000..26a2637 --- /dev/null +++ b/src/tools/spectra.jl @@ -0,0 +1,138 @@ +# src/tools/spectra.jl +# --------------------------------------------------------------------------- +# Random-access spectrum queries (LRU-cached in the engine). +# --------------------------------------------------------------------------- + +const _SPECTRUM_PROPS = Dict{String,Any}( + "representation" => prop("string", + "`peaks`: local maxima only (compact, chemically meaningful). `profile`: uniformly decimated m/z grid. Default peaks.", + enum=["peaks", "profile"], default="peaks"), + "max_points" => prop("integer", + "Maximum number of points returned. Default 2000.", + default=2000, minimum=10, maximum=100000), + "min_intensity" => prop("number", + "Drop points with intensity below this value. Default 0.", default=0.0), +) + +function _spectrum_payload(data, mz, intensity; x=nothing, y=nothing, index=nothing, + representation::AbstractString="peaks", max_points::Int=2000, + min_intensity::Float64=0.0) + n = length(mz) + mz_f = Float64.(mz) + int_f = Float64.(intensity) + total = sum(int_f) + bpi, base_idx = n == 0 ? (0.0, 0) : findmax(int_f) + base_mz = n == 0 ? nothing : compact_float(mz_f[base_idx]) + + kept = Int[] + if min_intensity > 0 + kept = findall(v -> v >= min_intensity, int_f) + # Never return an empty spectrum because of a too-aggressive threshold. + isempty(kept) && (kept = collect(1:n)) + else + kept = collect(1:n) + end + + if representation == "profile" + idx = kept[uniform_indices(length(kept), max_points)] + truncated = length(kept) > max_points + else + sub_mz = view(mz_f, kept) + sub_int = view(int_f, kept) + local_idx = top_local_maxima(sub_mz, sub_int, max_points) + idx = kept[local_idx] + truncated = length(kept) > max_points + end + + points = Any[Any[compact_float(mz_f[i]), compact_float(int_f[i])] for i in idx] + payload = Dict{String,Any}( + "num_points" => n, + "points_returned" => length(points), + "truncated" => truncated, + "representation" => representation, + "mz_range" => n == 0 ? nothing : Any[compact_float(minimum(mz_f)), compact_float(maximum(mz_f))], + "tic" => compact_float(total), + "bpi" => compact_float(bpi), + "base_peak_mz" => base_mz, + "points" => points, + ) + x !== nothing && (payload["coord"] = Any[x, y]) + index !== nothing && (payload["spectrum_index"] = index) + return payload +end + +const GET_SPECTRUM_TOOL = MCPTool( + name = "msi_get_spectrum_at_coord", + description = """ +Return the spectrum at spatial coordinates (x, y) using the O(1) coordinate map +and the engine's LRU cache. By default only local maxima ("peaks") up to +`max_points` are returned, keeping the payload small; use representation +"profile" for a uniformly decimated profile. Includes TIC, BPI, base-peak m/z +and the m/z range. Coordinates are 1-based. +""", + input_schema = object_schema(Dict{String,Any}( + "x" => prop("integer", "Column coordinate (1-based)."), + "y" => prop("integer", "Row coordinate (1-based)."), + _SPECTRUM_PROPS..., + ); required=["x", "y"]), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + data = require_data() + x = opt_int(params, "x"; default=nothing) + y = opt_int(params, "y"; default=nothing) + (x === nothing || y === nothing) && throw(invalid_params("Both `x` and `y` are required.")) + data.coordinate_map === nothing && throw(invalid_params( + "This dataset has no coordinate map (not imaging data). Use msi_get_spectrum_by_index.")) + width, height = data.image_dims + (1 <= x <= width && 1 <= y <= height) || throw(invalid_params( + "Coordinates ($(x), $(y)) are outside the image bounds $(width)×$(height)."; + details=Dict("image_dims" => Any[width, height]))) + idx = data.coordinate_map[x, y] + idx == 0 && throw(invalid_params( + "No spectrum exists at ($(x), $(y)); this pixel is empty in the coordinate map."; + suggested_action="Pick a coordinate inside the tissue region; msi_get_dataset_stats can help locate non-empty spectra.")) + + mz, intensity = MSI_src.GetSpectrum(data, x, y) + rep = lowercase(String(_pget(params, "representation", "peaks"))) + rep in ("peaks", "profile") || throw(invalid_params("`representation` must be \"peaks\" or \"profile\".")) + payload = _spectrum_payload(data, mz, intensity; + x=x, y=y, index=idx, representation=rep, + max_points=opt_int(params, "max_points"; default=2000, min=10, max=100_000), + min_intensity=opt_float(params, "min_intensity"; default=0.0, min=0.0, max=Inf)) + return tool_json(payload) + end, +) + +const GET_SPECTRUM_BY_INDEX_TOOL = MCPTool( + name = "msi_get_spectrum_by_index", + description = """ +Return the spectrum with a given linear index (1..num_spectra). Useful for +non-imaging mzML data or when you already know the index from +msi_get_dataset_stats. Same output shape as msi_get_spectrum_at_coord. +""", + input_schema = object_schema(Dict{String,Any}( + "index" => prop("integer", "Linear spectrum index (1-based)."), + _SPECTRUM_PROPS..., + ); required=["index"]), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + data = require_data() + index = opt_int(params, "index"; default=nothing) + index === nothing && throw(invalid_params("`index` is required.")) + n = length(data.spectra_metadata) + (1 <= index <= n) || throw(invalid_params( + "Spectrum index $(index) is outside 1..$(n).")) + mz, intensity = MSI_src.GetSpectrum(data, index) + rep = lowercase(String(_pget(params, "representation", "peaks"))) + rep in ("peaks", "profile") || throw(invalid_params("`representation` must be \"peaks\" or \"profile\".")) + payload = _spectrum_payload(data, mz, intensity; + index=index, representation=rep, + max_points=opt_int(params, "max_points"; default=2000, min=10, max=100_000), + min_intensity=opt_float(params, "min_intensity"; default=0.0, min=0.0, max=Inf)) + return tool_json(payload) + end, +) diff --git a/src/tools/tasks.jl b/src/tools/tasks.jl new file mode 100644 index 0000000..b628fc2 --- /dev/null +++ b/src/tools/tasks.jl @@ -0,0 +1,97 @@ +# src/tools/tasks.jl +# --------------------------------------------------------------------------- +# Polling / result / cancellation tools for background RunSpec executions. +# --------------------------------------------------------------------------- + +const TASK_STATUS_TOOL = MCPTool( + name = "msi_get_task_status", + description = """ +Poll a background task: status (queued/running/completed/failed/cancelled), +progress 0-1, message, timestamps, duration, result availability, and a short +result summary when completed. This is the tool to call in a loop after +msi_execute_runspec. +""", + input_schema = object_schema(Dict{String,Any}( + "task_id" => prop("string", "Task identifier returned by msi_execute_runspec."), + "include_summary" => prop("boolean", + "Include a compact result summary when completed. Default true.", default=true), + ); required=["task_id"]), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + id = opt_string(params, "task_id"; default="") + isempty(id) && throw(invalid_params("`task_id` is required.")) + t = get_task(id) + return tool_json(task_status_payload(t; + include_summary = opt_bool(params, "include_summary"; default=true))) + end, +) + +const TASK_RESULT_TOOL = MCPTool( + name = "msi_get_task_result", + description = """ +Fetch the full structured result of a completed task: statistics, preview, +artifact paths (CSV/PGM/MatrixMarket) and, when requested, inline matrices or +sparse triplets. If the task is still running, returns its status plus a hint +instead of failing. +""", + input_schema = object_schema(Dict{String,Any}( + "task_id" => prop("string", "Task identifier returned by msi_execute_runspec."), + ); required=["task_id"]), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + id = opt_string(params, "task_id"; default="") + isempty(id) && throw(invalid_params("`task_id` is required.")) + return tool_json(task_result_payload(get_task(id))) + end, +) + +const CANCEL_TASK_TOOL = MCPTool( + name = "msi_cancel_task", + description = """ +Request cancellation of a queued or running task. Cancellation is cooperative: +the engine cannot interrupt an in-flight disk pass, so the task stops at the +next checkpoint (before/after the expensive call). Queued tasks are cancelled +immediately. +""", + input_schema = object_schema(Dict{String,Any}( + "task_id" => prop("string", "Task identifier."), + ); required=["task_id"]), + annotations = Dict{String,Any}( + "readOnlyHint" => false, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + id = opt_string(params, "task_id"; default="") + isempty(id) && throw(invalid_params("`task_id` is required.")) + return tool_json(Dict{String,Any}( + "cancellation_requested" => true, + "task" => cancel_task(id), + )) + end, +) + +const LIST_TASKS_TOOL = MCPTool( + name = "msi_list_tasks", + description = "List recent background tasks (newest first), optionally filtered by status.", + input_schema = object_schema(Dict{String,Any}( + "limit" => prop("integer", "Maximum tasks to return. Default 20.", + default=20, minimum=1, maximum=64), + "status" => prop("string", "Optional status filter.", + enum=["queued", "running", "completed", "failed", "cancelled"]), + )), + annotations = Dict{String,Any}( + "readOnlyHint" => true, "destructiveHint" => false, + "idempotentHint" => true, "openWorldHint" => false), + handler = guarded_handler() do params + limit = opt_int(params, "limit"; default=20, min=1, max=64) + status = opt_string(params, "status"; default=nothing) + tasks = list_tasks(limit=limit, status=status) + return tool_json(Dict{String,Any}( + "tasks" => [task_status_payload(t; include_summary=false) for t in tasks], + "count" => length(tasks), + )) + end, +) diff --git a/src/util.jl b/src/util.jl new file mode 100644 index 0000000..5d1257b --- /dev/null +++ b/src/util.jl @@ -0,0 +1,231 @@ +# src/util.jl +# --------------------------------------------------------------------------- +# Small, dependency-light helpers shared across the server. +# --------------------------------------------------------------------------- + +const JSON_MIME = "application/json" + +""" + jsonable(x) + +Recursively convert `x` into a value that `JSON3.write` can always encode. + +Julia's JSON stack is not a fan of `NaN`, `Inf`, `Symbol`, `Type` or tuples, so +we normalize them here (non-finite floats become `nothing`). +""" +jsonable(x::Nothing) = nothing +jsonable(x::Bool) = x +jsonable(x::Integer) = x +jsonable(x::AbstractFloat) = isfinite(x) ? Float64(x) : nothing +jsonable(x::AbstractString) = String(x) +jsonable(x::Symbol) = String(x) +jsonable(x::Type) = string(x) +jsonable(x::Dates.AbstractTime) = string(x) +jsonable(x::AbstractDict) = Dict{String,Any}(string(k) => jsonable(v) for (k, v) in x) +jsonable(x::NamedTuple) = Dict{String,Any}(string(k) => jsonable(v) for (k, v) in pairs(x)) +jsonable(x::Tuple) = Any[jsonable(v) for v in x] +jsonable(x::AbstractMatrix) = Any[Any[jsonable(v) for v in x[i, :]] for i in 1:size(x, 1)] +jsonable(x::AbstractArray) = Any[jsonable(v) for v in x] +jsonable(x) = string(x) + +json_text(x) = JSON3.write(jsonable(x)) + +"""Wrap a payload as an MCP text content block containing compact JSON.""" +tool_json(payload) = TextContent(text=json_text(payload)) + +"""Build a JSON-Schema object schema for `input_schema`.""" +function object_schema(properties::AbstractDict; required::Vector{String}=String[]) + schema = Dict{String,Any}("type" => "object", "properties" => Dict{String,Any}(properties)) + !isempty(required) && (schema["required"] = required) + return schema +end + +"""Shorthand for a JSON-Schema property.""" +prop(type::AbstractString, description::AbstractString; kwargs...) = begin + d = Dict{String,Any}("type" => String(type), "description" => String(description)) + for (k, v) in kwargs + d[String(k)] = v + end + d +end + +now_iso() = Dates.format(Dates.now(), "yyyy-mm-ddTHH:MM:SS.sss") + +""" + canonical_json(x) + +Deterministic JSON-ish encoding used to hash `RunSpec`s. Dictionary keys are +sorted so the digest is stable across processes (Julia randomizes string hashes +between runs). +""" +canonical_json(x::Nothing) = "null" +canonical_json(x::Bool) = x ? "true" : "false" +canonical_json(x::Integer) = string(x) +canonical_json(x::AbstractFloat) = isfinite(x) ? repr(Float64(x)) : "null" +canonical_json(x::AbstractString) = JSON3.write(String(x)) +canonical_json(x::Symbol) = canonical_json(String(x)) +canonical_json(x::AbstractDict) = begin + keys_sorted = sort!(collect(String.(keys(x)))) + parts = String["$(canonical_json(k)):$(canonical_json(x[k]))" for k in keys_sorted] + "{" * join(parts, ",") * "}" +end +canonical_json(x::NamedTuple) = canonical_json(Dict(string(k) => v for (k, v) in pairs(x))) +canonical_json(x::Union{Tuple,AbstractArray}) = "[" * join(canonical_json.(collect(x)), ",") * "]" +canonical_json(x::Type) = canonical_json(string(x)) +canonical_json(x) = canonical_json(string(x)) + +short_hash(value::AbstractString, n::Int=16) = first(bytes2hex(SHA.sha256(value)), n) +short_hash(value, n::Int=16) = short_hash(canonical_json(value), n) + +""" + safe_filename(name) + +Turn arbitrary user text into a conservative file-name fragment. +""" +function safe_filename(name::AbstractString, fallback::AbstractString="output") + cleaned = replace(String(name), r"[^A-Za-z0-9._-]+" => "_") + cleaned = strip(cleaned, ['_', '.']) + return isempty(cleaned) ? String(fallback) : first(cleaned, 80) +end + +"""Round a float for compact machine-readable output.""" +compact_float(x) = isfinite(x) ? round(Float64(x), sigdigits=6) : nothing + +"""Aggregate statistics for an intensity matrix.""" +function matrix_stats(mat::AbstractMatrix{<:Real}) + n = length(mat) + n == 0 && return Dict{String,Any}( + "shape" => [0, 0], "count" => 0, "nonzero" => 0, + "min" => nothing, "max" => nothing, "mean" => nothing, + "median" => nothing, "p95" => nothing, "sum" => 0.0, + "base_peak_coord" => nothing, "centroid_coord" => nothing, + ) + + vals = Float64.(vec(mat)) + finite_vals = filter(isfinite, vals) + nz_count = count(>(0.0), finite_vals) + vmax = isempty(finite_vals) ? 0.0 : maximum(finite_vals) + + base_peak_coord = nothing + centroid = nothing + if vmax > 0 + idx = argmax(mat) + base_peak_coord = [idx[2], idx[1]] # (x, y) + total = sum(vals) + ys, xs = size(mat) + sx = 0.0 + sy = 0.0 + for y in 1:ys, x in 1:xs + v = Float64(mat[y, x]) + isfinite(v) || continue + sx += v * x + sy += v * y + end + if total > 0 + centroid = [compact_float(sx / total), compact_float(sy / total)] + end + end + + finite_vals_sorted = sort!(finite_vals) + median = isempty(finite_vals_sorted) ? nothing : + (length(finite_vals_sorted) % 2 == 1 ? finite_vals_sorted[(end + 1) ÷ 2] : + (finite_vals_sorted[end ÷ 2] + finite_vals_sorted[end ÷ 2 + 1]) / 2) + p95 = isempty(finite_vals_sorted) ? nothing : + finite_vals_sorted[clamp(round(Int, 0.95 * length(finite_vals_sorted)), 1, length(finite_vals_sorted))] + + return Dict{String,Any}( + "shape" => [size(mat, 2), size(mat, 1)], # [width, height] + "count" => n, + "nonzero" => nz_count, + "min" => compact_float(minimum(finite_vals; init=0.0)), + "max" => compact_float(vmax), + "mean" => compact_float(sum(finite_vals) / max(length(finite_vals), 1)), + "median" => compact_float(median === nothing ? 0.0 : median), + "p95" => compact_float(p95 === nothing ? 0.0 : p95), + "sum" => compact_float(sum(finite_vals)), + "base_peak_coord" => base_peak_coord, + "centroid_coord" => centroid, + ) +end + +""" + downsample_matrix(mat; max_dim=96) + +Average-pool `mat` down to at most `max_dim` in either dimension. Returns the +reduced matrix (kept as a full matrix so callers can render it directly). +""" +function downsample_matrix(mat::AbstractMatrix{<:Real}; max_dim::Int=96) + h, w = size(mat) + (h == 0 || w == 0 || (h <= max_dim && w <= max_dim)) && return Matrix{Float64}(mat) + max_dim = max(1, max_dim) + factor = max(ceil(Int, h / max_dim), ceil(Int, w / max_dim), 1) + out_h = max(1, fld(h, factor)) + out_w = max(1, fld(w, factor)) + out = zeros(Float64, out_h, out_w) + for oy in 1:out_h, ox in 1:out_w + y0 = (oy - 1) * factor + 1 + y1 = min(oy * factor, h) + x0 = (ox - 1) * factor + 1 + x1 = min(ox * factor, w) + acc = 0.0 + cnt = 0 + @inbounds for y in y0:y1, x in x0:x1 + v = Float64(mat[y, x]) + if isfinite(v) + acc += v + cnt += 1 + end + end + out[oy, ox] = cnt == 0 ? 0.0 : acc / cnt + end + return out +end + +"""Nearest/bilinear-free preview with row-major [y][x] nesting for JSON.""" +function preview_matrix(mat::AbstractMatrix{<:Real}; max_dim::Int=96) + reduced = downsample_matrix(mat; max_dim=max_dim) + # Round to 4 significant digits to keep payloads small. + rows = [Any[compact_float(v) for v in reduced[y, :]] for y in 1:size(reduced, 1)] + return Dict{String,Any}( + "dims" => [size(reduced, 2), size(reduced, 1)], + "rows" => rows, + "scale" => "linear; 0 = no signal; averaged pooling from the full matrix", + ) +end + +""" + top_local_maxima(mz, intensity, limit) + +Return at most `limit` local maxima sorted by m/z, useful for compact spectrum +payloads. Falls back to the global top intensities if no local maxima exist. +""" +function top_local_maxima(mz::AbstractVector, intensity::AbstractVector, limit::Int) + n = length(mz) + limit = max(1, limit) + candidates = Int[] + @inbounds for i in 1:n + v = intensity[i] + left = i == 1 ? -Inf : intensity[i - 1] + right = i == n ? -Inf : intensity[i + 1] + if v >= left && v >= right + push!(candidates, i) + end + end + if isempty(candidates) + candidates = collect(1:n) + end + # Partial sort candidates by intensity (descending), then keep m/z order. + order = sortperm(candidates; by=i -> -Float64(intensity[i])) + selected = candidates[order[1:min(limit, length(order))]] + sort!(selected; by=i -> Float64(mz[i])) + return selected +end + +"""Uniformly decimate an index range to at most `limit` indices.""" +function uniform_indices(n::Int, limit::Int) + n <= 0 && return Int[] + limit = max(1, limit) + n <= limit && return collect(1:n) + step = n / limit + return unique([clamp(round(Int, 1 + (k - 1) * step), 1, n) for k in 1:limit]) +end diff --git a/test/real_datasets.jl b/test/real_datasets.jl new file mode 100644 index 0000000..b151f0e --- /dev/null +++ b/test/real_datasets.jl @@ -0,0 +1,137 @@ +#!/usr/bin/env julia +# --------------------------------------------------------------------------- +# Reproducible validation against real datasets (not part of Pkg.test). +# +# julia --project=. test/real_datasets.jl /path/sample.imzML [/path/sample.mzML] +# +# Set JULIA_MSI_MCP_REAL_STREAMING=1 to also run the streaming pipeline. +# Artifacts go to JULIA_MSI_MCP_ARTIFACTS (default: a temp directory). +# --------------------------------------------------------------------------- + +using JuliaMSI_MCP +using JSON3 +using ModelContextProtocol + +const J = JuliaMSI_MCP +const ARTIFACTS = get(ENV, "JULIA_MSI_MCP_ARTIFACTS", mktempdir(prefix="juliamsi_real_")) +ENV["JULIA_MSI_MCP_ARTIFACTS"] = ARTIFACTS + +function call_tool(tool, args) + result = tool.handler(args) + if result isa ModelContextProtocol.CallToolResult + return result.is_error, JSON3.read(result.content[1]["text"]) + end + return false, JSON3.read(result.text) +end + +function wait_for(task_id; timeout=1800.0) + t0 = time() + while true + status = J.task_status_payload(J.get_task(task_id)) + if status["status"] in ("completed", "failed", "cancelled") || time() - t0 > timeout + return J.task_result_payload(J.get_task(task_id)), time() - t0 + end + sleep(1) + end +end + +function run_plan(plan; timeout=1800.0) + executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=0) + return wait_for(executed["task_id"]; timeout=timeout) +end + +function validate_imzml(path) + println("=== imzML: ", path) + t_open = @elapsed meta = J.open_dataset(path; cache_size=300, use_mmap=true, + precompute_analytics=false) + width, height = meta["image_dims"] + println("open_seconds=", round(t_open, digits=2), + " spectra=", meta["num_spectra"], " dims=", width, "x", height, + " mmap=", meta["source"]["mmap_active"], " rss_mb=", J._rss_mb()) + + data = J.require_data() + x, y = max(1, width ÷ 2), max(1, height ÷ 2) + mz, intensity = J.MSI_src.GetSpectrum(data, x, y) + base_mass = mz[argmax(intensity)] + println("spectrum(", x, ",", y, ") points=", length(mz), + " bpi=", maximum(intensity), " base_peak_mz=", base_mass) + + analytics, t_an = run_plan(J.plan_analytics(Dict("include_rows" => 2))) + println("analytics status=", analytics["status"], " wall_seconds=", round(t_an, digits=1), + " mz_range=", analytics["mz_range"]) + + ion, t_ion = run_plan(J.plan_ion_image(Dict( + "mass" => base_mass, "tolerance" => 0.15, "preview_max_dim" => 96))) + st = ion["stats"] + println("ion_image m/z=", base_mass, " status=", ion["status"], + " wall_seconds=", round(t_ion, digits=1), " max=", st["max"], + " nonzero=", st["nonzero"], " base_peak_coord=", st["base_peak_coord"]) + println(" artifact_csv=", ion["artifacts"]["csv"]["path"]) + + min_mz, max_mz = analytics["mz_range"] + masses = unique([base_mass, min_mz + 0.2 * (max_mz - min_mz), + min_mz + 0.5 * (max_mz - min_mz), + min_mz + 0.8 * (max_mz - min_mz)]) + multi, t_multi = run_plan(J.plan_multiple_slices(Dict( + "masses" => masses, "tolerance" => 0.15, "preview_max_dim" => 64))) + println("multiple_slices n=", multi["num_slices"], " wall_seconds=", round(t_multi, digits=1)) + for slice in multi["slices"] + s = slice["stats"] + println(" m/z=", slice["mass"], " max=", s["max"], " nonzero=", s["nonzero"]) + end + + if get(ENV, "JULIA_MSI_MCP_REAL_STREAMING", "0") == "1" + stream, t_stream = run_plan(J.plan_preprocessing(Dict( + "steps" => [ + Dict("name" => "smoothing", "params" => Dict("method" => "savitzky_golay", "window" => 5, "order" => 2)), + Dict("name" => "baseline_correction", "params" => Dict("method" => "snip", "iterations" => 20)), + Dict("name" => "normalization", "params" => Dict("method" => "tic")), + Dict("name" => "peak_picking", "params" => Dict("method" => "profile", "snr_threshold" => 3.0)), + ], + "num_bins" => 500, "min_peaks_per_bin" => 1, "frequency_threshold" => 0.02))) + println("streaming status=", stream["status"], " wall_seconds=", round(t_stream, digits=1), + " shape=", stream["matrix_shape"], " nonzeros=", stream["nonzeros"]) + println(" mtx=", stream["artifacts"]["matrix_mtx"]["path"]) + end + + J.close_dataset() + println("closed rss_mb=", J._rss_mb()) +end + +function validate_mzml(path) + println("=== mzML: ", path) + t_open = @elapsed meta = J.open_dataset(path; cache_size=50, use_mmap=true) + println("open_seconds=", round(t_open, digits=2), " spectra=", meta["num_spectra"], + " mmap=", meta["source"]["mmap_active"]) + + iserr, spec = call_tool(J.GET_SPECTRUM_BY_INDEX_TOOL, + Dict("index" => 1, "max_points" => 50)) + iserr && error("spectrum query failed: $(spec)") + println("spectrum(1) points=", spec["num_points"], " bpi=", spec["bpi"], + " base_peak_mz=", spec["base_peak_mz"]) + + analytics, t_an = run_plan(J.plan_analytics(Dict("include_rows" => 1)), timeout=600) + println("analytics status=", analytics["status"], " wall_seconds=", round(t_an, digits=1), + " mz_range=", analytics["mz_range"]) + + iserr, err = call_tool(J.GET_MZ_SLICE_TOOL, Dict("mass" => spec["base_peak_mz"], "tolerance" => 0.1)) + println("ion_image_rejected=", iserr, iserr ? " type=" * err["error"]["type"] : "") + J.close_dataset() +end + +function main(args) + isempty(args) && error("usage: julia --project=. test/real_datasets.jl ...") + for path in args + isfile(path) || error("file not found: $(path)") + if endswith(lowercase(path), ".imzml") + validate_imzml(path) + elseif endswith(lowercase(path), ".mzml") + validate_mzml(path) + else + @warn "Skipping unsupported file" path + end + end + println("Artifacts: ", ARTIFACTS) +end + +main(ARGS) diff --git a/test/runtests.jl b/test/runtests.jl new file mode 100644 index 0000000..396fae8 --- /dev/null +++ b/test/runtests.jl @@ -0,0 +1,312 @@ +using Test +using JSON3 +using ModelContextProtocol +using JuliaMSI_MCP + +const J = JuliaMSI_MCP + +include("synthetic.jl") + +# Keep generated artifacts inside a disposable directory. +const TEST_ARTIFACTS = mktempdir() +ENV["JULIA_MSI_MCP_ARTIFACTS"] = TEST_ARTIFACTS + +"""Call a tool handler and return `(is_error, payload)`.""" +function call_tool(tool, args::AbstractDict) + result = tool.handler(args) + if result isa ModelContextProtocol.CallToolResult + text = result.content[1]["text"] + return result.is_error, JSON3.read(text) + else + return false, JSON3.read(result.text) + end +end + +@testset "JuliaMSI_MCP" begin + + @testset "utilities" begin + @test J.canonical_json(Dict("b" => 2, "a" => 1)) == + J.canonical_json(Dict("a" => 1, "b" => 2)) + @test J.canonical_json(Dict("x" => [1.0, 2.0])) == + "{\"x\":[1.0,2.0]}" + @test J.jsonable(Dict("bad" => NaN))["bad"] === nothing + @test J.short_hash("abc") == J.short_hash("abc") + @test J.short_hash("abc") != J.short_hash("abd") + + m = [0.0 4.0; 2.0 8.0] + ds = J.downsample_matrix(m; max_dim=1) + @test size(ds) == (1, 1) + @test ds[1, 1] ≈ 3.5 + st = J.matrix_stats(m) + @test st["max"] == 8.0 + @test st["base_peak_coord"] == [2, 2] + @test st["nonzero"] == 3 + end + + @testset "dataset lifecycle, spectra and ion images" begin + dir = mktempdir() + path = write_synthetic_imzml(dir) + + @testset "open and metadata" begin + meta = open_dataset(path; precompute_analytics=true) + @test meta["open"] == true + @test meta["num_spectra"] == 12 + @test meta["image_dims"] == Any[4, 3] + @test meta["mz_range"] == Any[100.0, 500.0] + @test meta["analytics_ready"] == true + @test meta["source"]["type"] == "imzML" + @test meta["coordinate_map"] == true + @test isfile(path * ".cache") + @test J.session_metadata()["dataset_id"] == meta["dataset_id"] + end + + @testset "spectrum at coordinate" begin + iserr, p = call_tool(J.GET_SPECTRUM_TOOL, Dict("x" => 2, "y" => 2)) + @test !iserr + @test p["num_points"] == 5 + @test p["bpi"] == 1000.0 + @test p["base_peak_mz"] == 300.0 + @test p["coord"] == [2, 2] + @test 1 <= length(p["points"]) <= 5 + iserr, prof = call_tool(J.GET_SPECTRUM_TOOL, + Dict("x" => 2, "y" => 2, "representation" => "profile", + "max_points" => 100)) + @test !iserr + @test length(prof["points"]) == 5 + + iserr, p = call_tool(J.GET_SPECTRUM_BY_INDEX_TOOL, + Dict("index" => 6, "representation" => "profile")) + @test !iserr + @test p["representation"] == "profile" + + iserr, p = call_tool(J.GET_SPECTRUM_TOOL, Dict("x" => 99, "y" => 1)) + @test iserr + @test p["error"]["type"] == "InvalidParams" + end + + @testset "synchronous ion image" begin + iserr, p = call_tool(J.GET_MZ_SLICE_TOOL, + Dict("mass" => 300.0, "tolerance" => 0.5, + "include_matrix" => true)) + @test !iserr + @test p["stats"]["max"] == 1000.0 + @test p["stats"]["base_peak_coord"] == [2, 2] + @test p["preview"]["dims"] == [4, 3] + @test p["matrix"][2][2] == 1000.0 + @test isfile(p["artifacts"]["csv"]["path"]) + @test isfile(p["artifacts"]["pgm"]["path"]) + + # ROI mask (A.10): only two pixels are selected. + mask = zeros(Float64, 3, 4) + mask[2, 2] = 1.0 + mask[2, 3] = 1.0 + mask_path = joinpath(dir, "mask.pgm") + J.write_matrix_pgm(mask_path, mask) + iserr, masked = call_tool(J.GET_MZ_SLICE_TOOL, + Dict("mass" => 300.0, "tolerance" => 0.5, "mask_path" => mask_path)) + @test !iserr + @test masked["stats"]["nonzero"] == 2 + @test masked["stats"]["base_peak_coord"] == [2, 2] + end + + @testset "synchronous multiple slices" begin + iserr, p = call_tool(J.GET_MULTIPLE_SLICES_TOOL, + Dict("masses" => [100.0, 300.0], "tolerance" => 0.5)) + @test !iserr + @test p["num_slices"] == 2 + @test length(p["slices"]) == 2 + @test p["slices"][1]["mass"] == 100.0 + @test p["slices"][2]["stats"]["max"] == 1000.0 + end + + @testset "planning validation" begin + iserr, p = call_tool(J.PLAN_ION_IMAGE_TOOL, Dict("tolerance" => 0.5)) + @test iserr + @test p["error"]["type"] == "InvalidParams" + + plan = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5)) + @test plan["kind"] == "ion_image" + @test plan["validation"]["checked"] == true + @test J.get_runspec(plan["runspec_id"]).dataset_id == J.active_dataset_id() + + # Same inputs -> same content hash; different tolerance -> different hash. + plan2 = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5)) + @test plan2["runspec_id"] == plan["runspec_id"] + plan3 = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.6)) + @test plan3["runspec_id"] != plan["runspec_id"] + + # An empty mask path means "no mask", not the current directory. + plan_blank = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5, + "mask_path" => "")) + @test plan_blank["params"]["mask_path"] === nothing + + iserr, p = call_tool(J.PLAN_PREPROCESSING_TOOL, + Dict("steps" => [Dict("name" => "nope")])) + @test iserr + end + + @testset "asynchronous ion image + task tools" begin + plan = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5)) + executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=30) + @test executed["status"] == "completed" + @test executed["reused"] == false + + iserr, status = call_tool(J.TASK_STATUS_TOOL, + Dict("task_id" => executed["task_id"])) + @test !iserr + @test status["status"] == "completed" + @test status["progress"] == 1.0 + @test status["result_ready"] == true + + iserr, result = call_tool(J.TASK_RESULT_TOOL, + Dict("task_id" => executed["task_id"])) + @test !iserr + @test result["stats"]["max"] == 1000.0 + @test result["stats"]["base_peak_coord"] == [2, 2] + + # Re-using the same RunSpec returns the existing task. + again = J.submit_runspec(J.get_runspec(plan["runspec_id"])) + @test again["reused"] == true + @test again["task_id"] == executed["task_id"] + + iserr, listed = call_tool(J.LIST_TASKS_TOOL, Dict("limit" => 5)) + @test !iserr + @test listed["count"] >= 1 + end + + @testset "analytics task" begin + plan = J.plan_analytics(Dict("include_rows" => 3)) + executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=30) + @test executed["status"] == "completed" + res = J.task_result_payload(J.get_task(executed["task_id"])) + @test res["num_spectra"] == 12 + @test length(res["rows"]) == 3 + @test res["aggregate"]["TIC"]["max"] > 0 + @test isfile(res["artifacts"]["spectrum_stats_csv"]["path"]) + end + + @testset "streaming preprocessing task" begin + plan = J.plan_preprocessing(Dict( + "smoothing_window" => 5, + "baseline_iterations" => 10, + "normalization" => "tic", + "num_bins" => 50, + "min_peaks_per_bin" => 1, + "peak_picking" => true, + )) + executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=120) + @test executed["status"] == "completed" + res = J.task_result_payload(J.get_task(executed["task_id"])) + @test res["matrix_shape"] == Any[50, 12] + @test res["nonzeros"] >= 1 + @test isfile(res["artifacts"]["matrix_mtx"]["path"]) + @test isfile(res["artifacts"]["bin_centers_csv"]["path"]) + @test !isempty(res["top_bins"]) + end + + @testset "resources and prompts" begin + meta = J.DATASET_METADATA_RESOURCE.data_provider() + @test meta["open"] == true + stats = J.DATASET_STATS_RESOURCE.data_provider() + @test stats["analytics_ready"] == true + @test stats["rows_returned"] > 0 + + tasks = J.list_tasks(limit=1) + if !isempty(tasks) + t = first(tasks) + st = J.TASK_STATUS_TEMPLATE.data_provider( + "msi://tasks/$(t.id)/status", Dict("task_id" => t.id)) + @test st["task_id"] == t.id + rs = J.TASK_RESULT_TEMPLATE.data_provider( + "msi://tasks/$(t.id)/result", Dict("task_id" => t.id)) + @test rs["task_id"] == t.id + end + @test length(J.ALL_TOOLS) == 20 + @test length(J.ALL_RESOURCES) == 2 + @test length(J.ALL_PROMPTS) == 3 + @test J.build_server() isa ModelContextProtocol.Server + end + + @testset "close" begin + previous = J.close_dataset() + @test previous["open"] == true + @test J.session_metadata()["open"] == false + + iserr, p = call_tool(J.DATASET_INFO_TOOL, Dict()) + @test !iserr + @test p["open"] == false + + iserr, p = call_tool(J.GET_SPECTRUM_TOOL, Dict("x" => 1, "y" => 1)) + @test iserr + @test p["error"]["type"] == "SessionError" + end + + rm(dir; recursive=true, force=true) + end + + @testset "non-mmap I/O (Float32) regression" begin + dir = mktempdir() + path = write_synthetic_imzml(dir; width=3, height=2) + meta = open_dataset(path; use_mmap=false, precompute_analytics=true) + @test meta["source"]["mmap_active"] == false + @test meta["mz_range"] == Any[100.0, 500.0] + @test meta["analytics_ready"] == true + iserr, p = call_tool(J.GET_MZ_SLICE_TOOL, + Dict("mass" => 300.0, "tolerance" => 0.5)) + @test !iserr + @test p["stats"]["max"] == 1000.0 + J.close_dataset() + rm(dir; recursive=true, force=true) + end + + @testset "dataset switching invalidates plans" begin + dir1 = mktempdir() + dir2 = mktempdir() + p1 = write_synthetic_imzml(dir1; width=2, height=2) + p2 = write_synthetic_imzml(dir2; width=3, height=3) + open_dataset(p1; precompute_analytics=false) + plan = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5)) + rs = J.get_runspec(plan["runspec_id"]) + open_dataset(p2; precompute_analytics=false) + @test_throws J.MCPToolError J.submit_runspec(rs) + J.close_dataset() + rm(dir1; recursive=true, force=true) + rm(dir2; recursive=true, force=true) + end + + @testset "artifact retention" begin + root = TEST_ARTIFACTS + old_dir = joinpath(root, "old_task_0000") + new_dir = joinpath(root, "new_task_0000") + mkpath(old_dir) + mkpath(new_dir) + write(joinpath(old_dir, "a.csv"), "x"^1000) + write(joinpath(new_dir, "b.csv"), "y"^1000) + + # Backdate the old directory's mtime so age pruning can see it. + t = round(Int64, time() - 10 * 86400) + buf = zeros(Int64, 2) + buf[1] = t + buf[2] = t + ccall(:utime, Cint, (Cstring, Ptr{Int64}), old_dir, buf) + + # dry_run removes nothing + dry = J.prune_artifacts!(max_age_days=1.0, max_total_bytes=0.0, dry_run=true) + @test dry["dry_run"] == true + @test isdir(old_dir) && isdir(new_dir) + + # age pruning removes only the old directory + age = J.prune_artifacts!(max_age_days=1.0, max_total_bytes=0.0) + @test age["removed"] == 1 + @test !isdir(old_dir) + @test isdir(new_dir) + + # size budget trims the rest + size_budget = J.prune_artifacts!(max_age_days=0.0, max_total_bytes=10.0) + @test size_budget["removed"] >= 1 + @test !isdir(new_dir) + end + +end + +rm(TEST_ARTIFACTS; recursive=true, force=true) diff --git a/test/smoke_stdio.py b/test/smoke_stdio.py new file mode 100644 index 0000000..56a23be --- /dev/null +++ b/test/smoke_stdio.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""End-to-end smoke test for the JuliaMSI MCP server (stdio transport). + +Generates a small synthetic .imzML dataset (unless --dataset is given), launches +the real server process, and exercises the full JSON-RPC surface: initialize, +discovery, dataset open, spectrum query, async analytics task, ion image +plan -> execute -> poll -> result, resources, prompts and close. Imaging vs. +non-imaging (mzML) datasets are detected automatically. + +Usage: + python3 test/smoke_stdio.py [--dataset /path/to/file.imzML] [--keep] + +Requires: Python 3.8+ and a Julia installation with the project instantiated. +""" +import argparse +import collections +import json +import os +import select +import shutil +import subprocess +import sys +import tempfile +import threading +import time + +PROJECT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +JULIA = os.environ.get("JULIA", "julia") + + +class Client: + def __init__(self, dataset=None): + cmd = [JULIA, f"--project={PROJECT}", "--threads=auto", + os.path.join(PROJECT, "bin", "run_server.jl")] + env = dict(os.environ) + self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, bufsize=1, env=env) + self.stderr = collections.deque(maxlen=400) + self._reader = threading.Thread(target=self._drain_stderr, daemon=True) + self._reader.start() + + def _drain_stderr(self): + for line in self.proc.stderr: + self.stderr.append(line.rstrip()) + + def send(self, message): + self.proc.stdin.write(json.dumps(message) + "\n") + self.proc.stdin.flush() + + def recv(self, timeout=300): + deadline = time.time() + timeout + while time.time() < deadline: + ready, _, _ = select.select([self.proc.stdout], [], [], 1.0) + if ready: + line = self.proc.stdout.readline() + if not line: + raise RuntimeError("server closed stdout\n" + "\n".join(self.stderr)) + return json.loads(line) + if self.proc.poll() is not None: + raise RuntimeError("server exited\n" + "\n".join(self.stderr)) + raise TimeoutError("no JSON-RPC response within %ss" % timeout) + + def call(self, request_id, method, params=None, timeout=300): + message = {"jsonrpc": "2.0", "id": request_id, "method": method} + if params is not None: + message["params"] = params + self.send(message) + while True: + response = self.recv(timeout) + if response.get("id") == request_id: + if "error" in response: + raise RuntimeError("JSON-RPC error: " + json.dumps(response["error"])) + return response["result"] + + def tool(self, request_id, name, arguments): + result = self.call(request_id, "tools/call", {"name": name, "arguments": arguments}) + body = result["content"][0]["text"] + if result.get("isError"): + raise RuntimeError("tool %s failed: %s" % (name, body)) + return json.loads(body) + + def tool_error(self, request_id, name, arguments): + result = self.call(request_id, "tools/call", {"name": name, "arguments": arguments}) + if not result.get("isError"): + raise RuntimeError("tool %s unexpectedly succeeded" % name) + return json.loads(result["content"][0]["text"]) + + def close(self): + try: + self.proc.stdin.close() + except Exception: + pass + try: + self.proc.wait(timeout=30) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def ensure_dataset(path): + if path: + return path, False + tmp = tempfile.mkdtemp(prefix="juliamsi_smoke_") + script = ( + 'include(joinpath(ENV["JULIA_MSI_MCP_PROJECT"], "test", "synthetic.jl")); ' + 'println(write_synthetic_imzml(ENV["JULIA_MSI_MCP_SMOKE_DIR"]))' + ) + env = dict(os.environ, JULIA_MSI_MCP_PROJECT=PROJECT, JULIA_MSI_MCP_SMOKE_DIR=tmp) + out = subprocess.run([JULIA, f"--project={PROJECT}", "-e", script], + check=True, capture_output=True, text=True, env=env) + return out.stdout.strip().splitlines()[-1], tmp + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", help="existing .imzML (otherwise a synthetic one is generated)") + parser.add_argument("--keep", action="store_true", help="keep the temporary dataset") + args = parser.parse_args() + + dataset, tmp = ensure_dataset(args.dataset) + created_artifacts = False + if not os.environ.get("JULIA_MSI_MCP_ARTIFACTS"): + os.environ["JULIA_MSI_MCP_ARTIFACTS"] = tempfile.mkdtemp(prefix="juliamsi_smoke_artifacts_") + created_artifacts = True + client = Client(dataset) + try: + print("[1] initialize") + init = client.call(1, "initialize", { + "protocolVersion": "2025-11-25", + "capabilities": {}, + "clientInfo": {"name": "juliamsi-smoke", "version": "0.1"}, + }) + assert init["serverInfo"]["name"] == "juliamsi" + client.send({"jsonrpc": "2.0", "method": "notifications/initialized"}) + + print("[2] discovery") + tools = client.call(2, "tools/list")["tools"] + names = {t["name"] for t in tools} + for required in ("msi_open_dataset", "msi_plan_ion_image", "msi_execute_runspec", + "msi_get_task_status", "msi_get_task_result", "msi_close_dataset"): + assert required in names, "missing tool " + required + resources = client.call(3, "resources/list")["resources"] + assert any(r["uri"] == "msi://dataset/metadata" for r in resources) + templates = client.call(4, "resources/templates/list")["resourceTemplates"] + assert any("tasks" in t["uriTemplate"] for t in templates) + prompts = client.call(5, "prompts/list")["prompts"] + assert any(p["name"] == "analyze_region_of_interest" for p in prompts) + + print("[3] open dataset:", dataset) + meta = client.tool(6, "msi_open_dataset", + {"file_path": dataset, "precompute_analytics": False}) + num_spectra = meta["num_spectra"] + width, height = meta["image_dims"] + imaging = width > 0 and height > 0 and bool(meta.get("coordinate_map")) + assert num_spectra > 0 + print(" spectra=%d dims=%dx%d imaging=%s" % (num_spectra, width, height, imaging)) + + if imaging: + x = max(1, width // 2) + y = max(1, height // 2) + print("[4] spectrum at (%d,%d)" % (x, y)) + spec = client.tool(7, "msi_get_spectrum_at_coord", {"x": x, "y": y}) + else: + print("[4] spectrum by index (non-imaging dataset)") + spec = client.tool(7, "msi_get_spectrum_by_index", {"index": 1}) + assert spec["num_points"] > 0 + assert spec["bpi"] > 0 + assert len(spec["points"]) > 0 + + print("[5] async analytics task") + plan = client.tool(8, "msi_plan_analytics", {"include_rows": 1}) + executed = client.tool(9, "msi_execute_runspec", + {"runspec_id": plan["runspec_id"], "wait_seconds": 300}) + task_id = executed["task_id"] + status = client.tool(10, "msi_get_task_status", {"task_id": task_id}) + assert status["status"] == "completed", status + analytics = client.tool(11, "msi_get_task_result", {"task_id": task_id}) + assert analytics["num_spectra"] == num_spectra + assert analytics["aggregate"]["TIC"]["max"] > 0 + + print("[6] dataset stats and structured errors") + stats = client.tool(12, "msi_get_dataset_stats", + {"aggregate_only": True, "limit": 1}) + assert stats["num_spectra"] == num_spectra + error_args = {"x": width + 10, "y": 1} if imaging else {"x": 1, "y": 1} + err = client.tool_error(13, "msi_get_spectrum_at_coord", error_args) + assert err["error"]["type"] == "InvalidParams" + + if imaging: + print("[7] plan -> execute -> poll -> result (ion image)") + mass = spec["base_peak_mz"] + plan = client.tool(14, "msi_plan_ion_image", {"mass": mass, "tolerance": 0.5}) + executed = client.tool(15, "msi_execute_runspec", + {"runspec_id": plan["runspec_id"], "wait_seconds": 300}) + task_id = executed["task_id"] + status = client.tool(16, "msi_get_task_status", {"task_id": task_id}) + assert status["status"] == "completed", status + result = client.tool(17, "msi_get_task_result", {"task_id": task_id}) + assert result["stats"]["max"] > 0 + bpc = result["stats"]["base_peak_coord"] + assert 1 <= bpc[0] <= width and 1 <= bpc[1] <= height + plans = client.tool(18, "msi_list_plans", {"limit": 5}) + assert plans["count"] >= 1 + else: + print("[7] ion-image tools correctly reject non-imaging data") + ionerr = client.tool_error(19, "msi_plan_ion_image", + {"mass": spec["base_peak_mz"], "tolerance": 0.5}) + assert ionerr["error"]["type"] == "InvalidParams" + + print("[8] resources and prompt rendering") + task_resource = client.call(20, "resources/read", + {"uri": "msi://tasks/%s/status" % task_id}) + task_payload = json.loads(task_resource["contents"][0]["text"]) + assert task_payload["status"] == "completed" + prompt = client.call(21, "prompts/get", { + "name": "analyze_region_of_interest", + "arguments": {"dataset_path": dataset, "region": "tumor tissue"}, + }) + text = prompt["messages"][0]["content"]["text"] + assert "tumor tissue" in text and "{region}" not in text + + print("[9] close dataset") + closed = client.tool(22, "msi_close_dataset", {}) + assert closed["closed"] is True + + print("SMOKE TEST PASSED") + finally: + client.close() + if tmp and not args.keep: + shutil.rmtree(tmp, ignore_errors=True) + if created_artifacts: + shutil.rmtree(os.environ["JULIA_MSI_MCP_ARTIFACTS"], ignore_errors=True) + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print("SMOKE TEST FAILED:", exc, file=sys.stderr) + sys.exit(1) diff --git a/test/synthetic.jl b/test/synthetic.jl new file mode 100644 index 0000000..27a7f9f --- /dev/null +++ b/test/synthetic.jl @@ -0,0 +1,111 @@ +# test/synthetic.jl +# --------------------------------------------------------------------------- +# Minimal, valid imzML + ibd generator used by the integration tests. +# +# Layout: `width` × `height` spectra, Float32, uncompressed, centroided, five +# peaks per spectrum. One pixel is given a very strong peak at 300.0 Da so the +# tests can assert that ion-image extraction actually finds signal. +# --------------------------------------------------------------------------- + +function write_synthetic_imzml(dir::AbstractString; + width::Int=4, height::Int=3, + mzs::Vector{Float64}=[100.0, 200.0, 300.0, 400.0, 500.0]) + mkpath(dir) + base = joinpath(dir, "synthetic") + imzml_path = base * ".imzML" + ibd_path = base * ".ibd" + + n = width * height + offsets = Vector{Tuple{Int64,Int64,Int64,Int64}}(undef, n) # mz_off, mz_len, int_off, int_len + + open(ibd_path, "w") do io + # JuliaMSI's parser ignores arrays whose external offset is 0 (it uses 0 + # as the "unset" sentinel), so keep a small pad at the start of the ibd. + write(io, zeros(UInt8, 16)) + for k in 1:n + x = ((k - 1) % width) + 1 + y = ((k - 1) ÷ width) + 1 + intensities = Float64[10.0 + x, 20.0 + y, 30.0, 40.0, 50.0] + if (x, y) == (2, 2) + intensities[3] = 1000.0 + elseif (x, y) == (4, 3) + intensities[1] = 2000.0 + end + mz_bytes = reinterpret(UInt8, Float32.(mzs)) + int_bytes = reinterpret(UInt8, Float32.(intensities)) + mz_off = position(io) + write(io, mz_bytes) + int_off = position(io) + write(io, int_bytes) + offsets[k] = (Int64(mz_off), Int64(length(mzs)), Int64(int_off), Int64(length(mzs))) + end + end + + open(imzml_path, "w") do io + write(io, """ + + + + + + + + + + + + + + + + + + + + + + + + + + + +""") + for k in 1:n + x = ((k - 1) % width) + 1 + y = ((k - 1) ÷ width) + 1 + mz_off, mz_len, int_off, int_len = offsets[k] + write(io, """ + + + + + + + + + + + + + + + + + + + + + + + +""") + end + write(io, """ + + +""") + end + + return imzml_path +end