Repository navigation
Expand file tree
/
Copy pathreverse-map.jl
More file actions
225 lines (210 loc) · 10.2 KB
/
Copy pathreverse-map.jl
File metadata and controls
225 lines (210 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
using ArgParse, Zarr, Interpolations, StaticArrays, JSON
function infer_stride_align(invmap_path::AbstractString, params::AbstractString)
zattrs_path = joinpath(invmap_path, ".zattrs")
if isfile(zattrs_path)
attrs = JSON.parsefile(zattrs_path)
prov = get(attrs, "provenance", nothing)
if prov isa AbstractDict
runs = get(prov, "runs", Any[])
if !isempty(runs)
p = get(last(runs), "parameters", Dict{String,Any}())
haskey(p, "stride_scale_min") && return Int(p["stride_scale_min"])
end
end
end
m_st = match(r"(?:^|\.)stride([0-9,]+)", params)
m_sc = match(r"(?:^|\.)scales([0-9,]+)", params)
if m_st !== nothing && m_sc !== nothing
stride_min = parse(Int, last(split(m_st.captures[1], ',')))
sc_str = m_sc.captures[1]
s_min = occursin(',', sc_str) ?
minimum(parse.(Int, split(sc_str, ','))) :
minimum(parse.(Int, string.(collect(sc_str))))
return stride_min * (2 ^ s_min)
end
error("Could not infer stride_align from $zattrs_path or params='$params'; pass --stride-align explicitly.")
end
function load_stitch_tile_metadata(invmap_stitch_path::AbstractString, num_tiles::Int)
zattrs_path = joinpath(invmap_stitch_path, ".zattrs")
if isfile(zattrs_path)
attrs = JSON.parsefile(zattrs_path)
if haskey(attrs, "tile_ids") && haskey(attrs, "tile_keys_xy") && haskey(attrs, "tile_shape_s0_yx")
tile_ids = String.(attrs["tile_ids"])
tile_keys_xy = [Tuple{Int,Int}(Int.(k)) for k in attrs["tile_keys_xy"]]
sh = Int.(attrs["tile_shape_s0_yx"])
return tile_ids, tile_keys_xy, (sh[1], sh[2])
end
end
error("Missing tile metadata (tile_ids, tile_keys_xy, tile_shape_s0_yx) in $zattrs_path; pass --tile-shape-yx / --tile-grid-yx.")
end
"""
reverse_map_point(x_s0, y_s0, z_0based, invmap_align;
stride_align, invmap_stitch=nothing, box_stitch=nothing,
tile_ids=nothing, tile_keys_xy=nothing, tile_size_yx=nothing)
Maps a 0-based `(x_s0, y_s0, z_0based)` point in the final aligned `s0` Zarr:
1. Through Step 2 `invmap_align` (`invmapX` or `invmap`, matching `N-planes-warp.jl` + `warp.jl`)
to 0-based `(x_plane, y_plane)` in the pre-alignment plane (`stitched.s0.zarr` or single-tile slice).
2. If `invmap_stitch` is provided, through Step 1 `invmap_stitch` + `box_stitch` (reverse painter's
order `N_tiles:-1:1`) to 0-based `(tile_id, x_raw, y_raw)` in the raw MultiSEM HDF5 tile;
otherwise returns single-tile coordinates `("0-0-0", x_plane, y_plane)`.
Returns a `Dict` that is always valid JSON. If the point lies outside the region covered by the Step 2
inverse map, the plane coordinates (`stitched_s0_xy` / `pre_align_s0_xy`) and `raw_tile` are `nothing`;
if it lies in the stitched plane but on no tile, only `raw_tile` is `nothing`.
"""
function reverse_map_point(x_s0::Real, y_s0::Real, z_0based::Int, invmap_align;
stride_align::Int,
invmap_stitch=nothing,
box_stitch=nothing,
tile_ids::Union{Nothing,Vector{String}}=nothing,
tile_keys_xy::Union{Nothing,Vector{Tuple{Int,Int}}}=nothing,
tile_size_yx::Union{Nothing,Tuple{Int,Int}}=nothing)
z_jl = z_0based + 1
# Step 2: final aligned s0 -> pre-Z-alignment plane (exact mirror of N-planes-warp.jl + warp.jl)
sx = range(0, step=stride_align, length=size(invmap_align, 1))
sy = range(0, step=stride_align, length=size(invmap_align, 2))
inv_x = Float32.(invmap_align[:, :, z_jl, 1])
inv_y = Float32.(invmap_align[:, :, z_jl, 2])
itpx2 = extrapolate(scale(interpolate(inv_x, BSpline(Linear())), sx, sy), NaN32)
itpy2 = extrapolate(scale(interpolate(inv_y, BSpline(Linear())), sx, sy), NaN32)
p1, p2 = Float64(x_s0) + 1.0, Float64(y_s0) + 1.0 # 1-based target pixel as in warp.jl
dx::Float32 = itpx2(p1, p2)
dy::Float32 = itpy2(p1, p2)
# a point outside the region the Step 2 inverse map covers has no source: the interpolant gives NaN
# there, which JSON cannot represent, so report it as nulls and let the caller carry on with the
# other points
if !(isfinite(dx) && isfinite(dy))
return Dict(
"z" => z_0based,
"final_s0_xy" => [Float64(x_s0), Float64(y_s0)],
(invmap_stitch === nothing ? "pre_align_s0_xy" : "stitched_s0_xy") => nothing,
"raw_tile" => nothing,
)
end
x_stitched = Float64(x_s0) + dx
y_stitched = Float64(y_s0) + dy
if invmap_stitch === nothing
return Dict(
"z" => z_0based,
"final_s0_xy" => [Float64(x_s0), Float64(y_s0)],
"pre_align_s0_xy" => [x_stitched, y_stitched],
"raw_tile" => Dict(
"tile_index" => 1,
"tile_id" => "0-0-0",
"tile_xy" => [0, 0],
"x_raw" => x_stitched,
"y_raw" => y_stitched,
),
)
end
# Step 1: stitched.s0 -> raw unstitched tile (0-based x_raw, y_raw)
img_h, img_w = tile_size_yx
box_z = box_stitch[:, :, z_jl] # Zarr.jl reverses [nz, N, 9] -> (9, N, nz)
inv1_z = invmap_stitch[:, :, :, :, z_jl] # [nz, N, 2, H_pad, W_pad] -> (W_pad, H_pad, 2, N, nz)
n_tiles = size(box_z, 2)
chosen = nothing
for t in n_tiles:-1:1
x0, y0, w, h, st, mt, mb, ml, mr = Int.(box_z[:, t])
st <= 0 && error("Uninitialized stitched-invmap-box at z=$z_0based")
# render_tiles out_box spans [x0 + st, x0 + (w - 1)*st)
if (x0 + st <= x_stitched < x0 + (w - 1) * st) && (y0 + st <= y_stitched < y0 + (h - 1) * st)
gx = range(x0, step=st, length=w)
gy = range(y0, step=st, length=h)
itpx1 = extrapolate(scale(interpolate(inv1_z[1:w, 1:h, 1, t], BSpline(Linear())), gx, gy), NaN32)
itpy1 = extrapolate(scale(interpolate(inv1_z[1:w, 1:h, 2, t], BSpline(Linear())), gx, gy), NaN32)
x_raw = Float64(itpx1(x_stitched, y_stitched))
y_raw = Float64(itpy1(x_stitched, y_stitched))
# sofima's render_tiles decides a tile's footprint by Lanczos-warping a mask that is 1 on raw
# pixels ml : img_w-(mr+1)-1 (likewise in y) and keeping what rounds to non-zero, so the
# footprint ends half a pixel outside the first and last masked pixels
if (ml - 0.5 <= x_raw < img_w - (mr + 1) - 0.5) && (mt - 0.5 <= y_raw < img_h - (mb + 1) - 0.5)
chosen = Dict(
"tile_index" => t,
"tile_id" => tile_ids[t],
"tile_xy" => collect(tile_keys_xy[t]),
"x_raw" => x_raw,
"y_raw" => y_raw,
)
break
end
end
end
return Dict(
"z" => z_0based,
"final_s0_xy" => [Float64(x_s0), Float64(y_s0)],
"stitched_s0_xy" => [x_stitched, y_stitched],
"raw_tile" => chosen,
)
end
if abspath(PROGRAM_FILE) == @__FILE__
s = ArgParseSettings()
@add_arg_table! s begin
"--align-basepath"
help = "Directory containing invmapX.<params>.zarr or invmap.<params>.zarr"
required = true
"--stitch-basepath"
help = "Directory containing stitched-invmap.s0.zarr and stitched-invmap-box.s0.zarr (omit for single-tile stacks)"
default = ""
"--params"
help = "Alignment parameter string (e.g. patch256,128,64.stride64,32,16.scales12.k00.01.k0.1)"
required = true
"--level"
help = "Multiscale pyramid level of input points (0 for s0, 1 for s1, ...)"
arg_type = Int
default = 0
"--stride-align"
help = "Override Step 2 invmap grid stride in s0 pixels (0 = infer from .zattrs or --params)"
arg_type = Int
default = 0
"--tile-shape-yx"
help = "Fallback raw s0 tile height,width (e.g. 8250,7042) if stitched-invmap.s0.zarr/.zattrs is absent"
default = ""
"--tile-grid-yx"
help = "Fallback tile grid rows,cols (e.g. 2,3 -> tile IDs 0-r-c) if stitched-invmap.s0.zarr/.zattrs is absent"
default = ""
"points"
nargs = '+'
help = "0-based points formatted as x,y,z (Neuroglancer order)"
end
args = parse_args(ARGS, s)
invx_path = joinpath(args["align-basepath"], string("invmapX.", args["params"], ".zarr"))
inv_path = isdir(invx_path) ? invx_path : joinpath(args["align-basepath"], string("invmap.", args["params"], ".zarr"))
inv2 = zopen(inv_path)
stride_align = args["stride-align"] > 0 ? args["stride-align"] : infer_stride_align(inv_path, args["params"])
inv1, box1, tile_ids, tile_keys_xy, tile_size_yx = if !isempty(args["stitch-basepath"])
inv1_path = joinpath(args["stitch-basepath"], "stitched-invmap.s0.zarr")
box1_path = joinpath(args["stitch-basepath"], "stitched-invmap-box.s0.zarr")
ia = zopen(inv1_path)
ba = zopen(box1_path)
t_ids, t_keys, t_sz = if !isempty(args["tile-shape-yx"]) && !isempty(args["tile-grid-yx"])
r_cnt, c_cnt = parse.(Int, split(args["tile-grid-yx"], ','))
th, tw = parse.(Int, split(args["tile-shape-yx"], ','))
keys = [(x, y) for y in 0:(r_cnt - 1) for x in 0:(c_cnt - 1)]
ids = ["0-$y-$x" for (x, y) in keys]
ids, keys, (th, tw)
else
load_stitch_tile_metadata(inv1_path, size(ba, 2))
end
ia, ba, t_ids, t_keys, t_sz
else
nothing, nothing, nothing, nothing, nothing
end
scale_f = 2 ^ args["level"]
trans = scale_f / 2.0 - 0.5
out = []
for pstr in args["points"]
px, py, pz = parse.(Float64, split(pstr, ","))
xs0 = px * scale_f + trans
ys0 = py * scale_f + trans
zs0 = round(Int, pz * scale_f + trans)
push!(out, reverse_map_point(
xs0, ys0, zs0, inv2;
stride_align=stride_align,
invmap_stitch=inv1,
box_stitch=box1,
tile_ids=tile_ids,
tile_keys_xy=tile_keys_xy,
tile_size_yx=tile_size_yx,
))
end
println(JSON.json(out, 2))
end