Skip to content

Array and signal utilities ​

These helpers act on arrays and numeric values. They do not establish acquisition units, geometry conventions or a reconstruction model automatically. Use host arrays for the CPU example below, and consult the source-generated contracts before relying on boundary behavior.

A complete CPU example ​

julia
using HighOrderMRI
using LinearAlgebra

# Input already represents Hz/m; no gyromagnetic conversion is done here.
gradient = [0.0 1.0; 2.0 1.0; 4.0 1.0; 6.0 1.0]
dt = 0.5                         # seconds for this numerical example
trajectory = grad2traj(gradient, dt)   # cycles/m, first row zero
interval_average = traj2grad(trajectory, dt)
trajectory_f32 = f32(trajectory)

image = reshape(Float64.(1:16), 4, 4)
cropped = get_center_crop(image, Int64(2), Int64(2))
scaled = normalization(image)
standardized = standardization(image)
mask = get_mask(image; threshold=8.0)
metadata = struct_to_dict((spacing=1.0, description="numerical example"))

spectrum = convert_fft(complex.(image))
restored = convert_ifft(spectrum)
@assert size(interval_average) == (3, 2)
@assert cropped == image[2:3, 2:3]
@assert norm(restored - image) / norm(image) < 1e-12

Differencing a trapezoidal cumulative integral returns interval-average gradients, not the original endpoint samples. The transform pair above uses its own Cartesian array normalization; it is not a substitute for a high-order encoding operator or density-weighted reconstruction.

Storage and precision ​

gpu uses the current CUDA device and can fall back to returning its input when CUDA is unavailable. Its CUDA.cu conversion may also change precision. Use an explicit CuArray conversion when you need to preserve a chosen numeric type. f32/f64 change supported leaf precision; they do not select a device.

gpu ​

julia
gpu(x)

Move supported numeric leaves to the current CUDA device using the package's Functors/Adapt traversal. If CUDA is unavailable, return x unchanged and cache that availability result. This fallback is not an explicit device-selection API.

The adaptor calls CUDA.cu, which can convert floating-point precision. Use an explicit CuArray conversion when preserving a chosen element type matters. Traversal follows Functors support; it is not an unconditional deep copy of an arbitrary object. No GPU is selected by this function.

Source: src/utils/GPUFunctions.jl

cpu ​

julia
cpu(x)

Adapt supported array leaves to ordinary CPU arrays through Functors/Adapt. Ranges are retained. The result follows the input object's supported traversal; already-host storage need not be copied independently. This function does not change numeric precision deliberately.

Source: src/utils/GPUFunctions.jl

f32 ​

julia
f32(m)

Convert supported real numeric array leaves to Float32 and complex leaves to ComplexF32 through Functors/Adapt. Boolean arrays remain unchanged. This is a precision conversion, not a CPU/GPU transfer; traversal follows the supported object structure.

Source: src/utils/GPUFunctions.jl

f64 ​

julia
f64(m)

Convert supported real numeric array leaves to Float64 and complex leaves to ComplexF64 through Functors/Adapt. Boolean arrays remain unchanged. This is a precision conversion, not a CPU/GPU transfer; traversal follows the supported object structure.

Source: src/utils/GPUFunctions.jl

Integration and differentiation ​

No gyromagnetic ratio or physical-unit conversion is included. For magnetic field gradients in T/m, account for the appropriate conversion before treating the integral as cycles/m. See Symbols and notation.

grad2traj ​

julia
grad2traj(x::AbstractArray{T}, dt::S; dim::Int = 1) where {T <: Real, S <: Real}

Cumulatively integrate x by the trapezoidal rule along dim, prepending a zero sample. For a nonempty selected axis, the output has the input shape. The accumulated increments are (x[j+1] + x[j]) * dt / 2; arithmetic determines the result precision, so it need not equal the input element type.

Use a valid dimension and floating-point host arrays. No gyromagnetic ratio, unit conversion, or initial trajectory offset is applied. For example, Hz/m integrated over seconds gives cycles/m; a magnetic gradient in T/m requires the appropriate gyromagnetic conversion before this helper represents k-space.

Source: src/utils/conversion.jl

traj2grad ​

julia
traj2grad(x::AbstractArray{T}, dt::S; dim::Int = 1) where {T <: Real, S <: Real}

Compute adjacent finite differences (x[j+1] - x[j]) / dt along dim. The selected output axis is shorter by one; other dimensions are unchanged. There is no padded endpoint or differentiation of a separately supplied time vector. Use a nonzero dwell and compatible physical units. No gyromagnetic conversion is applied, and arithmetic determines the output precision.

Source: src/utils/conversion.jl

Resizing and central regions ​

imresize_complex interpolates magnitude and wrapped phase separately. Phase near the -pi/pi branch cut can therefore interpolate incorrectly; this is not a phase-unwrapping or geometry-aware resampling method.

get_center_crop currently returns all zeros if either requested axis equals the corresponding input axis. Its example above deliberately uses a strict crop on both axes. The limitation is retained in the implementation and documented below. normalization and standardization likewise produce nonfinite results for constant arrays because their denominators vanish.

imresize_real ​

julia
imresize_real(img::AbstractArray{T}, dims::Tuple) where T <: Real

Resize a real array with ImageTransformations.imresize. length(dims) must equal ndims(img). Interpolation settings and output numeric behavior are those of the dependency's default imresize call; this is not a physical-coordinate or geometry-aware resampling routine.

Source: src/utils/ImageResize.jl

imresize_complex ​

julia
imresize_complex(img::AbstractArray{Complex{T}}, dims::Tuple) where T <: Real

Resize magnitude and wrapped phase separately using the default imresize, then return resized_magnitude .* exp.(im .* resized_phase). length(dims) must equal ndims(img).

The phase is not unwrapped. Values near the -pi/pi branch cut can interpolate through zero phase and create an incorrect complex transition. This method is not equivalent to interpolating real and imaginary parts, and does not promise phase-preserving physical resampling.

Source: src/utils/ImageResize.jl

get_center_range ​

julia
get_center_range(x::Int64, x_range::Int64)

Return floor(x/2) - floor(x_range/2) + 1 : floor(x/2) + ceil(x_range/2) as an Int64 unit range. Here x is the full axis length and x_range is the requested length, not a centre coordinate. Use positive lengths; containment and bounds are not validated. Even/odd cases follow this exact index convention.

Source: src/utils/ImageProcess.jl

get_center_crop ​

julia
get_center_crop(image::AbstractArray{T}, out_x::Int64, out_y::Int64) where T <: Number

Centre-crop or zero-pad the first two axes of a 2D or 3D numeric array. The requested sizes must be positive Int64 values. The third axis, when present, is retained, and the output has the input element type.

Current limitation ​

If either requested spatial size equals the corresponding input size, none of the four copy branches executes: the result is all zeros. This includes an unchanged requested size. Do not use this helper for that case without an explicit caller-side alternative. The limitation is documented here, not fixed by this documentation change.

Source: src/utils/ImageProcess.jl

get_factors ​

julia
get_factors(num::Int64)::Tuple{Int64, Int64}

For a positive Int64, return an ascending pair (a, b) with a*b == num selected near the square root. The pair satisfies a <= b, including square numbers. Use positive input; the implementation has no explicit domain guard for zero or negative values.

Source: src/utils/utils.jl

normalization ​

julia
normalization(img::AbstractArray{T, 2}) where T <: Real

Apply min-max normalization (img - minimum(img)) / (maximum(img) - minimum(img)) to a real matrix. This rescales image intensity; it does not preserve absolute quantitative calibration. A constant image has a zero denominator and produces nonfinite values in the current implementation. Empty/nonfinite inputs are not handled by a separate validation policy.

Source: src/utils/ImageProcess.jl

standardization ​

julia
standardization(img::AbstractArray{T, 2}) where T <: Real

Subtract the mean and divide by the population standard deviation std(img; corrected=false) of a real matrix. A constant image has zero standard deviation and produces nonfinite values in the current implementation. This helper does not preserve absolute intensity or perform robust outlier handling.

Source: src/utils/ImageProcess.jl

get_mask ​

julia
get_mask(image; threshold = 0)

Return a Boolean array of the input shape whose entries satisfy abs(image) > threshold. The comparison is strict; values equal to the threshold are excluded. This is an intensity threshold, not a geometry or noise-estimation mask. NaN magnitudes compare false.

Source: src/utils/utils.jl

Array transforms and metadata ​

convert_fft ​

julia
convert_fft(x; dims = [1, 2])

Apply the centred FFT along dims and divide by N = prod(size(x)[dims]). The default transforms the first two dimensions. The exact convention is fftshift(fft(ifftshift(x,dims),dims),dims) / N. This is a Cartesian array transform, not the package's physical high-order encoding operator or its masked normalization.

Source: src/Recon/recon_ifft.jl

convert_ifft ​

julia
convert_ifft(x; dims = [1, 2])

Apply the centred inverse FFT along dims and multiply by N = prod(size(x)[dims]). The default transforms the first two dimensions. The exact convention is fftshift(ifft(ifftshift(x,dims),dims),dims) * N. Together with convert_fft and matching dimensions, this forms an inverse array-transform pair up to floating-point error.

Source: src/Recon/recon_ifft.jl

struct_to_dict ​

julia
struct_to_dict(x)

Return a dictionary whose keys are string field names and whose values are getfield(x, name). The conversion is shallow: array or mutable field values remain shared with x. It does not recursively serialize nested objects.

Source: src/utils/io.jl

Scope ​

The repository's src/utils/ISMRMRD.jl and src/utils/ShiftFOV.jl are not loaded by the package module and are not supported public entry points. This migration does not activate them or invent API documentation for unfinished code.

HighOrderMRI.jl documentation · v0.1.1 · code 5d6ac72 · docs 5d6ac72