licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
3281
""" segmentation_F( segmentation_B_not_ice_mask::Matrix{Gray{Float64}}, segmentation_B_ice_intersect::BitMatrix, segmentation_B_watershed_intersect::BitMatrix, ice_labels::Vector{Int64}, cloudmask::BitMatrix, landmask::BitMatrix; min_area_opening::Int64=20 ) Cleans up past segmentation images with morphological operations, and applies the results of prior watershed segmentation, returning the final cleaned image for tracking with ice floes segmented and isolated. # Arguments - `segmentation_B_not_ice_mask`: gray image output from `segmentation_b.jl` - `segmentation_B_ice_intersect`: binary mask output from `segmentation_b.jl` - `segmentation_B_watershed_intersect`: ice pixels, output from `segmentation_b.jl` - `ice_labels`: vector of pixel coordinates output from `find_ice_labels.jl` - `cloudmask.jl`: bitmatrix cloudmask for region of interest - `landmask.jl`: bitmatrix landmask for region of interest - `min_area_opening`: threshold used for area opening; pixel groups greater than threshold are retained """ function segmentation_F( segmentation_B_not_ice_mask::Matrix{Gray{Float64}}, segmentation_B_ice_intersect::BitMatrix, segmentation_B_watershed_intersect::BitMatrix, ice_labels::Vector{Int64}, cloudmask::BitMatrix, landmask::BitMatrix; min_area_opening::Int64=20 )::BitMatrix IceFloeTracker.apply_landmask!(segmentation_B_not_ice_mask, landmask) ice_leads = .!segmentation_B_watershed_intersect .* segmentation_B_ice_intersect ice_leads .= .!ImageMorphology.area_opening(ice_leads; min_area=min_area_opening, connectivity=2) not_ice = IceFloeTracker.MorphSE.dilate( segmentation_B_not_ice_mask, IceFloeTracker.MorphSE.strel_diamond((5, 5)) ) IceFloeTracker.MorphSE.mreconstruct!( IceFloeTracker.MorphSE.dilate, not_ice, complement.(not_ice), complement.(segmentation_B_not_ice_mask), ) reconstructed_leads = (not_ice .* ice_leads) .+ (60 / 255) leads_segmented = IceFloeTracker.kmeans_segmentation(reconstructed_leads, ice_labels) .* .!segmentation_B_watershed_intersect @info("Done with k-means segmentation") leads_segmented_broken = IceFloeTracker.hbreak(leads_segmented) leads_branched = IceFloeTracker.branch(leads_segmented_broken) leads_filled = .!ImageMorphology.imfill(.!leads_branched, 0:1) leads_opened = IceFloeTracker.branch( ImageMorphology.area_opening( leads_filled; min_area=min_area_opening, connectivity=2 ), ) leads_bothat = IceFloeTracker.MorphSE.bothat( leads_opened, IceFloeTracker.MorphSE.strel_diamond((5, 5)) ) .> 0.499 leads = convert(BitMatrix, (complement.(leads_bothat) .* leads_opened)) ImageMorphology.area_opening!(leads, leads; min_area=min_area_opening, connectivity=2) leads_bothat_filled = (IceFloeTracker.MorphSE.fill_holes(leads) .* cloudmask) floes = IceFloeTracker.branch(leads_bothat_filled) floes_opened = IceFloeTracker.MorphSE.opening(floes, centered(IceFloeTracker.se_disk4())) IceFloeTracker.MorphSE.mreconstruct!( IceFloeTracker.MorphSE.dilate, floes_opened, floes, floes_opened ) return floes_opened end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1662
""" watershed_ice_floes(intermediate_segmentation_image;) Performs image processing and watershed segmentation with intermediate files from segmentation_b.jl to further isolate ice floes, returning a binary segmentation mask indicating potential sparse boundaries of ice floes. # Arguments -`intermediate_segmentation_image`: binary cloudmasked and landmasked intermediate file from segmentation B, either `SegB.not_ice_bit` or `SegB.ice_intersect` """ function watershed_ice_floes(intermediate_segmentation_image::BitMatrix)::BitMatrix features = Images.feature_transform(.!intermediate_segmentation_image) distances = 1 .- Images.distance_transform(features) seg_mask = ImageSegmentation.hmin_transform(distances, 2) seg_mask_bool = seg_mask .> 0 markers = Images.label_components(seg_mask_bool) segment = ImageSegmentation.watershed(distances, markers) labels = ImageSegmentation.labels_map(segment) borders = Images.isboundary(labels) return borders end """ watershed_product(watershed_B_ice_intersect, watershed_B_not_ice;) Intersects the outputs of watershed segmentation on intermediate files from segmentation B, indicating potential sparse boundaries of ice floes. # Arguments - `watershed_B_ice_intersect`: binary segmentation mask from `watershed_ice_floes` - `watershed_B_not_ice`: binary segmentation mask from `watershed_ice_floes` """ function watershed_product( watershed_B_ice_intersect::BitMatrix, watershed_B_not_ice::BitMatrix; )::BitMatrix ## Intersect the two watershed files watershed_intersect = watershed_B_ice_intersect .* watershed_B_not_ice return watershed_intersect end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
21865
function make_landmask_se() begin BitMatrix( reshape( [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ], 99, 99, ), ) end end se_disk4() = begin se = zeros(Bool, 7, 7) se[4, 4] = 1 bwdist(se) .<= 3.6 end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
6696
# Helper functions """ make_filename() Makes default filename with timestamp. """ function make_filename()::String return "persisted_img-" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" end function make_filename(fname::T, ext::T=".png")::T where {T<:AbstractString} return timestamp(fname) * ext end """ timestamp(fname) Attach timestamp to `fname`. """ function timestamp(fname::String) ts = Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") return fname * "-" * ts end """ fname_ext_split(fname) Split `"fname.ext"` into `"fname"` and `"ext"`. """ function fname_ext_split(fname::String) return (name=fname[1:(end - 4)], ext=fname[(end - 2):end]) end """ fname_ext_splice(fname, ext) Join `"fname"` and `"ext"` with `'.'`. """ function fname_ext_splice(fname::String, ext::String) return fname * '.' * ext end """ check_fname(fname) Checks `fname` does not exist in current directory; throws an assertion if this condition is false. # Arguments - `fname`: String object or Symbol to a reference to a String representing a path. """ function check_fname(fname::Union{String,Symbol,Nothing}=nothing)::String if fname isa String # then use as filename check_name = fname elseif fname isa Symbol check_name = eval(fname) # get the object represented by the symbol elseif isnothing(fname) # nothing provided so make a filename check_name = make_filename() end # check name does not exist in wd isfile(check_name) && error("$check_name already exists in $(pwd())") return check_name end """ loadimg(; dir::String, fname::String) Load an image from `dir` with filename `fname` into a matrix of `Float64` values. Returns the loaded image. """ function loadimg(; dir::String, fname::String) return joinpath(dir, fname) |> load |> x-> float64.(x) end """ add_padding(img, style) Extrapolate the image `img` according to the `style` specifications type. Returns the extrapolated image. # Arguments - `img`: Image to be padded. - `style`: A supported type (such as `Pad` or `Fill`) representing the extrapolation style. See the relevant [documentation](https://juliaimages.org/latest/function_reference/#ImageFiltering) for details. See also [`remove_padding`](@ref) """ function add_padding(img, style::Union{Pad,Fill})::Matrix return collect(Images.padarray(img, style)) end """ remove_padding(paddedimg, border_spec) Removes padding from the boundary of padded image `paddedimg` according to the border specification `border_spec` type. Returns the cropped image. # Arguments - `paddedimg`: Pre-padded image. - `border_spec`: Type representing the style of padding (such as `Pad` or `Fill`) with which `paddedimg` is assumend to be pre-padded. Example: `Pad((1,2), (3,4))` specifies 1 row on the top, 2 columns on the left, 3 rows on the bottom, and 4 columns on the right boundary. See also [`add_padding`](@ref) """ function remove_padding(paddedimg, border_spec::Union{Pad,Fill})::Matrix top, left = border_spec.lo bottom, right = border_spec.hi return paddedimg[(top + 1):(end - bottom), (left + 1):(end - right)] end """ imextendedmin(img) Mimics MATLAB's imextendedmin function that computes the extended-minima transform, which is the regional minima of the H-minima transform. Regional minima are connected components of pixels with a constant intensity value. This function returns a transformed bitmatrix. # Arguments - `img`: image object - `h`: suppress minima below this depth threshold - `conn`: neighborhood connectivity; in 2D 1 = 4-neighborhood and 2 = 8-neighborhood """ function imextendedmin(img::AbstractArray; h::Int=2, conn::Int=2)::BitMatrix mask = ImageSegmentation.hmin_transform(img, h) mask_minima = Images.local_minima(mask; connectivity=conn) return Bool.(mask_minima) end """ bwdist(bwimg) Distance transform for binary image `bwdist`. """ function bwdist(bwimg::AbstractArray{Bool})::AbstractArray{Float64} return Images.distance_transform(Images.feature_transform(bwimg)) end """ padnhood(img, I, nhood) Pad the matrix `img[nhood]` with zeros according to the position of `I` within the edges`img`. Returns `img[nhood]` if `I` is not an edge index. """ function padnhood(img, I, nhood) # adaptive padding maxr, maxc = size(img) tofill = SizedMatrix{3,3}(zeros(Int, 3, 3)) @views if I == CartesianIndex(1, 1) # top left corner` tofill[2:3, 2:3] = img[nhood] elseif I == CartesianIndex(maxr, 1) # bottom left corner tofill[1:2, 2:3] = img[nhood] elseif I == CartesianIndex(1, maxc) # top right corner tofill[2:3, 1:2] = img[nhood] elseif I == CartesianIndex(maxr, maxc) # bottom right corner tofill[1:2, 1:2] = img[nhood] elseif I[1] == 1 # top edge (first row) tofill[2:3, 1:3] = img[nhood] elseif I[2] == 1 # left edge (first col) tofill[1:3, 2:3] = img[nhood] elseif I[1] == maxr # bottom edge (last row) tofill[1:2, 1:3] = img[nhood] elseif I[2] == maxc # right edge (last row) tofill[1:3, 1:2] = img[nhood] else tofill = img[nhood] end return tofill end """ _bin9todec(v) Get decimal representation of a bit vector `v` with the leading bit at its leftmost posistion. Example ``` julia> _bin9todec([0 0 0 0 0 0 0 0 0]) 0 julia> _bin9todec([1 1 1 1 1 1 1 1 1]) 511 ``` """ function _bin9todec(v::AbstractArray)::Int64 return sum(vec(v) .* 2 .^ (0:(length(v) - 1))) end """ _operator_lut(I, img, nhood, lut1, lut2) Look up the neighborhood `nhood` in lookup tables `lut1` and `lut2`. Handles cases when the center of `nhood` is on the edge of `img` using data in `I`. """ function _operator_lut( I::CartesianIndex{2}, img::AbstractArray{Bool}, nhood::CartesianIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}}, lut1::Vector{Int64}, lut2::Vector{Int64}, )::SVector{2,Int64} # corner pixels length(nhood) == 4 && return @SVector [false, 0] val = IceFloeTracker._bin9todec(_pad_handler(I, img, nhood)) + 1 return @SVector [lut1[val], lut2[val]] end function _operator_lut( I::CartesianIndex{2}, img::AbstractArray{Bool}, nhood::CartesianIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}}, lut::Vector{T}, )::T where {T} # for bridge # corner pixels length(nhood) == 4 && return false # for bridge and some other operations like hbreak, branch return lut[_bin9todec(_pad_handler(I, img, nhood)) + 1] end function _pad_handler(I, img, nhood) (length(nhood) == 6) && return padnhood(img, I, nhood) # edge pixels return @view img[nhood] end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
4009
module CenterIndexedArrays using Interpolations, OffsetArrays using OffsetArrays: IdentityUnitRange export CenterIndexedArray include("symrange.jl") """ A `CenterIndexedArray` is one for which the array center has indexes `0,0,...`. Along each coordinate, allowed indexes range from `-n:n`. CenterIndexedArray(A) "converts" `A` into a CenterIndexedArray. All the sizes of `A` must be odd. """ struct CenterIndexedArray{T,N,A<:AbstractArray} <: AbstractArray{T,N} data::A halfsize::NTuple{N,Int} function CenterIndexedArray{T,N,A}(data::A) where {T,N,A<:AbstractArray} new{T,N,A}(data, _halfsize(data)) end end CenterIndexedArray(A::AbstractArray{T,N}) where {T,N} = CenterIndexedArray{T,N,typeof(A)}(A) CenterIndexedArray{T,N}(::UndefInitializer, sz::Vararg{<:Integer,N}) where {T,N} = CenterIndexedArray(Array{T,N}(undef, sz...)) CenterIndexedArray{T,N}(::UndefInitializer, sz::NTuple{N,Integer}) where {T,N} = CenterIndexedArray(Array{T,N}(undef, sz)) CenterIndexedArray{T}(::UndefInitializer, sz::Vararg{<:Integer,N}) where {T,N} = CenterIndexedArray{T,N}(undef, sz...) CenterIndexedArray{T}(::UndefInitializer, sz::NTuple{N,Integer}) where {T,N} = CenterIndexedArray{T,N}(undef, sz) # This is the AbstractArray default, but do this just to be sure Base.IndexStyle(::Type{A}) where {A<:CenterIndexedArray} = IndexCartesian() Base.size(A::CenterIndexedArray) = size(A.data) Base.axes(A::CenterIndexedArray) = map(SymRange, A.halfsize) const SymAx = Union{SymRange, Base.Slice{SymRange}} Base.axes(r::Base.Slice{SymRange}) = (r.indices,) function Base.similar(A::CenterIndexedArray, ::Type{T}, inds::Tuple{SymAx,Vararg{SymAx}}) where T data = Array{T}(undef, map(length, inds)) CenterIndexedArray(data) end function Base.similar(::Type{T}, inds::Tuple{SymAx, Vararg{SymAx}}) where T data = Array{T}(undef, map(length, inds)) CenterIndexedArray(data) end # This is incomplete: ideally we wouldn't need SymAx in the first slot # as long as there was at least one SymAx. function Base.similar(A::CenterIndexedArray, ::Type{T}, inds::Tuple{SymAx,Vararg{Union{Int,<:IdentityUnitRange,SymAx}}}) where T torange(n) = isa(n, Int) ? Base.OneTo(n) : n return OffsetArray{T}(undef, map(torange, inds)) end function _halfsize(A::AbstractArray) all(isodd, size(A)) || error("Must have all-odd sizes") map(n->n>>UInt(1), size(A)) end @inline function Base.getindex(A::CenterIndexedArray{T,N}, i::Vararg{Int,N}) where {T,N} @boundscheck checkbounds(A, i...) @inbounds val = A.data[map(offset, A.halfsize, i)...] val end Base.@propagate_inbounds Base.getindex(A::CenterIndexedArray{T,N,I}, i::Vararg{Int,N}) where {T,N,I<:AbstractInterpolation} = _getindex(A, i...) Base.@propagate_inbounds Base.getindex(A::CenterIndexedArray{T,N,I}, i::Vararg{Number,N}) where {T,N,I<:AbstractInterpolation} = _getindex(A, i...) @inline function _getindex(A::CenterIndexedArray{T,N,I}, i::Vararg{Number,N}) where {T,N,I<:AbstractInterpolation} @boundscheck checkbounds(A, i...) @inbounds val = A.data(map(offset, A.halfsize, i)...) val end Base.throw_boundserror(A::CenterIndexedArray, I) = (Base.@_noinline_meta; throw(BoundsError(A, I))) offset(off, i) = off+i+1 @inline function Base.setindex!(A::CenterIndexedArray{T,N}, v, i::Vararg{Int,N}) where {T,N} @boundscheck checkbounds(A, i...) @inbounds A.data[map(offset, A.halfsize, i)...] = v v end Base.BroadcastStyle(::Type{<:CenterIndexedArray}) = Broadcast.ArrayStyle{CenterIndexedArray}() function Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{CenterIndexedArray}}, ::Type{ElType}) where ElType similar(ElType, axes(bc)) end Base.parent(A::CenterIndexedArray) = A.data function Base.showarg(io::IO, A::CenterIndexedArray, toplevel) print(io, "CenterIndexedArray(") Base.showarg(io, parent(A), false) print(io, ')') toplevel && print(io, " with eltype ", eltype(A)) end include("deprecated.jl") end # module
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
200
@deprecate CenterIndexedArray(::Type{T}, dims) where {T} CenterIndexedArray{T}(undef, dims...) @deprecate CenterIndexedArray(::Type{T}, dims...) where {T} CenterIndexedArray{T}(undef, dims...)
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1586
## SymRange, an AbstractUnitRange that's symmetric around 0 # These are used as axes for CenterIndexedArrays struct SymRange <: AbstractUnitRange{Int} n::Int # goes from -n:n end function SymRange(r::AbstractUnitRange) first(r) == -last(r) || error("cannot convert $r to a SymRange") SymRange(last(r)) end Base.first(r::SymRange) = -r.n Base.last(r::SymRange) = r.n Base.axes(r::SymRange) = (r,) @inline Base.unsafe_indices(r::SymRange) = (r,) function iterate(r::SymRange) r.n == 0 && return nothing first(r), first(r) end function iterate(r::SymRange, s) s == last(r) && return nothing copy(s+1), s+1 end @inline function Base.getindex(v::SymRange, i::Int) @boundscheck abs(i) <= v.n || Base.throw_boundserror(v, i) return i end Base.intersect(r::SymRange, s::SymRange) = SymRange(min(last(r), last(s))) @inline function Base.getindex(r::SymRange, s::SymRange) @boundscheck checkbounds(r, s) s end @inline function Base.getindex(r::SymRange, s::AbstractUnitRange{<:Integer}) @boundscheck checkbounds(r, s) return s end # TODO: should we be worried about the mismatch in axes? # And should `convert(SymRange, r)` fail if axes(r) isn't the same as the result? Base.promote_rule(::Type{SymRange}, ::Type{UR}) where {UR<:AbstractUnitRange} = UR Base.promote_rule(::Type{UnitRange{T2}}, ::Type{SymRange}) where {T2} = UnitRange{promote_type(T2, Int)} Base.show(io::IO, r::SymRange) = print(io, "SymRange(", repr(last(r)), ')') if isdefined(Base, :reduced_index) Base.reduced_index(r::SymRange) = SymRange(0) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1524
module QuadDIRECT using LinearAlgebra using StaticArrays, PositiveFactorizations export Box, CountedFunction, LoggedFunction export leaves, value, numevals, analyze, analyze!, minimize export splitprint, splitprint_colored, treeprint include("types.jl") include("util.jl") include("quadratic_model.jl") include("algorithm.jl") # Convenience methods function analyze(f, x0::AbstractVector{<:Real}, lower::AbstractVector{<:Real}, upper::AbstractVector{<:Real}; kwargs...) inds = LinearIndices(x0) LinearIndices(lower) == LinearIndices(upper) == inds || error("lengths must match") splits = similar(x0, Vector{Float64}) for i in inds lo, hi, xi = lower[i], upper[i], x0[i] @assert(lo<=xi<=hi) lo = max(xi-1, (xi+lo)/2) hi = min(xi+1, (xi+hi)/2) xi = xi == lo ? (xi+hi)/2 : xi == hi ? (xi+lo)/2 : xi @assert(lo < xi < hi) @assert isfinite(lo) && isfinite(xi) && isfinite(hi) splits[i] = [lo, xi, hi] end return analyze(f, splits, lower, upper; kwargs...) end function analyze(f, x0::AbstractVector{<:Real}; kwargs...) return analyze(f, x0, fill(-Inf, length(x0)), fill(Inf, length(x0)); kwargs...) end function analyze(f, lower::AbstractVector{<:Real}, upper::AbstractVector{<:Real}; kwargs...) x0 = (lower .+ upper)./2 for i in eachindex(x0) if !isfinite(x0[i]) x0[i] = clamp(0, lower[i], upper[i]) end end return analyze(f, x0, lower, upper; kwargs...) end end # module
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
29262
function init(f, xsplits, lower::AbstractVector, upper::AbstractVector) # Validate the inputs n = length(lower) length(upper) == length(xsplits) == n || throw(DimensionMismatch("inconsistent dimensionality among lower, upper, and splits")) for i = 1:n xsi = xsplits[i] length(xsi) == 3 || throw(DimensionMismatch("3 values along each dimension required, got $(xsi) along dimension $i")) lower[i] <= xsi[1] < xsi[2] < xsi[3] <= upper[i] || error("splits must be in strictly increasing order and lie between lower and upper, got $xsi along dimension $i") all(isfinite, xsi) || error("not all splits along dimension $i are finite") end # Compute a consistent eltype xs1 = xsplits[1] Tx = promote_type(typeof(xs1[1]), typeof(xs1[2]), typeof(xs1[3])) for i = 2:n xsi = xsplits[i] Tx = promote_type(Tx, typeof(xsi[1]), typeof(xsi[2]), typeof(xsi[3])) end Tx = boxeltype(Tx) x0 = Tx[x[2] for x in xsplits] box, xstar = _init(f, copy(x0), xsplits, lower, upper) box, x0, xstar end @noinline function _init(f, xstar, xsplits, lower, upper) T = boxeltype(promote_type(eltype(xstar), eltype(lower), eltype(upper))) n = length(xstar) root = box = Box{T,n}() xtmp = copy(xstar) fcur = dummyvalue(T) for i = 1:n box = split!(box, f, xtmp, i, xsplits[i], lower[i], upper[i], xstar[i], fcur) xcur, fcur = box.parent.xvalues[box.parent_cindex], box.parent.fvalues[box.parent_cindex] xstar = replacecoordinate!(xstar, i, xcur) end box, xstar end function split!(box::Box{T}, f, xtmp, splitdim, xsplit, lower::Real, upper::Real, xcur, fcur) where T # Evaluate f along the splits, keeping track of the best fsplit = MVector3{T}(typemax(T), typemax(T), typemax(T)) fmin, idxmin = typemax(T), 0 for l = 1:3 @assert(isfinite(xsplit[l])) if xsplit[l] == xcur && !isdummy(fcur) ftmp = fcur else xtmp = replacecoordinate!(xtmp, splitdim, xsplit[l]) ftmp = f(xtmp) end if ftmp < fmin fmin = ftmp idxmin = l end fsplit[l] = ftmp end idxmin == 0 && error("function was not finite at any evaluation point $xsplit") if idxmin == 1 && fsplit[1] == fsplit[2] idxmin = 2 # prefer the middle in case of ties end add_children!(box, splitdim, xsplit, fsplit, lower, upper) xtmp = replacecoordinate!(xtmp, splitdim, xsplit[idxmin]) return box.children[idxmin] end # Splits a box. If the "tilt" over the domain of the # box suggests that one of its neighbors might be even lower, # recursively calls itself to split that box, too. # Returns `box, minval`. function autosplit!(box::Box{T}, mes::Vector{<:MELink}, f::WrappedFunction, x0, xtmp, splitdim, xsplitdefaults, lower, upper, minwidth, visited::Set) where T box ∈ visited && error("already visited box") box.qnconverged && return (box, value(box)) if !isleaf(box) # This box already got split along a different dimension box = find_smallest_child_leaf(box) xtmp = position(box, x0) end if splitdim == 0 # If we entered this box from a neighbor, just choose an axis that has been split the least nsplits = count_splits(box) splitdim = argmin(nsplits) if nsplits[splitdim] > 0 # If all dimensions have been split, prefer splitting unbounded dimensions bbs = boxbounds(box, lower, upper) if all(isfinite, bbs[splitdim]) for (i, bb) in enumerate(bbs) if !all(isfinite, bb) splitdim = i break end end end end end xsplitdefault = xsplitdefaults[splitdim] lwr, upr = lower[splitdim], upper[splitdim] p = find_parent_with_splitdim(box, splitdim) if isroot(p) && p.splitdim != splitdim xcur, fcur = x0[splitdim], box.parent.fvalues[box.parent_cindex] split!(box, f, xtmp, splitdim, xsplitdefault, lwr, upr, xcur, fcur) trimschedule!(mes, box, splitdim, x0, lower, upper) return box, minimum(box.fvalues) end bb = boxbounds(p) bb[2]-bb[1] > max(minwidth[splitdim], epswidth(bb)) || return (box, value(box)) xp, fp = p.parent.xvalues, p.parent.fvalues Ξ”x = max(xp[2]-xp[1], xp[3]-xp[2]) # a measure of the "pragmatic" box scale even when the box is infinite xcur = xp[p.parent_cindex] @assert(xcur == xtmp[splitdim]) fcur = box.parent.fvalues[box.parent_cindex] # Do a quadratic fit along splitdim xvert, fvert, qcoef = qfit(xp[1]=>fp[1], xp[2]=>fp[2], xp[3]=>fp[3]) if qcoef > 0 # xvert is a minimum. However, in general we can't trust it: for example, for the # "canyon" function # f(x,y) = (x+y)^2/k + k*(x-y)^2, # at fixed `x` the minimum `y` is at # ystar = (k^2-1)/(k^2+1)*x. # If the current box has a different `x` than the one used for box `p`, # then this estimate will be wrong. # (If `p == box.parent` it would be safe, but given that we'd have to pick a third # point anyway, this case does not seem worth treating separately.) # Instead of trusting `xvert`, we take `qcoef` (the quadratic coefficient) at face value. We then # choose a second (arbitrary) point along splitdim (e.g., a new `y` in the "canyon" example) # to evaluate `f`, and then use these two position/value pairs to estimate the # remaining two parameters of the quadratic. if isinf(bb[1]) xnew = xcur - 8*(bb[2]-xcur) elseif isinf(bb[2]) xnew = xcur + 8*(xcur-bb[1]) else xnew = bb[2]-xcur > xcur-bb[1] ? (xcur+2*bb[2])/3 : (2*bb[1]+xcur)/3 end @assert(isfinite(xnew)) xtmp = replacecoordinate!(xtmp, splitdim, xnew) fnew = f(xtmp) # Solve for the minimum of the quadratic given the two pairs xcur=>fcur, xnew=>fnew xvert = (xcur+xnew)/2 - (fnew-fcur)/(2*qcoef*(xnew-xcur)) if bb[1] <= xvert <= bb[2] # xvert is in the box, use it---but first, make sure it's not "degenerate" with # xcur or xnew xvert = ensure_distinct(xvert, xcur, xnew, bb) xtmp = replacecoordinate!(xtmp, splitdim, xvert) fvert = f(xtmp) xf1, xf2, xf3 = order_pairs(xcur=>fcur, xnew=>fnew, xvert=>fvert) add_children!(box, splitdim, MVector3{T}(xf1[1], xf2[1], xf3[1]), MVector3{T}(xf1[2], xf2[2], xf3[2]), lwr, upr) trimschedule!(mes, box, splitdim, x0, lower, upper) return box, minimum(box.fvalues) end # xvert is not in the box. Prepare to split the neighbor, but for this box # just bisect xcur and xnew if xvert < bb[1] xtmp, dir = replacecoordinate!(xtmp, splitdim, bb[1]), -1 else xtmp, dir = replacecoordinate!(xtmp, splitdim, bb[2]), +1 end nbr, success = find_leaf_at_edge(get_root(box), xtmp, splitdim, dir) xmid = (xcur+xnew)/2 xtmp = replacecoordinate!(xtmp, splitdim, xmid) fmid = f(xtmp) xf1, xf2, xf3 = order_pairs(xcur=>fcur, xnew=>fnew, xmid=>fmid) add_children!(box, splitdim, MVector3{T}(xf1[1], xf2[1], xf3[1]), MVector3{T}(xf1[2], xf2[2], xf3[2]), lwr, upr) trimschedule!(mes, box, splitdim, x0, lower, upper) minbox = minimum(box.fvalues) if !success || nbr ∈ visited || !isfinite(value(nbr)) || length(visited) > ndims(box) return (box, minbox) # check nbr ∈ visited to avoid cycles end nbr, mv = autosplit!(nbr, mes, f, x0, position(nbr, x0), 0, xsplitdefaults, lower, upper, minwidth, push!(visited, box)) if mv < minbox return nbr, mv end return box, minbox end trisect!(box, f, xtmp, splitdim, bb, Ξ”x, xcur, fcur) trimschedule!(mes, box, splitdim, x0, lower, upper) return box, isleaf(box) ? value(box) : minimum(box.fvalues) end function trisect!(box::Box{T}, f, xtmp, splitdim, bb, Ξ”x, xcur, fcur) where T l, r = bb if isinf(l) l = r - 6*Ξ”x # gap is usually 1/3 of the box size, so undo this at the level of "box size" elseif isinf(r) r = l + 6*Ξ”x end a, b, c = 5l/6+r/6, (l+r)/2, l/6+5r/6 # Ensure xcur is one of the three if xcur < (a+b)/2 a = xcur elseif xcur < (b+c)/2 b = xcur else c = xcur end if a < b < c return split!(box, f, xtmp, splitdim, MVector3{T}(a, b, c), bb..., xcur, fcur) end return box end # This requires there to be a (non-root) parent split along splitdim function trisect!(box::Box, f, xtmp, splitdim, p = find_parent_with_splitdim(box, splitdim)) bb = boxbounds(p) xp, fp = p.parent.xvalues, p.parent.fvalues Ξ”x = max(xp[2]-xp[1], xp[3]-xp[2]) # a measure of the "pragmatic" box scale even when the box is infinite xcur = xp[p.parent_cindex] @assert(xcur == xtmp[splitdim]) fcur = box.parent.fvalues[box.parent_cindex] trisect!(box, f, xtmp, splitdim, bb, Ξ”x, xcur, fcur) end # Returns target box, value, and Ξ±. Uses Ξ±=0 to signal failure. function quasinewton!(box::Box{T}, B, g, c, scale, f::Function, x0, lower, upper, itermax = 20) where T x = position(box, x0) fbox = fmin = value(box) isfinite(fbox) || return box, fmin, T(0) # Solve the bounded linear least-squares problem forcing B to be positive-definite cB = cholesky(Positive, B) Ξ”x = -(cB \ g) # unconstrained solution lsc, usc = (lower.-x)./scale, (upper.-x)./scale Ξ”x[:] .= clamp.(Ξ”x, lsc, usc) Ξ”x = lls_bounded!(Ξ”x, Matrix(cB), g, lsc, usc) # Test whether the update moves the point appreciably. If not, mark this point # as converged. issame = true for i = 1:length(Ξ”x) issame &= abs(Ξ”x[i]) < sqrt(eps(scale[i])) end if issame box.qnconverged = true return box, fmin, T(0) end Ξ”x[:] .= Ξ”x .* scale Ξ± = T(1.0) iter = 0 while !isinside(x + Ξ±*Ξ”x, lower, upper) && iter < itermax Ξ± /= 2 iter += 1 end iter == itermax && return box, fmin, T(0) iter = 0 # the above weren't "real" iterations, so reset root = get_root(box) # Do a backtracking linesearch local xtarget, ftarget while iter < itermax iter += 1 xtarget = x + Ξ±*Ξ”x # Sadly, the following function evaluations get discarded. But recording them # while preserving the box structure would take ndims(box)-1 additional # evaluations, which is not worth it unless xtarget itself is an improvement. ftarget = f(xtarget) ftarget < fbox && break Ξ± /= 2 end ftarget >= fbox && return box, fmin, T(0) leaf = find_leaf_at(root, xtarget) isfinite(value(leaf)) || return box, fmin, T(0) # The new point should improve on what was already obtained in `leaf` ftarget >= value(leaf) && return box, fmin, T(0) # For consistency with the tree structure, we can change only one coordinate of # xleaf per split. Cycle through all coordinates, picking the one at each stage # that yields the smallest value as predicted by the quadratic model among the # not-yet-selected coordinates. dims_targeted = falses(ndims(leaf)) q(x) = (x'*B*x)/2 + g'*x + c for j = 1:ndims(leaf) xleaf = position(leaf, x0) xtest = copy(xleaf) imin, qmin = 0, typemax(T) for i = 1:ndims(leaf) dims_targeted[i] && continue xtest = replacecoordinate!(xtest, i, xtarget[i]) qx = q(xtest) if qx < qmin qmin = qx imin = i end end imin == 0 && break xcur, xt = xleaf[imin], xtarget[imin] if abs(xcur - xt) < sqrt(eps(scale[imin])) # We're already at this point, continue dims_targeted[imin] = true continue end bb = boxbounds(leaf, imin, lower, upper) a, b, c = pick3(xcur, xt, bb) minsep = eps(T)*(c-a) if a + minsep >= b || b + minsep >= c # The box might be so narrow that there are not enough distinct floating-point # numbers that lie between the bounds. dims_targeted[imin] = true continue end split!(leaf, f, xleaf, imin, MVector3{T}(a, b, c), bb..., xleaf[imin], value(leaf)) fmin = min(fmin, minimum(leaf.fvalues)) childindex = findfirst(isequal(xt), leaf.xvalues) leaf = leaf.children[childindex] isfinite(value(leaf)) || return leaf, fmin, T(0) dims_targeted[imin] = true end return leaf, fmin, Ξ± end # Linear least squares with box-bounds. From # Sequential Coordinate-wise Algorithm for the # Non-negative Least Squares Problem # VojtΛ‡ch e Franc, V ́clav aHlav ́ acΛ‡, and Mirko Navara # Solves min(x'*H*x/2 + f'*x) over the domain bounded by lower and upper function lls_bounded(H::AbstractMatrix{T}, f::VT, lower::V, upper::V, tol = sqrt(eps(T))) where {T,VT<:AbstractVector{T},V<:AbstractVector} x = clamp.(-H \ f, lower, upper) lls_bounded!(x, H, f, lower, upper, zeros(T, length(f)), tol) return x end lls_bounded!(x::VT, H::AbstractMatrix{T}, f::VT, lower::V, upper::V, tol = sqrt(eps(T))) where {T,VT<:AbstractVector{T},V<:AbstractVector} = lls_bounded!(x, H, f, lower, upper, zeros(T, length(f)), tol) function lls_bounded!(x::VT, H::AbstractMatrix{T}, f::VT, lower::V, upper::V, g::VT, tol = sqrt(eps(T))) where {T,VT<:AbstractVector{T},V<:AbstractVector} assert_oneindexed(A) = @assert(all(r->first(r)==1, axes(A))) assert_oneindexed(x); assert_oneindexed(H); assert_oneindexed(f); assert_oneindexed(lower) assert_oneindexed(upper); assert_oneindexed(g) m, n = size(H) m == n || error("H must be square") length(f) == n || error("Mismatch between H and f") length(g) == n || error("Mismatch between H and g") niter = 0 while niter <= 1000 # Once per iter, calculate gradient freshly to avoid accumulation of roundoff mul!(g, H, x) for i = 1:n g[i] += f[i] end xchange = zero(T) for k = 1:n xold = x[k] xnew = clamp(xold - g[k]/H[k,k], lower[k], upper[k]) x[k] = xnew dx = xnew-xold xchange = max(xchange, abs(dx)) if dx != 0 for i = 1:n g[i] += dx*H[i,k] end end end if xchange < tol break end niter += 1 end x end # A dumb O(N) algorithm for building the minimum-edge structures # For large trees, this is the bottleneck function minimum_edges(root::Box{T,N}, x0, lower, upper, minwidth=zeros(eltype(x0), ndims(root)); extrapolate::Bool=true) where {T,N} mes = [MELink{T,T}(root) for i = 1:N] # Make it a priority to have enough splits along each coordinate to provide adequate # information for the quasi-Newton method. To compute an estimate of the full quadratic # model, we'll need (N+1)*(N+2)Γ·2 independent points, so prioritze splitting # boxes so that each coordinate has at least 1/Nth of the requisite number of splits. nthresh = ceil(Int, (((N+1)*(N+2))Γ·2)/N) nsplits = Vector{Int}(undef, N) for box in leaves(root) box.qnconverged && continue fval = value(box) isfinite(fval) || continue count_splits!(nsplits, box) nmin = minimum(nsplits) for i = 1:N if nmin < nthresh nsplits[i] == nmin || continue end bb = boxbounds(find_parent_with_splitdim(box, i), lower[i], upper[i]) bb[2]-bb[1] < minwidth[i] && continue insert!(mes[i], width(box, i, x0, lower, upper), box=>extrapolate ? fval+qdelta(box, i) : fval) end end return mes end function trimschedule!(mes::Vector{<:MELink}, box::Box, splitdim, x0, lower, upper) isleaf(box) && return mes for child in box.children fval = child.parent.fvalues[child.parent_cindex] for i = 1:ndims(box) trim!(mes[i], width(child, i, x0, lower, upper), child=>fval) end end return mes end function mesprint(mes) for i = 1:length(mes) print(i, ": ") for item in mes[i] print(", (", item.w, ',', item.f, ')') end println() end nothing end function sweep!(root::Box, f, x0, splits, lower, upper; extrapolate::Bool = true, fvalue=-Inf, minwidth=zeros(eltype(x0), ndims(root))) mes = minimum_edges(root, x0, lower, upper, minwidth; extrapolate=extrapolate) sweep!(root, mes, f, x0, splits, lower, upper; fvalue=fvalue, minwidth=minwidth) end function sweep!(root::Box{T}, mes::Vector{<:MELink}, f, x0, splits, lower, upper; fvalue=-Inf, minwidth=zeros(eltype(x0), ndims(root))) where T xtmp = similar(x0) flag = similar(x0, Bool) nsplits = similar(x0, Int) visited = Set{typeof(root)}() splitboxes = Set{typeof(root)}() dimorder = sortperm(length.(mes)) # process the dimensions with the shortest queues first fvalueT = T(fvalue) for i in dimorder me = mes[i] while !isempty(me) item = popfirst!(me) box = item.l box.qnconverged && continue bb = boxbounds(find_parent_with_splitdim(box, i), lower[i], upper[i]) bb[2]-bb[1] < minwidth[i] && continue position!(xtmp, flag, box) default_position!(xtmp, flag, x0) count_splits!(nsplits, box) if nsplits[i] > 0 && any(iszero, nsplits) # println("discarding ", box, " along dimension ", i) continue end empty!(visited) finalbox, minval = autosplit!(box, mes, f, x0, xtmp, i, splits, lower, upper, minwidth, visited) push!(splitboxes, finalbox) minval <= fvalueT && return root, unique_smallest_leaves(splitboxes) end end root, unique_smallest_leaves(splitboxes) end """ root, x0 = analyze(f, splits, lower, upper; rtol=1e-3, atol=0.0, fvalue=-Inf, maxevals=2500, nquasinewton=<auto>, minwidth=zeros(length(splits)), print_interval=typemax(Int)) Analyze the behavior of `f`, searching for minima, over the rectangular box specified by `lower` and `upper` (`lower[i] <= x[i] <= upper[i]`). The bounds may be infinite. `splits` is a list of 3-vectors containing the initial values along each coordinate axis at which to potentially evaluate `f`; the values must be in increasing order. `root` is a tree structure that stores information about the behavior of `f`. `x0` contains the initial evaluation point, the position constructed from the middle value of `splits` in each dimension. There are several keywords which can be important: - `rtol` and `atol` represent relative and absolute, respectively, changes in minimum function value required for the exploration to terminate. (These limits must be hit on `ndims` successive sweeps.) Alternatively, the analysis is terminated if the function value is ever reduced below `fvalue`. The combination `rtol=0, fvalue=<user-supplied-value>` can be especially useful in benchmarking situations in which you know the value of the global minimum; it will force the algorithm to keep trying until it reaches `fvalue`, or until it exceeds the maximum number of allowed function evaluations. - `maxevals` allows you to control the maximum number of function evaluations that the algorithm is permitted to use. The actual number may be a bit higher, as the criterion is not checked while, e.g., in the middle of a splitting-sweep or a quasi-Newton step. - `nquasinewton` is the number of "explore" function evaluations required before attempting the first quasi-Newton step. The default value is the minimum number of evaluations required to estimate the parameters of a quadratic model, `(N+1)*(N+2)Γ·2` in `N` dimensions. Using a higher number may encourage the algorithm to spend more time "exploring" before thoroughly "exploiting" the most promising leads so far. - `minwidth[i]` sets the minimum box size along dimension `i`. This is not strictly enforced, but boxes that become smaller will not be split during "explore" (sweep) phases of the algorithm. You can use this to improve coverage of space when you know that some parameter-value changes are too small to lead to measurable improvements. - setting `print_interval` displays a small amount of information about progress. # Example: # A function that has a long but skinny valley aligned at 45 degrees (minimum at [0,0]) function canyon(x) x1, x2 = x[1], x[2] return 0.1*(x1+x2)^2 + 10*(x1-x2)^2 end lower, upper = [-Inf, -Inf], [Inf, Inf] # unbounded domain # We'll initially consider a grid that covers -11->-9 along the first dimension # and -7->-5 along the second. This isn't a great initial guess, but that's OK. splits = ([-11,-10,-9], [-7,-6,-5]) # Since this problem has a minimum value of 0, relying on `rtol` is not ideal # (it's possible to make infinitesimal relative improvements nearly forever), # so specify an absolute tolerance. julia> root, x0 = analyze(canyon, splits, lower, upper; atol=0.01) (BoxRoot@[NaN, NaN], [-10.0, -6.0]) julia> box = minimum(root) Box1.9407745316864587e-25@[-6.94556e-13, -6.98108e-13] julia> value(box) 1.9407745316864587e-25 julia> position(box, x0) 2-element Array{Float64,1}: -6.94556e-13 -6.98108e-13 See also [`minimize`](@ref). """ function analyze(f, splits, lower, upper; kwargs...) box, x0 = init(f, splits, lower, upper) root = get_root(box) analyze!(root, f, x0, splits, lower, upper; kwargs...) return root, x0 end """ root = analyze!(root, f, x0, splits, lower, upper; kwargs...) Further refinement of `root`. See [`analyze`](@ref) for details. """ function analyze!(root::Box, f::Function, x0, splits, lower, upper; rtol=1e-3, atol=0.0, fvalue=-Inf, maxevals=2500, print_interval=typemax(Int), kwargs...) analyze!(root, CountedFunction(f), x0, splits, lower, upper; rtol=rtol, atol=atol, fvalue=fvalue, maxevals=maxevals, print_interval=print_interval, kwargs...) end function analyze!(root::Box{T}, f::WrappedFunction, x0, splits, lower, upper; rtol=1e-3, atol=0.0, fvalue=-Inf, maxevals=2500, print_interval=typemax(Int), nquasinewton=qnthresh(ndims(root)), kwargs...) where T box = minimum(root) boxval = value(box) lastval = typemax(boxval) tol_counter = 0 lastprint = 0 baseline_evals = len = lenold = length(leaves(root)) if baseline_evals == numevals(f) baseline_evals = 0 # already counted end if print_interval < typemax(Int) println("Initial minimum ($len evaluations): ", box) end extrapolate = true # The quasi-Newton step can reduce the function value so significantly, insist on # using it at least once (unless the threshold to kick in not reachable) used_quasinewton = nquasinewton > maxevals nsweep, nqn = baseline_evals+numevals(f), 0 thresh = sqrt(eps(T)) nsplits = zeros(Int, ndims(root)) while boxval > fvalue && (tol_counter <= ndims(root) || !used_quasinewton) && len < maxevals lastval = boxval numeval0 = numevals(f) _, splitboxes = sweep!(root, f, x0, splits, lower, upper; extrapolate=extrapolate, fvalue=fvalue, kwargs...) box = minimum(root) numeval1 = numevals(f) nsweep += numeval1 - numeval0 if nquasinewton < baseline_evals + numevals(f) < maxevals && boxval > fvalue && !isempty(splitboxes) # Quasi-Newton step for boxes split in the sweep spbxs = sort(collect(splitboxes); by=value) # if unsorted, set hashing would introduce randomness # determine which are in separate "basins" using a convexity test # basinboxes = spbxs # basinboxes = different_basins(spbxs, x0, lower, upper) basinboxes = filter(is_diag_convex, spbxs) badbox = Dict(box=>false for box in basinboxes) for (ibox, box) in enumerate(basinboxes) box.qnconverged && continue isleaf(box) || continue # "outdated" badbox[box] && continue # in same basin as a previous successful quadratic fit baseline_evals + numevals(f) >= maxevals && break # Ensure at least one split per coordinate before trying to build the quadratic model count_splits!(nsplits, box) xtmp = position(box, x0) for i = 1:ndims(box) if nsplits[i] == 0 box = split!(box, f, xtmp, i, splits[i], lower[i], upper[i], xtmp[i], value(box)) xtmp[i] = box.parent.xvalues[box.parent_cindex] end end scale = boxscale(box, splits) Q, xbase, c, success_build = build_quadratic_model(box, x0, scale, thresh) if success_build && all(x->x>0, Q.dimpiv) # Add more points, as needed, to fill in any missing rows from the regression @assert isleaf(box) complete_quadratic_model!(Q, c, box, f, x0, xbase, scale, splits, lower, upper, thresh) # If the model is complete, try Quasi-Newton algorithm if Q.nzrows[] == size(Q.coefs, 1) && minimum(abs.(diag(Q.coefs))) >= thresh g, B = solve(Q) # Bscale = (1./scale) .* B .* (1./scale)' # display(Bscale) # error("stop") leaf, minvalue, Ξ± = quasinewton!(box, B, g, c, scale, f, x0, lower, upper) success_qn = Ξ± > 0 used_quasinewton |= success_qn minvalue < fvalue && break if success_qn @assert(isleaf(leaf)) boxvalue = value(box) # If the improvement was tiny, mark the solution to block # future attempts at quasi-Newton in this region if boxvalue - minvalue <= max(atol, rtol*(abs(boxvalue) + abs(minvalue))) # Check that leaf has roughly the same coordinates, too. xbox = position(box, x0) xleaf = position(leaf, x0) if issame(xbox, xleaf, scale) leaf.qnconverged = true end end # check future boxes and eliminate them if they appear to lie in the same basin if Ξ± == 1 for j = ibox+1:length(basinboxes) boxj = basinboxes[j] vj, xj = value(boxj), position(boxj, x0) Ξ”x = (xj - xbase) ./ scale pred = c + g'*Ξ”x + (Ξ”x'*B*Ξ”x)/2 if abs(pred - vj) <= 0.1*abs(pred - minvalue) # FIXME hardcoded badbox[boxj] = true end end end end end end end # if !used_quasinewton # nquasinewton *= 2 # end box = minimum(root) boxval = value(box) end nqn += numevals(f) - numeval1 len = baseline_evals + numevals(f) len == lenold && break # couldn't split any boxes lenold = len if len-lastprint > print_interval println("minimum ($len evaluations): ", box) lastprint = len end @assert(boxval <= lastval) if lastval - boxval < atol || lastval - boxval < rtol*(abs(lastval) + abs(boxval)) tol_counter += 1 else tol_counter = 0 end end if print_interval < typemax(Int) println("Final minimum ($len evaluations): ", minimum(root)) println("$nsweep evaluations for initialization+sweeps, $nqn for Quasi-Newton") end root end """ xmin, fmin = minimize(f, splits, lower, upper; kwargs...) Return the position `xmin` and value `fmin` of the minimum of `f` over the specified domain. See [`analyze`](@ref) for information about the input arguments. """ function minimize(f, splits, lower, upper; kwargs...) root, x0 = analyze(f, splits, lower, upper; kwargs...) box = minimum(root) return position(box, x0), value(box) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2566
using PyPlot, Colors, PerceptualColourMaps using QuadDIRECT using QuadDIRECT: Box get_finite(x, default) = isfinite(x) ? x : default outerbounds(b1, b2) = (min(b1[1], b2[1]), max(b1[2], b2[2])) outerbounds(b1, b2::Real) = (min(b1[1], b2), max(b1[2], b2)) outerbounds_finite(b1, b2) = (min(b1[1], get_finite(b2[1], b1[1])), max(b1[2], get_finite(b2[2], b1[2]))) widenbounds(b) = (Ξ”x = 0.1*(b[2]-b[1]); return (b[1]-Ξ”x, b[2]+Ξ”x)) function plotbounds(root::Box{T,2}, x0, lower, upper) where T xbounds, ybounds = (Inf, -Inf), (Inf, -Inf) bb = Vector{Tuple{T,T}}(undef, 2) x = [NaN, NaN] flag = [false, false] for box in leaves(root) for i = 1:2 bb[i] = (lower[i], upper[i]) end QuadDIRECT.boxbounds!(bb, box) xbounds = outerbounds_finite(xbounds, bb[1]) ybounds = outerbounds_finite(ybounds, bb[2]) x = QuadDIRECT.position!(x, flag, box) QuadDIRECT.default_position!(x, flag, x0) xbounds = outerbounds(xbounds, x[1]) ybounds = outerbounds(ybounds, x[2]) end widenbounds(xbounds), widenbounds(ybounds) end function plotboxes(root::Box{T,2}, x0, lower, upper, xbounds::Tuple{Any,Any}, ybounds::Tuple{Any,Any}; clim=extrema(root), cs::AbstractVector{<:Colorant}=cmap("RAINBOW3")) where T clf() for bx in leaves(root) plotrect(bx, x0, clim, cs, lower, upper, xbounds, ybounds) end xlim(xbounds) ylim(ybounds) ax = gca() # norm = PyPlot.matplotlib[:colors][:Normalize](vmin=clim[1], vmax=clim[2]) # cb = PyPlot.matplotlib[:colorbar][:ColorbarBase](ax, cmap=ColorMap(cs), norm=norm) ax end plotboxes(root::Box{T,2}, x0, lower, upper; clim=extrema(root), cs::AbstractVector{<:Colorant}=cmap("RAINBOW3")) where T = plotboxes(root, x0, lower, upper, plotbounds(root, x0, lower, upper)...; clim=clim, cs=cs) function plotrect(box::Box{T,2}, x0, clim, cs, lower, upper, xbounds, ybounds) where T @assert(QuadDIRECT.isleaf(box)) x = QuadDIRECT.position(box, x0) bb = QuadDIRECT.boxbounds(box, lower, upper) bbx, bby = bb rectx = [bbx[1], bbx[2], bbx[2], bbx[1], bbx[1]] recty = [bby[1], bby[1], bby[2], bby[2], bby[1]] fval = box.parent.fvalues[box.parent_cindex] cnorm = (clamp(fval, clim...) - clim[1])/(clim[2] - clim[1]) col = cs[round(Int, (length(cs)-1)*cnorm) + 1] hold(true) fill(clamp.(rectx, xbounds...), clamp.(recty, ybounds...), color=[red(col), green(col), blue(col)]) plot(rectx, recty, "k") plot([x[1]], [x[2]], "k.") hold(false) nothing end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
20265
## Use regression to compute the best-fit quadratic model (with a dense Hessian) const scaledthresh = 100 # FIXME hardcoded """ g, B = solve(Q::QmIGE) Solve a quadratic model `Q` for the gradient `g` and Hessian `B`. See [`build_quadratic_model`](@ref) and [`complete_quadratic_model!`](@ref) to build `Q`. """ function solve(Q::QmIGE{T,N}) where {T,N} # Importantly, this defines the storage order in Q gB = LowerTriangular(Q.coefs) \ Q.rhs g, B = Vector{T}(undef, N), Matrix{T}(undef, N, N) k = 0 dimpiv = Q.dimpiv for i = 1:N di = dimpiv[i] g[di] = gB[k+=1] for j = 1:i dj = dimpiv[j] B[di,dj] = B[dj,di] = gB[k+=1] end end return g, B end # Uses available points to set up the regression problem """ Q = build_quadratic_model(box, x0, scale, thresh) Start building a quadratic model of the function, using points already stored in the tree that contains `box`. `scale` (see [`boxscale`](@ref)) is used in part to ensure numeric stability, and will prevent inclusion of points that are too distant along any coordinate axis. `Q` is not guaranteed to be complete; the tree may not contain enough points, or enough "independent" points, to determine all the parameters of `Q`. See also [`complete_quadratic_model!`](@ref). """ function build_quadratic_model(box::Box{T,N}, x0, scale, thresh) where {T,N} Q = QmIGE{T,N}() c = value(box) xbase = position(box, x0) xtmp = similar(xbase) flag = similar(xtmp, Bool) nanfill = fill(T(NaN), N) bbs = boxbounds(box, nanfill, nanfill) succeeded = true @assert(isleaf(box)) if !isleaf(box) for i = 1:3 succeeded &= descend!(Q, c, box.children[i], x0, xbase, xtmp, flag, bbs, scale, thresh) end end # To increase the numeric stability of the result, we do more boxes than # nominally needed (see the `swap` portion of `insert!`) need_extra = true while succeeded && (Q.nzrows[] < length(Q.rhs) || need_extra) && !isroot(box) if Q.nzrows[] == length(Q.rhs) need_extra = minimum(abs.(diag(Q.coefs))) < thresh # because of scaling this doesn't need units end cindex = box.parent_cindex box = box.parent succeeded &= all(isfinite, box.fvalues) && !box.qnconverged succeeded || break j = 1 if j == cindex j+=1 end succeeded &= descend!(Q, c, box.children[j], x0, xbase, xtmp, flag, bbs, scale, thresh) succeeded || break j += 1 if j == cindex j+=1 end succeeded &= descend!(Q, c, box.children[j], x0, xbase, xtmp, flag, bbs, scale, thresh) end return Q, xbase, c, succeeded end # Evaluates the function at new points until the quadratic model is fully specified """ complete_quadratic_model!(Q::QmIGE, c, box::Box, f::Function, x0, xbase, scale, splits, lower::AbstractVector, upper::AbstractVector, thresh) Split boxes in the tree containing `box` until all the parameters of the quadratic model can be determined. It is allowed to fail if one or more boxes are too small to be split further, so it is advisable to check that all diagonal coefficients in `Q` exceed `thresh` before proceeding. See also [`solve`](@ref). """ function complete_quadratic_model!(Q::QmIGE, c, box::Box{T,N}, f::Function, x0, xbase, scale, splits, lower::AbstractVector, upper::AbstractVector, thresh) where {T,N} @assert(all(x->x>0, Q.dimpiv)) xtmp = similar(x0) Ξ”x = similar(x0) Ξ”xtmp = similar(x0) flag = similar(x0, Bool) dimpiv = Q.dimpiv rowoffset = 0 # Sanity check i = 0 for idim = 1:N for irow = 0:idim if isassigned(Q.rowbox, i+=1) @assert(isleaf(Q.rowbox[i])) position!(xtmp, flag, Q.rowbox[i], x0) for j = idim+1:N sd = Q.dimpiv[j] @assert(xtmp[sd]==xbase[sd]) end end end end # Process block-by-block, each block corresponding to a "new" splitting dimension for idim = 1:N all_are_set = true for j = 1:idim+1 all_are_set &= abs(Q.coefs[j+rowoffset,j+rowoffset]) >= thresh end if all_are_set rowoffset += idim + 1 continue end rowb = row = rowoffset + idim + 1 # within this dimension's block, go backwards irow = idim # @show Q.rowbox[rowoffset+1:row] # If all boxes that differed along this dimension were out-of-scale, we # need to split along that dimension. if !isassigned(Q.rowbox, rowb) splitdim = Q.dimpiv[idim] position!(xtmp, flag, box, x0) xcur, s = xbase[splitdim], scale[splitdim] p = find_parent_with_splitdim(box, splitdim) bb = boxbounds(p) @assert xtmp[splitdim] == xcur l = max(bb[1], xcur - s/2) u = min(bb[2], xcur + s/2) if l >= xcur l, xcur = xcur, (xcur + u)/2 elseif xcur >= u u, xcur = xcur, (l + xcur)/2 end abs(u-l) < epswidth((l, u)) && return Q #FIXME? split!(box, f, xtmp, splitdim, MVector3{T}(l, xcur, u), lower[splitdim], upper[splitdim], xcur, value(box)) xcur = xbase[splitdim] j = 3 j1 = 1; if box.xvalues[j1] == xcur j = j1; j1 += 1; end j2 = j1+1; if box.xvalues[j2] == xcur j = j2; j2 += 1; end nbrbox = box.fvalues[j1] < box.fvalues[j2] ? box.children[j1] : box.children[j2] Q.rowbox[rowb] = nbrbox box = box.children[j] end while irow >= 0 # @show row # if row == rowb # rng = rowoffset+1:rowoffset+idim+1 # display(Q.coefs[rng,rng]) # @show thresh # end Qd = abs(Q.coefs[row,row]) if Qd < thresh # @show rowb irow rbox = Q.rowbox[rowb] @assert isleaf(rbox) position!(xtmp, flag, rbox, x0) Ξ”x .= xtmp .- xbase if irow > 0 # When irow > 0, splitting along the corresponding dimension will fill # in this missing information splitdim = dimpiv[irow] else # root = get_root(box) # splitprint_colored(root, box) # println() # splitprint_colored(root, rbox) # println() # @show Ξ”x dimpiv # irow == 0 corresponds to the coefficient of the gradient if Ξ”x[dimpiv[idim]] == 0 # There's no displacement in the gradient coordinate, so obviously # we have to split it splitdim = dimpiv[idim] else # Here it's not so obvious which coordinate we need to split. # To avoid the risk of failure, we check the result of the gaussian # elimination and choose our splitting dimension as the one that # has largest (remaining) diagonal value. Ξ”xtmp[:] .= Ξ”x ./ scale maxdiag, splitdim = zero(T), 0 rng = rowoffset+1:rowoffset+idim+1 Q.rowzero[row] = true for ii = 1:idim # The precise magnitude of the step doesn't matter for these "probe" trials sd = dimpiv[ii] xold = Ξ”xtmp[sd] Ξ”xtmp[sd] = Ξ”xtmp[sd] == 0 ? 1 : 2*Ξ”xtmp[sd] # ensure a non-zero entry no matter what # @show Ξ”xtmp setrow!(Q.rowtmp, dimpiv, Ξ”xtmp, N, sd) Ξ”xtmp[sd] = xold # @show ii sd rtmp, _ = incremental_gaussian_elimination!(Q.rowtmp, Q.coefs, Q.rowzero, rng; canswap=false, debug=false) thisdiag = abs(Q.rowtmp[row]) if thisdiag > maxdiag maxdiag = thisdiag splitdim = sd end end if splitdim == 0 rng = rowoffset+1:rowoffset+idim+1 display(Q.coefs[rng,rng]) error("no direction works") end # @show maxdiag splitdim end end xcur = xtmp[splitdim] p = find_parent_with_splitdim(rbox, splitdim) # Check that the box is big enough to split along this dimension if !isroot(p) bb = boxbounds(p) bbeps = epswidth(bb) if !(bb[2] - bb[1] > bbeps) || !(bb[2] - xtmp[splitdim] > bbeps) || !(xtmp[splitdim] - bb[1] > bbeps) return Q # fail (FIXME?) end end insrows, rboxn = split_insert!(Q, rbox, p, row:rowoffset+idim+1, f, xbase, c, xtmp, splitdim, scale, splits, lower, upper) if Qd == 0 && (maximum(insrows) != row || Q.coefs[row,row] == 0) # Debugging println("Something went wrong") @show numevals(f) insrows row irow rowb rowoffset idim Q.dimpiv @show rbox.parent.splitdim box.parent.splitdim @show splitdim boxbounds(rbox, lower, upper) rng = rowoffset+1:rowoffset+idim+1 display(Q.coefs[rng,rng]) @show xcur rbox.xvalues (rbox.xvalues .- xcur)./scale[splitdim] end Qd == 0 && @assert(maximum(insrows) == row) if row == rowb Q.rowbox[row] = rboxn # ensure it's a leaf end end if isassigned(Q.rowbox, row) && isleaf(Q.rowbox[row]) rowb = row end row -=1; irow -= 1 end rowoffset += idim + 1 end return Q end function split_insert!(Q, rbox::Box{T}, p, rng, f, xbase, c, xtmp, splitdim, scale, splits, lower, upper) where T debug = false debug && @show rng row = first(rng) xcur = xtmp[splitdim] if isroot(p) xsplit = MVector3{T}(splits[splitdim]) @assert(xsplit[1] < xsplit[2] < xsplit[3]) lwr, upr = lower[splitdim], upper[splitdim] else bb = boxbounds(p) lwr, upr = bb[1], bb[2] xcur, scalesd = xtmp[splitdim], scale[splitdim] lo, hi = max(lwr, 5*lwr/6 + xcur/6, xcur - scalesd), min(upr, xcur/6 + 5*upr/6, xcur + scalesd) if lo + sqrt(eps(T))*scalesd >= xcur lo, xcur = xcur, (xcur+hi)/2 elseif xcur + sqrt(eps(T))*scalesd >= hi xcur, hi = (xcur+lo)/2, xcur end xsplit = MVector3{T}(lo, xcur, hi) xcur = xtmp[splitdim] @assert(xsplit[1] < xsplit[2] < xsplit[3]) end j1 = 1 if xsplit[j1] == xcur j1 += 1 end j2 = j1+1 if xsplit[j2] == xcur j2 += 1 end l, h = xsplit[j1], xsplit[j2] Qd = abs(Q.coefs[row, row]) if Qd != 0 # This is a case where the existing entry is below thresh. Before proceeding, check # whether the new one would be an improvement---rbox might be too small along # splitdim to raise the value. xtmp[splitdim] = l setrow!(Q.rowtmp, Q.dimpiv, (xtmp-xbase)./scale, ndims(rbox), splitdim) incremental_gaussian_elimination!(Q.rowtmp, Q.coefs, Q.rowzero, rng; canswap=false, debug=false) debug && @show abs(Q.rowtmp[row]) if abs(Q.rowtmp[row]) < Qd xtmp[splitdim] = h setrow!(Q.rowtmp, Q.dimpiv, (xtmp-xbase)./scale, ndims(rbox), splitdim) incremental_gaussian_elimination!(Q.rowtmp, Q.coefs, Q.rowzero, rng; canswap=false, debug=false) debug && @show abs(Q.rowtmp[row]) if abs(Q.rowtmp[row]) < Qd # Neither was an improvement, so keep what we've got debug && println("skipping") return (row,-1), rbox end end end # Split rbox and insert into Q val = value(rbox) fsplit = MVector3(val,val,val) xtmp[splitdim] = l fsplit[j1] = f(xtmp) xtmp[splitdim] = h fsplit[j2] = f(xtmp) add_children!(rbox, splitdim, xsplit, fsplit, lwr, upr) if l != xbase[splitdim] xtmp[splitdim] = l debug && @show (xtmp.-xbase)./scale insrow1 = insert!(Q, (xtmp.-xbase)./scale, rbox.fvalues[j1]-c, splitdim, rbox.children[j1]; canswap=false, debug=debug) else debug && println("skipping l") insrow1 = 0 end if h != xbase[splitdim] xtmp[splitdim] = h debug && @show (xtmp.-xbase)./scale insrow2 = insert!(Q, (xtmp.-xbase)./scale, rbox.fvalues[j2]-c, splitdim, rbox.children[j2]; canswap=false, debug=debug) else debug && println("skipping h") insrow2 = 0 end # Return the leaf corresponding to the original xtmp[splitdim] = xcur j = 1; if j == j1 j += 1 end; if j == j2 j += 1 end return ((insrow1, insrow2), rbox.children[j]) end function descend!(Q::QmIGE, c, box, x0, xbase, Ξ”x, flag, bbs, scale, thresh, skip::Bool=false) box.qnconverged && return false # don't build quadratic models that include points tagged as converged minima # Is this box so far away that we should prune this branch? boxbounds!(bbs, flag, box) for i = 1:ndims(box) xb, bb = xbase[i], bbs[i] min(bb[1] - xb, xb - bb[2]) > scaledthresh*scale[i] && return true end position!(Ξ”x, flag, box, x0) thisx = isleaf(box) ? zero(eltype(Ξ”x)) : Ξ”x[box.splitdim] if !skip # Add this point to the model isgood = true leaf = find_leaf_at(box, Ξ”x) for i = 1:length(Ξ”x) Ξ”x[i] = (Ξ”x[i] - xbase[i])/scale[i] # To prevent distant points from numerically overwhelming the local structure of the box, # put in a cutoff. The concern is that large values here will dominate # eigenvalues that come from local data. isgood &= abs(Ξ”x[i]) < scaledthresh end if isgood insert!(Q, Ξ”x, value(box)-c, box.parent.splitdim, leaf) else # we have to save space for this dimension, since they are added # in splitdim order sd = box.parent.splitdim if sd βˆ‰ Q.dimpiv Q.ndims[] += 1 Q.dimpiv[Q.ndims[]] = sd end end end # Recursively add all children if !isleaf(box) iskip = findfirst(isequal(thisx), box.xvalues) for i = 1:3 descend!(Q, c, box.children[i], x0, xbase, Ξ”x, flag, bbs, scale, thresh, i==iskip) || return false end end return true end function Base.insert!(Q::QmIGE, Ξ”x, Ξ”f, splitdim::Integer, box::Box; canswap::Bool=true, debug::Bool=false) coefs, rhs, rowtmp = Q.coefs, Q.rhs, Q.rowtmp dimpiv, rowzero, ndims_old = Q.dimpiv, Q.rowzero, Q.ndims[] ndims = setrow!(rowtmp, dimpiv, Ξ”x, ndims_old, splitdim) if ndims > ndims_old # Append to coefs. We always insert at the end of the # block corresponding to splitdim, so that we're performing # elimination on incoming points. That gives us a chance to # test for degeneracy before inserting them. i = ndims + (ndims*(ndims+1))Γ·2 # #gcoefs + #Bcoefs so far i == 0 && return i for j = 1:i coefs[i,j] = rowtmp[j] end rowzero[i] = false Q.rowbox[i] = box rhs[i] = Ξ”f Q.ndims[] = ndims Q.nzrows[] += 1 return i end ndims == 0 && return 0 # We've seen all the nonzero dimensions in Ξ”x previously # Use elimination to determine whether it provides novel information blockstart = ndims + ((ndims-1)*ndims)Γ·2 # first row for this splitting dimension blockend = blockstart + ndims # last row for this splitting dimension finalrow, newrhs, box = incremental_gaussian_elimination!(rowtmp, coefs, rowzero, blockstart:blockend, Ξ”f, rhs, box, Q.rowbox; canswap=canswap, debug=debug) if finalrow > 0 rowzero[finalrow] = false for j = 1:finalrow coefs[finalrow,j] = rowtmp[j] end store!(rhs, newrhs, finalrow) store!(Q.rowbox, box, finalrow) Q.nzrows[] += 1 end return finalrow end # This implements the logic of "flipped" Gaussian elimination (the zeros block on the # upper triangle) when adding a new point. We do it in flipped form because incoming # points tend to build a lower-triangular matrix: the tree structure # adds dimensions one at a time, so Ξ”x will be all-zeros for trailing dimensions # (once permuted into the order specified by dimpiv). function incremental_gaussian_elimination!(newrow::AbstractVector{T}, coefs::AbstractMatrix, rowzero::AbstractVector{Bool}, rng::AbstractUnitRange, newrhs=nothing, rhs=nothing, meta=nothing, metastore=nothing; canswap::Bool=true, debug::Bool=false) where T # @inline myapprox(x, y, rtol) = isequal(x, y) | (abs(x-y) < rtol*(abs(x) + abs(y))) @inline myapprox(x, y, rtol) = (x == y) | (abs(x-y) < rtol*(abs(x) + abs(y))) rtol = 1000*eps(T) debug && @show rng debug && println("input: ", newrow[rng]) i = last(rng) @assert(first(rng) > 0) @inbounds while i >= first(rng) if newrow[i] == 0 i -= 1 continue end rowzero[i] && break if canswap && abs(newrow[i]) > abs(coefs[i,i]) # Swap (for numeric stability) debug && println("swap at ", i, "($(newrow[i]) vs $(coefs[i,i])") for j = 1:i newrow[j], coefs[i,j] = coefs[i,j], newrow[j] end newrhs = swap!(rhs, newrhs, i) meta = swap!(metastore, meta, i) end c = newrow[i]/coefs[i,i] @simd for j = 1:i-1 sub = c * coefs[i,j] # coefsp[j,i] newrow[j] = ifelse(myapprox(newrow[j], sub, rtol), zero(sub), newrow[j] - sub) end newrow[i] = 0 # rather than subtracting, just set it (to avoid roundoff error) debug && @show i newrow[rng] newrhs = subtract(rhs, c, i, newrhs) i -= 1 end if i < first(rng) i = 0 end return i, newrhs, meta end function swap!(store, x, i) x, store[i] = store[i], x return x end swap!(::Any, ::Nothing, i) = nothing store!(store, x, i) = store[i] = x store!(::Any, ::Nothing, i) = nothing subtract(rhs, c, i, newrhs) = newrhs - c*rhs[i] subtract(rhs, c, i, ::Nothing) = nothing function setrow!(rowtmp, dimpiv, Ξ”x, ndims, splitdim) fill!(rowtmp, 0) k = 0 have_splitdim = false for j = 1:ndims d = dimpiv[j] have_splitdim |= splitdim == d # The g coefs are linear in x, the B coefs quadratic # The implied storage order here matches `solve` below Ξ”xd = Ξ”x[d] if Ξ”xd == 0 k += j+1 continue end rowtmp[k+=1] = Ξ”xd # g coef for i = 1:j-1 rowtmp[k+=1] = Ξ”xd * Ξ”x[dimpiv[i]] # B[d,dimpiv[i]] coefficient end rowtmp[k+=1] = (Ξ”xd * Ξ”xd)/2 # B[d,d] coefficient end if !have_splitdim # We've not seen this dimension previously, so make it the # next one in dimpiv. ndims += 1 dimpiv[ndims] = splitdim rowtmp[k+=1] = Ξ”xd = Ξ”x[splitdim] for i = 1:ndims-1 rowtmp[k+=1] = Ξ”xd * Ξ”x[dimpiv[i]] end rowtmp[k+=1] = (Ξ”xd * Ξ”xd)/2 end # Back up to last nonzero dimension while ndims > 0 && Ξ”x[dimpiv[ndims]] == 0 ndims -= 1 end return ndims end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
5889
""" mel = MELink{Tx,Ty}(dummylabel) Create a linked-list storing labels and x/y pairs that represent the "minimum edge" of a set of values, where the stored x and y values are monotonic in both x and y. Insertion of a new x/y pair expunges any entries with smaller x but larger y. Add new elements with `insert!(mel, x, label=>y)`. The first item in the list is a dummy item with `x=0`, so that the head of the list is constant. """ mutable struct MELink{Tl,Tw,Tf} l::Tl # label w::Tw # x-coordinate (box width) f::Tf # y-coordinate (function value) next::MELink{Tl,Tw,Tf} function MELink{Tl,Tw,Tf}(l, w, f) where {Tw, Tf, Tl} mel = new{Tl,Tw,Tf}(l, w, f) mel.next = mel return mel end function MELink{Tl,Tw,Tf}(l, w, f, next) where {Tw, Tf, Tl} mel = new{Tl,Tw,Tf}(l, w, f, next) return mel end end MELink{Tw,Tf}(dummylabel::Tl) where {Tl,Tw,Tf} = MELink{Tl,Tw,Tf}(dummylabel, typemin(Tw), typemin(Tf)) Base.IteratorSize(::Type{<:MELink}) = Base.SizeUnknown() # Mutable length-3 vector without the storage overhead of Array mutable struct MVector3{T} <: AbstractVector{T} x1::T x2::T x3::T end MVector3{T}(a::AbstractVector) where T = convert(MVector3{T}, a) Base.IndexStyle(::Type{<:MVector3}) = IndexLinear() Base.size(v::MVector3) = (3,) Base.axes1(v::MVector3) = Base.OneTo(3) function Base.getindex(v::MVector3, i::Int) @boundscheck ((1 <= i) & (i <= 3)) || Base.throw_boundserror(v, i) ifelse(i == 1, v.x1, ifelse(i == 2, v.x2, v.x3)) end function Base.setindex!(v::MVector3, val, i::Int) @boundscheck ((1 <= i) & (i <= 3)) || Base.throw_boundserror(v, i) if i == 1 v.x1 = val elseif i == 2 v.x2 = val else v.x3 = val end v end Base.convert(::Type{MVector3{T}}, a::MVector3{T}) where T = a function Base.convert(::Type{MVector3{T}}, a::AbstractVector) where T @boundscheck axes(a) == (Base.OneTo(3),) || throw(DimensionMismatch("vector must have length 3")) @inbounds ret = MVector3{T}(a[1], a[2], a[3]) return ret end Base.convert(::Type{MVector3}, a::AbstractVector{T}) where T = convert(MVector3{T}, a) Base.similar(::MVector3{T}, ::Type{S}, dims::Tuple{Vararg{Int}}) where {T,S} = Array{S}(undef, dims) boxeltype(::Type{<:Integer}) = Float64 boxeltype(::Type{T}) where T = T mutable struct Box{T,N} parent::Box{T,N} parent_cindex::Int # of its parent's children, which one is this? splitdim::Int # the dimension along which this box has been split, or 0 if this is a leaf node qnconverged::Bool # true if the box was the minimum-value box in a Quasi-Newton step and the improvement was within convergence criterion minmax::Tuple{T,T} # the outer edges not corresponding to one of the parent's xvalues (splits that occur between dots in Fig 2) xvalues::MVector3{T} # the values of x_splitdim at which f is evaluated fvalues::MVector3{T} # the corresponding values of f children::MVector3{Box{T,N}} function default!(box::Box{T,N}) where {T,N} box.qnconverged = false box.minmax = (typemax(T), typemin(T)) box.xvalues = MVector3{T}(typemax(T), zero(T), typemin(T)) box.fvalues = MVector3{T}(zero(T), zero(T), zero(T)) box.children = MVector3(box, box, box) end function Box{T,N}() where {T,N} # Create the root box box = new{T,N}() box.parent = box box.parent_cindex = 0 box.splitdim = 0 default!(box) return box end function Box{T,N}(parent::Box, parent_cindex::Integer) where {T,N} # Create a new child and store it in the parent box = new{T,N}(parent, parent_cindex, 0) parent.children[parent_cindex] = box default!(box) box end end Box(parent::Box{T,N}, parent_cindex::Integer) where {T,N} = Box{T,N}(parent, parent_cindex) isroot(box::Box) = box.parent == box isleaf(box::Box) = box.splitdim == 0 Base.parent(box::Box) = box.parent Base.ndims(box::Box{T,N}) where {T,N} = N Base.IteratorSize(::Type{<:Box}) = Base.SizeUnknown() abstract type WrappedFunction <: Function end # A function that keeps track of the number of evaluations mutable struct CountedFunction{F} <: WrappedFunction f::F evals::Int CountedFunction{F}(f) where F = new{F}(f, 0) end CountedFunction(f::Function) = CountedFunction{typeof(f)}(f) function (f::CountedFunction{F})(x::AbstractVector) where F f.evals += 1 return f.f(x) end numevals(f::CountedFunction) = f.evals # A function that keeps track of the number of evaluations mutable struct LoggedFunction{F} <: WrappedFunction f::F values::Vector{Float64} LoggedFunction{F}(f) where F = new{F}(f, Float64[]) end LoggedFunction(f::Function) = LoggedFunction{typeof(f)}(f) function (f::LoggedFunction{F})(x::AbstractVector) where F val = f.f(x) push!(f.values, val) return val end numevals(f::LoggedFunction) = length(f.values) # Quadratic-model Incremental Gaussian Elimination struct QmIGE{T,N} coefs::PermutedDimsArray{T,2,(2, 1),(2, 1),Array{T,2}} # to make row-major operations fast rhs::Vector{T} dimpiv::Vector{Int} # order in which dimensions were added rowzero::Vector{Bool} # true if a row in coefs is all-zeros rowbox::Vector{Box{T,N}} # the box that set this row ndims::typeof(Ref(1)) # number of dimensions added so far nzrows::typeof(Ref(1)) rowtmp::Vector{T} end function QmIGE{T,N}() where {T,N} m = ((N+1)*(N+2))Γ·2 - 1 # the constant is handled separately coefs = PermutedDimsArray(zeros(T, m, m), (2, 1)) rhs = zeros(T, m) rowtmp = zeros(T, m) dimpiv = zeros(Int, N) rowzero = fill(true, m) rowbox = Vector{Box{T,N}}(undef, m) QmIGE{T,N}(coefs, rhs, dimpiv, rowzero, rowbox, Ref(0), Ref(0), rowtmp) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
30306
dummyvalue(::Type{T}) where T<:AbstractFloat = T(NaN) dummyvalue(::Type{T}) where T = typemax(T) isdummy(val::T) where T = isequal(val, dummyvalue(T)) """ qnthresh(N) Return the minimum number of points needed to specify the quasi-Newton quadratic model in `N` dimensions. """ qnthresh(N) = ((N+1)*(N+2))Γ·2 """ xvert, fvert, qcoef = qfit(xm=>fm, x0=>f0, xp=>fp) Given three points `xm < x0 < xp ` and three corresponding values `fm`, `f0`, and `fp`, fit a quadratic. Returns the position `xvert` of the vertex, the quadratic's value `fvert` at `xvert`, and the coefficient `qcoef` of the quadratic term. `xvert` is a minimum if `qcoef > 0`. Note that if the three points lie on a line, `qcoef == 0` and both `xvert` and `fvert` will be infinite. """ function qfit(xfm, xf0, xfp) cm, c0, cp = lagrangecoefs(xfm, xf0, xfp) xm, fm = xfm x0, f0 = xf0 xp, fp = xfp qvalue(x) = cm*(x-x0)*(x-xp) + c0*(x-xm)*(x-xp) + cp*(x-xm)*(x-x0) qcoef = cm+c0+cp if fm == f0 == fp return x0, f0, zero(qcoef) # when it's flat, use the middle point as the "vertex" end xvert = (cm*(x0+xp) + c0*(xm+xp) + cp*(xm+x0))/(2*qcoef) return xvert, qvalue(xvert), qcoef end @inline function lagrangecoefs(xfm, xf0, xfp) xm, fm = xfm.first, xfm.second x0, f0 = xf0.first, xf0.second xp, fp = xfp.first, xfp.second @assert(xp > x0 && x0 > xm && isfinite(xm) && isfinite(xp)) cm = fm/((xm-x0)*(xm-xp)) # coefficients of Lagrange polynomial c0 = f0/((x0-xm)*(x0-xp)) cp = fp/((xp-xm)*(xp-x0)) cm, c0, cp end """ Ξ”f = qdelta(box) Return the difference `fmin - fbox`, where `fbox` is the value of `f` at the evaluation point of `box` and `fmin` is the minimum of a one-dimensional quadratic fit of `f` (using the data in `box.parent`) over the bounds of `box`. Note that `Ξ”f` might be -Inf, if `box` is unbounded and the quadratic estimate is not convex. """ function qdelta(box::Box) xv, fv = box.parent.xvalues, box.parent.fvalues xm, x0, xp = xv[1], xv[2], xv[3] fm, f0, fp = fv[1], fv[2], fv[3] fbox = box.parent.fvalues[box.parent_cindex] cm, c0, cp = lagrangecoefs(xm=>fm, x0=>f0, xp=>fp) qvalue(x) = cm*(x-x0)*(x-xp) + c0*(x-xm)*(x-xp) + cp*(x-xm)*(x-x0) bb = boxbounds(box) qcoef = cm+c0+cp xvert = (cm*(x0+xp) + c0*(xm+xp) + cp*(xm+x0))/(2*qcoef) if qcoef > 0 && bb[1] <= xvert <= bb[2] # Convex and the vertex is inside the box return qvalue(xvert) - fbox end # Otherwise, the minimum is achieved at one of the edges # This needs careful evaluation in the case of infinite boxes to avoid Inf - Inf == NaN. if isinf(bb[1]) || isinf(bb[2]) lcoef = -cm*(x0+xp) - c0*(xm+xp) - cp*(xm+x0) ccoef = cm*x0*xp + c0*xm*xp + cp*xm*x0 if qcoef == 0 # the function is linear let lcoef = lcoef, ccoef = ccoef lvalue(x) = lcoef*x + ccoef return min(lvalue(bb[1]), lvalue(bb[2])) - fbox end else qvalue_inf(x) = isinf(x) ? abs(x)*sign(qcoef) : qvalue(x) return min(qvalue_inf(bb[1]), qvalue_inf(bb[2])) - fbox end end return min(qvalue(bb[1]), qvalue(bb[2])) - fbox end function qdelta(box::Box{T}, splitdim::Integer) where T p = find_parent_with_splitdim(box, splitdim) return p.parent.splitdim == splitdim ? qdelta(p) : zero(T) end function is_diag_convex(box) # Test whether we're likely to be in a convex patch. This only checks the # diagonals, because that's quick. isdiagconvex = true for i = 1:ndims(box) p = find_parent_with_splitdim(box, i) if isroot(p) isdiagconvex = false else xs, fs = p.parent.xvalues, p.parent.fvalues xvert, fvert, qcoef = qfit(xs[1]=>fs[1], xs[2]=>fs[2], xs[3]=>fs[3]) isdiagconvex &= qcoef > 0 end isdiagconvex || break end return isdiagconvex end ## Minimum Edge List utilities Base.empty!(mel::MELink) = (mel.next = mel; return mel) function dropnext!(prev, next) if next != next.next # Drop the next item from the list next = next.next prev.next = next else # Drop the last item from the list prev.next = prev next = prev end return next end """ prev, next = trim!(mel::MELink, w, label=>fvalue) Remove entries from `mel` that are worse than `(w, label=>fvalue)`. Returns linked-list positions on either side of the putative new value. """ function trim!(mel::MELink, w, lf::Pair) l, f = lf.first, lf.second prev, next = mel, mel.next while prev != next && w > next.w if f <= next.f next = dropnext!(prev, next) else prev = next next = next.next end end if w == next.w && f < next.f next = dropnext!(prev, next) end return prev, next end function Base.insert!(mel::MELink, w, lf::Pair) l, f = lf prev, next = trim!(mel, w, lf) # Perform the insertion if prev == next # we're at the end of the list prev.next = typeof(mel)(l, w, f) else if f < next.f prev.next = typeof(mel)(l, w, f, next) end end return mel end function Base.iterate(mel::MELink) mel == mel.next && return nothing return (mel.next, mel.next) end function Base.iterate(mel::MELink, state::MELink) state == state.next && return nothing return (state.next, state.next) end function popfirst!(mel::MELink) item = mel.next mel.next = item.next == item ? mel : item.next return item end Base.length(mel::MELink) = count(x->true, mel) function Base.show(io::IO, mel::MELink) print(io, "List(") next = mel.next while mel != next print(io, '(', next.w, ", ", next.l, "=>", next.f, "), ") mel = next next = next.next end print(io, ')') end ### Box utilities function Base.show(io::IO, box::Box) x = fill(NaN, ndims(box)) position!(x, box) val = isroot(box) ? "Root" : value(box) print(io, "Box$val@", x) end function value(box::Box) isroot(box) && error("root box does not have a unique value") box.parent.fvalues[box.parent_cindex] end value_safe(box::Box{T}) where T = isroot(box) ? typemax(T) : value(box) Base.isless(box1::Box, box2::Box) = isless(value_safe(box1), value_safe(box2)) function pick_other(xvalues, fvalues, idx) j = 1 if j == idx j += 1 end xf1 = xvalues[j] => fvalues[j] j += 1 if j == idx j += 1 end xf2 = xvalues[j] => fvalues[j] return xf1, xf2 end function treeprint(io::IO, f::Function, root::Box) show(io, root) y = f(root) y != nothing && print(io, y) if !isleaf(root) print(io, '(') treeprint(io, f, root.children[1]) print(io, ", ") treeprint(io, f, root.children[2]) print(io, ", ") treeprint(io, f, root.children[3]) print(io, ')') end end treeprint(io::IO, root::Box) = treeprint(io, x->nothing, root) function add_children!(parent::Box{T}, splitdim, xvalues, fvalues, u::Real, v::Real) where T isleaf(parent) || error("cannot add children to non-leaf node") (length(xvalues) == 3 && xvalues[1] < xvalues[2] < xvalues[3]) || throw(ArgumentError("xvalues must be monotonic, got $xvalues")) parent.splitdim = splitdim p = find_parent_with_splitdim(parent, splitdim) if isroot(p) parent.minmax = (u, v) else parent.minmax = boxbounds(p) end for i = 1:3 @assert(parent.minmax[1] <= xvalues[i] <= parent.minmax[2]) end minsep = eps(T)*(xvalues[3]-xvalues[1]) @assert(xvalues[2]-xvalues[1] > minsep) @assert(xvalues[3]-xvalues[2] > minsep) parent.xvalues = xvalues parent.fvalues = fvalues for i = 1:3 Box(parent, i) # creates the children of parent end parent end function cycle_free(box) p = parent(box) while !isroot(p) p == box && return false p = p.parent end return true end function isparent(parent, child) parent == child && return true while !isroot(child) child = child.parent parent == child && return true end return false end """ boxp = find_parent_with_splitdim(box, splitdim::Integer) Return the first node at or above `box` who's parent box was split along dimension `splitdim`. If `box` has not yet been split along `splitdim`, returns the root box. """ function find_parent_with_splitdim(box::Box, splitdim::Integer) while !isroot(box) p = parent(box) if p.splitdim == splitdim return box end box = p end return box end """ box = greedy_smallest_child_leaf(root) Walk the tree recursively, choosing the child with smallest function value at each stage. `box` will be a leaf node. """ function greedy_smallest_child_leaf(box::Box) # Not guaranteed to be the smallest function value, it's the smallest that can be # reached stepwise while !isleaf(box) idx = argmin(box.fvalues) box = box.children[idx] end box end """ box = find_smallest_child_leaf(root) Return the node below `root` with smallest function value. """ function find_smallest_child_leaf(box::Box) vmin, boxmin = value(box), box for leaf in leaves(box) vleaf = value(leaf) if vleaf <= vmin vmin, boxmin = vleaf, leaf end end return boxmin end function unique_smallest_leaves(boxes) uboxes = Set{eltype(boxes)}() for box in boxes push!(uboxes, find_smallest_child_leaf(box)) end return uboxes end """ box = find_leaf_at(root, x) Return the leaf-node `box` that contains `x`. """ function find_leaf_at(root::Box, x) isleaf(root) && return root while !isleaf(root) i = root.splitdim found = false for box in (root.children[1], root.children[2], root.children[3]) bb = boxbounds(box) if bb[1] <= x[i] <= bb[2] root = box found = true break end end found || error("$(x[i]) not within $(root.minmax)") end root end """ box, success = find_leaf_at_edge(root, x, splitdim, dir) Return the node `box` that contains `x` with an edge at `x[splitdim]`. If `dir > 0`, a box to the right of the edge will be returned; if `dir < 0`, a box to the left will be returned. `box` will be a leaf-node unless `success` is false; the usual explanation for this is that the chosen edge is at the edge of the allowed domain, and hence there isn't a node in that direction. This is a useful utility for finding the neighbor of a given box. Example: # Let's find the neighbors of `box` along its parent's splitdim x = position(box, x0) i = box.parent.splitdim bb = boxbounds(box) # Right neighbor x[i] = bb[2] rnbr = find_leaf_at_edge(root, x, i, +1) # Left neighbor x[i] = bb[1] lnbr = find_leaf_at_edge(root, x, i, -1) """ function find_leaf_at_edge(root::Box, x, splitdim::Integer, dir::Signed) isleaf(root) && return root, false while !isleaf(root) i = root.splitdim found = false for box in (root.children[1], root.children[2], root.children[3]) bb = boxbounds(box) if within(x[i], bb, dir) root = box found = true break end end found || return (root, false) end return (root, true) end """ x = position(box) x = position(box, x0) Return the n-dimensional position vector `x` at which this box was evaluated when it was a leaf. Some entries of `x` might be `NaN`, if `box` is sufficiently near the root and not all dimensions have been split. The variant supplying `x0` fills in those dimensions with the corresponding values from `x0`. """ Base.position(box::Box) = position!(fill(NaN, ndims(box)), box) function Base.position(box::Box, x0::AbstractVector) x = similar(x0) flag = falses(length(x0)) position!(x, flag, box, x0) end function position!(x, flag, box::Box, x0::AbstractVector) copyto!(x, x0) position!(x, flag, box) end function position!(x, box::Box) flag = falses(length(x)) position!(x, flag, box) return x end function position!(x, flag, box::Box) fill!(flag, false) nfilled = 0 while !isroot(box) && nfilled < length(x) i = box.parent.splitdim if !flag[i] x[i] = box.parent.xvalues[box.parent_cindex] flag[i] = true nfilled += 1 end box = box.parent end x end function default_position!(x, flag, xdefault) length(x) == length(flag) == length(xdefault) || throw(DimensionMismatch("all three inputs must have the same length")) for i = 1:length(x) if !flag[i] x[i] = xdefault[i] end end x end """ left, right = boxbounds(box) Compute the bounds of `box` along the `splitdim` of `box`'s parent. This throws an error for the root box. """ function boxbounds(box::Box) isroot(box) && error("cannot compute bounds on root Box") p = parent(box) if box.parent_cindex == 1 return (p.minmax[1], (p.xvalues[1]+p.xvalues[2])/2) elseif box.parent_cindex == 2 return ((p.xvalues[1]+p.xvalues[2])/2, (p.xvalues[2]+p.xvalues[3])/2) elseif box.parent_cindex == 3 return ((p.xvalues[2]+p.xvalues[3])/2, p.minmax[2]) end error("invalid parent_cindex $(box.parent_cindex)") end """ left, right = boxbounds(box, lower::Real, upper::Real) Compute the bounds of `box` along the `splitdim` of `box`'s parent. For the root box, returns `(lower, upper)`. """ function boxbounds(box::Box, lower::Real, upper::Real) isroot(box) && return (lower, upper) return boxbounds(box) end """ bb = boxbounds(box, lower::AbstractVector, upper::AbstractVector) Compute the bounds of `box` along all dimensions. """ function boxbounds(box::Box{T}, lower::AbstractVector, upper::AbstractVector) where T length(lower) == length(upper) == ndims(box) || throw(DimensionMismatch("lower and upper must match dimensions of box")) bb = [(T(lower[i]), T(upper[i])) for i = 1:ndims(box)] boxbounds!(bb, box) end """ bb = boxbounds(box, splitdim::Integer, lower::AbstractVector, upper::AbstractVector) Compute the bounds of `box` along dimension `splitdim`. """ function boxbounds(box::Box{T}, splitdim::Integer, lower::AbstractVector, upper::AbstractVector) where T p = find_parent_with_splitdim(box, splitdim) boxbounds(p, lower[splitdim], upper[splitdim]) end function boxbounds!(bb, box::Box) flag = falses(ndims(box)) boxbounds!(bb, flag, box) return bb end function boxbounds!(bb, flag, box::Box) fill!(flag, false) if isleaf(box) bb[box.parent.splitdim] = boxbounds(box) flag[box.parent.splitdim] = true else bb[box.splitdim] = box.minmax flag[box.splitdim] = true end nfilled = 1 while !isroot(box) && nfilled < ndims(box) i = box.parent.splitdim if !flag[i] bb[i] = boxbounds(box) flag[i] = true nfilled += 1 end box = box.parent end bb end function boxbounds!(bb, flag, box::Box, lower, upper) for i = 1:ndims(box) bb[i] = (lower[i], upper[i]) end boxbounds!(bb, flag, box) end """ scale = boxscale(box, splits) Return a vector containing a robust measure of the "scale" of `box` along each coordinate axis. Specifically, it is typically related to the gap between evaluation points of its parent boxes, falling back on the initial user-supplied `splits` if it hasn't been split along a particular axis. Note that a box that extends to infinity still has a finite `scale`. Moreover, a box where one evaluation point is at the edge has a scale bigger than zero. """ function boxscale(box::Box{T,N}, splits) where {T,N} bxscale(s1, s2, s3) = s1 == s2 ? s3 - s2 : s2 == s3 ? s2 - s1 : min(s2-s1, s3-s2) bxscale(s) = bxscale(s[1], s[2], s[3]) scale = Vector{T}(undef, N) for i = 1:N p = find_parent_with_splitdim(box, i) splitsi = splits[i] if isroot(p) scale[i] = bxscale(splitsi) else scale[i] = bxscale(p.parent.xvalues) end end return scale end function width(box::Box, splitdim::Integer, xdefault::Real, lower::Real, upper::Real) p = find_parent_with_splitdim(box, splitdim) bb = boxbounds(p, lower, upper) x = isroot(p) ? xdefault : p.parent.xvalues[p.parent_cindex] max(x-bb[1], bb[2]-x) end width(box::Box, splitdim::Integer, xdefault, lower, upper) = width(box, splitdim, xdefault[splitdim], lower[splitdim], upper[splitdim]) function isinside(x, lower, upper) ret = true for i = 1:length(x) ret &= lower[i] <= x[i] <= upper[i] end ret end function isinside(x, bb::Vector{Tuple{T,T}}) where T ret = true for i = 1:length(x) bbi = bb[i] ret &= bbi[1] <= x[i] <= bbi[2] end ret end """ within(x, (left, right), dir) Return `true` if `x` lies between `left` and `right`. If `x` is on the edge, `dir` must point towards the interior (positive if `x==left`, negative if `x==right`). """ function within(x::Real, bb::Tuple{Real,Real}, dir) if !(bb[1] <= x <= bb[2]) return false end ((x == bb[1]) & (dir < 0)) && return false ((x == bb[2]) & (dir > 0)) && return false return true end function epswidth(bb::Tuple{T,T}) where T<:Real w1 = isfinite(bb[1]) ? eps(bb[1]) : T(0) w2 = isfinite(bb[2]) ? eps(bb[2]) : T(0) return 10*min(w1, w2) end function count_splits(box::Box) nsplits = Vector{Int}(undef, ndims(box)) count_splits!(nsplits, box) end function count_splits!(nsplits, box::Box) fill!(nsplits, 0) if box.splitdim == 0 box = box.parent box.splitdim == 0 && return nsplits # an unsplit tree end nsplits[box.splitdim] += 1 while !isroot(box) box = box.parent nsplits[box.splitdim] += 1 end return nsplits end function Base.extrema(root::Box) isleaf(root) && error("tree is empty") minv, maxv = extrema(root.fvalues) for bx in root isleaf(bx) && continue mn, mx = extrema(bx.fvalues) minv = min(minv, mn) maxv = max(maxv, mx) end minv, maxv end ## Utilities for experimenting with topology of the tree """ splitprint([io::IO], box) Print a representation of all boxes below `box`, using parentheses prefaced by a number `n` to denote a split along dimension `n`, and `l` to represent a leaf. See also [`parse`](@ref) for the inverse: converting a string representation to a tree of boxes. """ function splitprint(io::IO, box::Box) if isleaf(box) print(io, 'l') else print(io, box.splitdim, '(') splitprint(io, box.children[1]) print(io, ", ") splitprint(io, box.children[2]) print(io, ", ") splitprint(io, box.children[3]) print(io, ')') end end splitprint(box::Box) = splitprint(stdout, box) """ splitprint_colored([io::IO], box, innerbox) Like [`splitprint`](@ref), except that `innerbox` is highlighted in red, and the chain of parents of `innerbox` are highlighted in cyan. """ function splitprint_colored(io::IO, box::Box, thisbox::Box, allparents=get_allparents(thisbox)) if isleaf(box) box == thisbox ? printstyled(io, 'l', color=:light_red) : print(io, 'l') else if box == thisbox printstyled(io, box.splitdim, color=:light_red) elseif box ∈ allparents printstyled(io, box.splitdim, color=:cyan) else print(io, box.splitdim) end print(io, '(') splitprint_colored(io, box.children[1], thisbox, allparents) print(io, ", ") splitprint_colored(io, box.children[2], thisbox, allparents) print(io, ", ") splitprint_colored(io, box.children[3], thisbox, allparents) print(io, ')') end end splitprint_colored(box::Box, thisbox::Box) = splitprint_colored(stdout, box, thisbox) function get_allparents(box) allparents = Set{typeof(box)}() p = box while !isroot(p) p = parent(p) push!(allparents, p) end allparents end """ root = parse(Box{T,N}, string) Parse a `string`, in the output format of [`splitprint`](@ref), and generate a tree of boxes with that structure. """ function Base.parse(::Type{B}, str::AbstractString) where B<:Box b = B() splitbox!(b, str) end # splitbox! uses integer-valued positions and sets all function values to 0 function splitbox!(box::Box{T,N}, dim) where {T,N} x = position(box, zeros(N)) xd = x[dim] add_children!(box, dim, [xd,xd+1,xd+2], zeros(3), -Inf, Inf) box end function splitbox!(box::Box, str::AbstractString) str == "l" && return m = match(r"([0-9]*)\((.*)\)", str) dim = parse(Int, m.captures[1]) dimstr = m.captures[2] splitbox!(box, dim) commapos = [0,0] commaidx = 0 open = 0 i = firstindex(dimstr) while i <= ncodeunits(dimstr) c, i = iterate(dimstr, i) if c == '(' open += 1 elseif c == ')' open -= 1 elseif c == ',' && open == 0 commapos[commaidx+=1] = prevind(dimstr, i) end end splitbox!(box.children[1], strip(dimstr[1:prevind(dimstr, commapos[1])])) splitbox!(box.children[2], strip(dimstr[nextind(dimstr, commapos[1]):prevind(dimstr, commapos[2])])) splitbox!(box.children[3], strip(dimstr[nextind(dimstr, commapos[2]):end])) return box end ## Tree traversal """ root = get_root(box) Return the root node for `box`. """ function get_root(box::Box) while !isroot(box) box = parent(box) end box end abstract type DepthFirstIterator end Base.IteratorSize(::Type{<:DepthFirstIterator}) = Base.SizeUnknown() struct DepthFirstLeafIterator{B<:Box} <: DepthFirstIterator root::B end function leaves(root::Box) DepthFirstLeafIterator(root) end function Base.iterate(iter::DepthFirstLeafIterator) state = find_next_leaf(iter, iter.root) state === nothing && return nothing return state, state end Base.iterate(root::Box) = root, root function Base.iterate(iter::DepthFirstLeafIterator, state::Box) @assert(isleaf(state)) state = find_next_leaf(iter, state) state === nothing && return nothing return (state, state) end function find_next_leaf(iter::DepthFirstLeafIterator, state::Box) ret = iterate(iter.root, state) ret === nothing && return nothing while !isleaf(ret[1]) ret = iterate(iter.root, ret[2]) ret === nothing && return nothing end return ret[2] end function Base.iterate(root::Box, state::Box) item = state # old item if isleaf(item) box, i = up(item, root) if i <= length(box.children) item = box.children[i] return (item, item) end @assert(box == root) return nothing end item = item.children[1] return (item, item) end function up(box, root) local i box == root && return (box, length(box.children)+1) while true box, i = box.parent, box.parent_cindex+1 box == root && return (box, i) i <= length(box.children) && break end return (box, i) end function Base.length(iter::DepthFirstLeafIterator) ret = iterate(iter) len = 0 while ret !== nothing item, state = ret ret = iterate(iter, state) len += 1 end return len end ## Utilities for working with both mutable and immutable vectors replacecoordinate!(x, i::Integer, val) = (x[i] = val; x) replacecoordinate!(x::SVector{N,T}, i::Integer, val) where {N,T} = SVector{N,T}(_rpc(Tuple(x), i-1, T(val))) @inline _rpc(t, i, val) = (ifelse(i == 0, val, t[1]), _rpc(Base.tail(t), i-1, val)...) _rps(::Tuple{}, i, val) = () ipcopy!(dest, src) = copyto!(dest, src) ipcopy!(dest::SVector, src) = src ## Other utilities lohi(x, y) = x <= y ? (x, y) : (y, x) function lohi(x, y, z) @assert(x <= y) z <= x && return z, x, y z <= y && return x, z, y return x, y, z end function order_pairs(xf1, xf2) x1, f1 = xf1 x2, f2 = xf2 return x1 <= x2 ? (xf1, xf2) : (xf2, xf1) end function order_pairs(xf1, xf2, xf3) xf1, xf2 = order_pairs(xf1, xf2) xf2, xf3 = order_pairs(xf2, xf3) xf1, xf2 = order_pairs(xf1, xf2) return xf1, xf2, xf3 end function biggest_interval(a, b, c, d) ab, bc, cd = b-a, c-b, d-c if ab <= bc && ab <= cd return (a, b) elseif bc <= ab && bc <= cd return (b, c) end return (c, d) end function ensure_distinct(x::T, xref, bb::Tuple{Real,Real}; minfrac = 0.1) where T Ξ”x = min(xref - bb[1], bb[2] - xref) if !isfinite(Ξ”x) x != xref && return x return xref + 1 end Ξ”xmin = T(minfrac*Ξ”x) if abs(x - xref) < Ξ”xmin s = x == xref ? (bb[2] - xref > xref - bb[1] ? 1 : -1) : sign(x-xref) x = T(xref + Ξ”xmin*s) end return x end function ensure_distinct(x::T, x1, x2, bb::Tuple{Real,Real}; minfrac = 0.1) where T x1, x2 = lohi(x1, x2) Ξ”xmin = minfrac*min(x2-x1, bb[2] == x2 ? T(Inf) : bb[2]-x2, bb[1] == x1 ? T(Inf) : x1-bb[1]) @assert(Ξ”xmin > 0) if abs(x - x1) < Ξ”xmin s = x == x1 ? 1 : sign(x-x1) x = T(max(bb[1], x1 + Ξ”xmin*s)) elseif abs(x - x2) < Ξ”xmin s = x == x2 ? -1 : sign(x-x2) x = T(min(bb[2], x2 + Ξ”xmin*s)) end return x end """ t, exitdim = pathlength_box_exit(x0, dx, bb) Given a ray `x0 + t*dx`, compute the value of `t` at which the ray exits the box delimited by `bb` (a vector of `(lo, hi)` tuples). Also return the coordinate dimension along which the exit occurs. """ function pathlength_box_exit(x0, dx, bb) t = oftype((bb[1][1] - x0[1])/dx[1], Inf) exitdim = 0 for i = 1:length(x0) xi, dxi, bbi = x0[i], dx[i], bb[i] ti = (ifelse(dxi >= 0, bbi[2], bbi[1]) - xi)/dxi if ti < t t = ti exitdim = i end end t, exitdim end """ t, intersectdim = pathlength_hyperplane_intersect(x0, dx, xtarget, tmax) Compute the maximum pathlength `t` (up to a value of `tmax`) at which the ray `x0 + t*dx` intersects one of the hyperplanes specified by `x[i] = xtarget[i]` for any dimension `i`. """ function pathlength_hyperplane_intersect(x0, dx, xtarget, tmax) t = zero(typeof((xtarget[1] - x0[1])/dx[1])) intersectdim = 0 for i = 1:length(x0) xi, dxi, xti = x0[i], dx[i], xtarget[i] ti = (xti - xi)/dxi if ti <= tmax && ti > t t = ti intersectdim = i end end t, intersectdim end # function different_basins(boxes::AbstractVector{B}, x0, lower, upper) where B<:Box # basinboxes = B[] # for box in boxes # ubasin = true # for bbox in basinboxes # if !is_different_basin(box, bbox, x0, lower, upper) # ubasin = false # break # end # end # if ubasin # push!(basinboxes, box) # end # end # return basinboxes # end # function is_different_basin(box1, box2, x0, lower, upper) # # This convexity test has its limits: we're comparing the maximum along the secant # # within the box to a function value calculated at a point that isn't along the secant. # # False positives happen, but this is better than false negatives. # root = get_root(box1) # v1, v2 = value(box1), value(box2) # x1, x2 = position(box1, x0), position(box2, x0) # dx = x2 - x1 # bb = boxbounds(box1, lower, upper) # flag = Vector{Bool}(undef, length(lower)) # leaf = box1 # t, exitdim = pathlength_box_exit(x1, dx, bb) # # For consistency (e.g., commutivity with box1 and box2), we have to check # # exit condition even at first box, even though it's likely a false positive. # vmax = v1 + t*(v2-v1) # qdtot = oftype(vmax, 0) # # for i = 1:ndims(leaf) # commented out to avoid false negatives # # qdtot += qdelta(leaf, i) # # end # if value(leaf)+qdtot > vmax # return true # end # while t < 1 # x2[:] .= x1 .+ t.*dx # x2[exitdim] = bb[exitdim][dx[exitdim] > 0 ? 2 : 1] # avoid roundoff error in the critical coordinate # leaf_old = leaf # leaf, success = find_leaf_at_edge(root, x2, exitdim, dx[exitdim] > 0 ? +1 : -1) # success || break # boxbounds!(bb, flag, leaf, lower, upper) # tnext, exitdim = pathlength_box_exit(x1, dx, bb) # tnext = max(tnext, t) # while tnext == t # must have hit a corner # tnext += oftype(t, 1e-4) # x2[:] .= x1 .+ tnext.*dx # bxtmp = find_leaf_at(root, x2) # boxbounds!(bb, flag, bxtmp, lower, upper) # tnext, exitdim = pathlength_box_exit(x1, dx, bb) # end # vmax = v1 + t*(v2-v1) # if tnext < 1 # vmax = max(vmax, v1 + tnext*(v2-v1)) # end # qdtot = oftype(vmax, 0) # # for i = 1:ndims(leaf) # # qdtot += qdelta(leaf, i) # # end # if value(leaf)+qdtot > vmax # return true # end # t = tnext # end # return false # end """ a, b, c = pick3(a, b, (lower::Real, upper::Real)) Returns an ordered triple `a, b, c`, with two agreeing with the input `a` and `b`, and the third point bisecting the largest interval between `a`, `b`, and the edges `lower`, `upper`. """ function pick3(a, b, bb) a, b = lohi(a, b) imin, imax = biggest_interval(bb[1], a, b, bb[2]) if isinf(imin) return a-2*(b-a), a, b elseif isinf(imax) return a, b, b+2*(b-a) end return a, b, c = lohi(a, b, (imin+imax)/2) end function issame(x1, x2, scale, rtol=sqrt(eps(eltype(x1)))) same = true for i = 1:length(x1) same &= abs(x1[i] - x2[i]) < rtol*scale[i] end return same end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2700
module RFFT using FFTW, LinearAlgebra export RCpair, plan_rfft!, plan_irfft!, rfft!, irfft!, normalization import Base: real, complex, copy, copy! mutable struct RCpair{T<:AbstractFloat,N,RType<:AbstractArray{T,N},CType<:AbstractArray{Complex{T},N}} R::RType C::CType region::Vector{Int} end function RCpair{T}(::UndefInitializer, realsize::Dims{N}, region=1:length(realsize)) where {T<:AbstractFloat,N} sz = [realsize...] firstdim = region[1] sz[firstdim] = realsize[firstdim]>>1 + 1 sz2 = copy(sz) sz2[firstdim] *= 2 R = Array{T,N}(undef, (sz2...,)::Dims{N}) C = unsafe_wrap(Array, convert(Ptr{Complex{T}}, pointer(R)), (sz...,)::Dims{N}) # work around performance problems of reinterpretarray RCpair(view(R, map(n->1:n, realsize)...), C, [region...]) end RCpair(A::Array{T}, region=1:ndims(A)) where {T<:AbstractFloat} = copy!(RCpair{T}(undef, size(A), region), A) real(RC::RCpair) = RC.R complex(RC::RCpair) = RC.C copy!(RC::RCpair, A::AbstractArray{T}) where {T<:Real} = (copy!(RC.R, A); RC) function copy(RC::RCpair{T,N}) where {T,N} C = copy(RC.C) R = reshape(reinterpret(T, C), size(parent(RC.R))) RCpair(view(R, RC.R.indices...), C, copy(RC.region)) end # New API rplan_fwd(R, C, region, flags, tlim) = FFTW.rFFTWPlan{eltype(R),FFTW.FORWARD,true,ndims(R)}(R, C, region, flags, tlim) rplan_inv(R, C, region, flags, tlim) = FFTW.rFFTWPlan{eltype(R),FFTW.BACKWARD,true,ndims(R)}(R, C, region, flags, tlim) function plan_rfft!(RC::RCpair{T}; flags::Integer = FFTW.ESTIMATE, timelimit::Real = FFTW.NO_TIMELIMIT) where T p = rplan_fwd(RC.R, RC.C, RC.region, flags, timelimit) return Z::RCpair -> begin FFTW.assert_applicable(p, Z.R, Z.C) FFTW.unsafe_execute!(p, Z.R, Z.C) return Z end end function plan_irfft!(RC::RCpair{T}; flags::Integer = FFTW.ESTIMATE, timelimit::Real = FFTW.NO_TIMELIMIT) where T p = rplan_inv(RC.C, RC.R, RC.region, flags, timelimit) return Z::RCpair -> begin FFTW.assert_applicable(p, Z.C, Z.R) FFTW.unsafe_execute!(p, Z.C, Z.R) rmul!(Z.R, 1 / prod(size(Z.R)[Z.region])) return Z end end function rfft!(RC::RCpair{T}) where T p = rplan_fwd(RC.R, RC.C, RC.region, FFTW.ESTIMATE, FFTW.NO_TIMELIMIT) FFTW.unsafe_execute!(p, RC.R, RC.C) return RC end function irfft!(RC::RCpair{T}) where T p = rplan_inv(RC.C, RC.R, RC.region, FFTW.ESTIMATE, FFTW.NO_TIMELIMIT) FFTW.unsafe_execute!(p, RC.C, RC.R) rmul!(RC.R, 1 / prod(size(RC.R)[RC.region])) return RC end @deprecate RCpair(realtype::Type{T}, realsize, region=1:length(realsize)) where T<:AbstractFloat RCpair{T}(undef, realsize, region) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
14739
module RegisterCore using ..CenterIndexedArrays using ImageCore, ImageFiltering using Requires import Base: +, -, *, / export # types MismatchArray, NumDenom, ColonFun, PreprocessSNF, # functions highpass, indmin_mismatch, maxshift, mismatcharrays, ratio, separate, paddedview, trimmedview """ The major functions/types exported by this module are: - `NumDenom` and `MismatchArray`: packed pair representation of `(num,denom)` mismatch data - `separate`: splits a `NumDenom` array into its component `num,denom` arrays - `indmin_mismatch`: find the location of the minimum mismatch - `highpass`: highpass filter an image before performing registration - `PreprocessSNF`: shot-noise standardization and filtering """ RegisterCore """ x = NumDenom(num, denom) `NumDenom{T}` is an object containing a `(num,denom)` pair. `x.num` is `num` and `x.denom` is `denom`. Algebraically, `NumDenom` objects act like 2-vectors, and can be added and multiplied by scalars: nd1 + nd2 = NumDenom(nd1.num + nd2.num, nd1.denom + nd2.denom) 2*nd = NumDenom(2*nd.num, 2*nd.denom) Note that this is *not* what you'd get from normal arithmetic with ratios, where, e.g., `2*nd` would be expected to produce `NumDenom(2*nd.num, nd.denom)`. The reason for calling these `*` and `+` is for use in `Interpolations.jl`, because it allows interpolation to be performed on "both arrays" at once without recomputing the interpolation coefficients. See the documentation for information about how this is used for performing aperturered mismatch computations. As a consequence, there is no `convert(Float64, nd::NumDenom)` method, because the algebra above breaks any pretense that `NumDenom` numbers are somehow equivalent to ratios. If you want to convert to a ratio, see [`ratio`](@ref). """ struct NumDenom{T<:Number} num::T denom::T end NumDenom(n::Gray, d::Gray) = NumDenom(gray(n), gray(d)) NumDenom(n::Gray, d) = NumDenom(gray(n), d) NumDenom(n, d::Gray) = NumDenom(n, gray(d)) NumDenom(n, d) = NumDenom(promote(n, d)...) (+)(p1::NumDenom, p2::NumDenom) = NumDenom(p1.num + p2.num, p1.denom + p2.denom) (-)(p1::NumDenom, p2::NumDenom) = NumDenom(p1.num - p2.num, p1.denom - p2.denom) (*)(n::Number, p::NumDenom) = NumDenom(n * p.num, n * p.denom) (*)(p::NumDenom, n::Number) = n * p (/)(p::NumDenom, n::Number) = NumDenom(p.num / n, p.denom / n) Base.oneunit(::Type{NumDenom{T}}) where {T} = NumDenom{T}(oneunit(T), oneunit(T)) Base.oneunit(p::NumDenom) = oneunit(typeof(p)) Base.zero(::Type{NumDenom{T}}) where {T} = NumDenom(zero(T), zero(T)) Base.zero(p::NumDenom) = zero(typeof(p)) function Base.promote_rule(::Type{NumDenom{T1}}, ::Type{T2}) where {T1,T2<:Number} return NumDenom{promote_type(T1, T2)} end function Base.promote_rule(::Type{NumDenom{T1}}, ::Type{NumDenom{T2}}) where {T1,T2} return NumDenom{promote_type(T1, T2)} end Base.eltype(::Type{NumDenom{T}}) where {T} = T Base.convert(::Type{NumDenom{T}}, p::NumDenom{T}) where {T} = p Base.convert(::Type{NumDenom{T}}, p::NumDenom) where {T} = NumDenom{T}(p.num, p.denom) function Base.round(::Type{NumDenom{T}}, p::NumDenom) where {T} return NumDenom{T}(round(T, p.num), round(T, p.denom)) end function Base.convert(::Type{F}, p::NumDenom) where {F<:AbstractFloat} return error("`convert($F, ::NumDenom)` is deliberately not defined, see `?NumDenom`.") end function Base.show(io::IO, p::NumDenom) print(io, "NumDenom(") show(io, p.num) print(io, ",") show(io, p.denom) print(io, ")") return nothing end const MismatchArray{ND<:NumDenom,N,A} = CenterIndexedArray{ND,N,A} """ mxs = maxshift(D) Return the `maxshift` value used to compute the mismatch array `D`. """ maxshift(A::MismatchArray) = A.halfsize """ `numdenom = MismatchArray(num, denom)` packs the array-pair `(num,denom)` into a single `MismatchArray`. This is useful preparation for interpolation. """ function (::Type{M})(num::AbstractArray, denom::AbstractArray) where {M<:MismatchArray} size(num) == size(denom) || throw(DimensionMismatch("num and denom must have the same size")) T = promote_type(eltype(num), eltype(denom)) numdenom = CenterIndexedArray{NumDenom{T}}(undef, size(num)) return _packnd!(numdenom, num, denom) end function _packnd!(numdenom::AbstractArray, num::AbstractArray, denom::AbstractArray) Rnd, Rnum, Rdenom = eachindex(numdenom), eachindex(num), eachindex(denom) if Rnum == Rdenom for (Idest, Isrc) in zip(Rnd, Rnum) @inbounds numdenom[Idest] = NumDenom(num[Isrc], denom[Isrc]) end elseif Rnd == Rnum for (Inum, Idenom) in zip(Rnum, Rdenom) @inbounds numdenom[Inum] = NumDenom(num[Inum], denom[Idenom]) end else for (Ind, Inum, Idenom) in zip(Rnd, Rnum, Rdenom) @inbounds numdenom[Ind] = NumDenom(num[Inum], denom[Idenom]) end end return numdenom end function _packnd!( numdenom::CenterIndexedArray, num::CenterIndexedArray, denom::CenterIndexedArray ) @simd for I in eachindex(num) @inbounds numdenom[I] = NumDenom(num[I], denom[I]) end return numdenom end # The next are mostly used just for testing """ `mms = mismatcharrays(nums, denoms)` packs array-of-arrays num/denom pairs as an array-of-MismatchArrays. `mms = mismatcharrays(nums, denom)`, for `denom` a single array, uses the same `denom` array for all `nums`. """ function mismatcharrays( nums::AbstractArray{A}, denom::AbstractArray{T} ) where {A<:AbstractArray,T<:Number} first = true local mms for i in eachindex(nums) num = nums[i] mm = MismatchArray(num, denom) if first mms = Array{typeof(mm)}(undef, size(nums)) first = false end mms[i] = mm end return mms end function mismatcharrays( nums::AbstractArray{A1}, denoms::AbstractArray{A2} ) where {A1<:AbstractArray,A2<:AbstractArray} size(nums) == size(denoms) || throw( DimensionMismatch("nums and denoms arrays must have the same number of apertures"), ) first = true local mms for i in eachindex(nums, denoms) mm = MismatchArray(nums[i], denoms[i]) if first mms = Array{typeof(mm)}(undef, size(nums)) first = false end mms[i] = mm end return mms end """ `num, denom = separate(mm)` splits an `AbstractArray{NumDenom}` into separate numerator and denominator arrays. """ function separate(data::AbstractArray{NumDenom{T}}) where {T} num = Array{T}(undef, size(data)) denom = similar(num) for I in eachindex(data) nd = data[I] num[I] = nd.num denom[I] = nd.denom end return num, denom end function separate(mm::MismatchArray) num, denom = separate(mm.data) return CenterIndexedArray(num), CenterIndexedArray(denom) end function separate(mma::AbstractArray{M}) where {M<:MismatchArray} T = eltype(eltype(M)) nums = Array{CenterIndexedArray{T,ndims(M)}}(undef, size(mma)) denoms = similar(nums) for (i, mm) in enumerate(mma) nums[i], denoms[i] = separate(mm) end return nums, denoms end """ r = ratio(nd::NumDenom, thresh, fillval=NaN) Return `nd.num/nd.denom`, unless `nd.denom < thresh`, in which case return `fillval` converted to the same type as the ratio. Choosing a `thresh` of zero will always return the ratio. """ @inline function ratio(nd::NumDenom{T}, thresh, fillval=convert(T, NaN)) where {T} r = nd.num / nd.denom return nd.denom < thresh ? oftype(r, fillval) : r end ratio(r::Real, thresh, fillval=NaN) = r function (::Type{M})(::Type{T}, dims::Dims) where {M<:MismatchArray,T} return CenterIndexedArray{NumDenom{T}}(undef, dims) end function (::Type{M})(::Type{T}, dims::Integer...) where {M<:MismatchArray,T} return CenterIndexedArray{NumDenom{T}}(undef, dims) end function Base.copyto!(M::MismatchArray, nd::Tuple{AbstractArray,AbstractArray}) num, denom = nd size(M) == size(num) == size(denom) || error("all sizes must match") for (IM, Ind) in zip(eachindex(M), eachindex(num)) M[IM] = NumDenom(num[Ind], denom[Ind]) end return M end #### Utility functions #### """ `index = indmin_mismatch(numdenom, thresh)` returns the location of the minimum value of what is effectively `num./denom`. However, it considers only those points for which `denom .> thresh`; moreover, it will never choose an edge point. `index` is a CartesianIndex into the arrays. """ function indmin_mismatch(numdenom::MismatchArray{NumDenom{T},N}, thresh::Real) where {T,N} imin = CartesianIndex(ntuple(d -> 0, Val(N))) rmin = typemax(T) threshT = convert(T, thresh) @inbounds for I in CartesianIndices(map(trimedges, axes(numdenom))) nd = numdenom[I] if nd.denom > threshT r = nd.num / nd.denom if r < rmin imin = I rmin = r end end end return imin end function indmin_mismatch(r::CenterIndexedArray{T,N}) where {T<:Number,N} imin = CartesianIndex(ntuple(d -> 0, Val(N))) rmin = typemax(T) @inbounds for I in CartesianIndices(map(trimedges, axes(r))) rval = r[I] if rval < rmin imin = I rmin = rval end end return imin end trimedges(r::AbstractUnitRange) = (first(r) + 1):(last(r) - 1) ### Miscellaneous """ `datahp = highpass([T], data, sigma)` returns a highpass-filtered version of `data`, with all negative values truncated at 0. The highpass is computed by subtracting a lowpass-filtered version of data, using Gaussian filtering of width `sigma`. As it is based on `Image.jl`'s Gaussian filter, it gracefully handles `NaN` values. If you do not wish to highpass-filter along a particular axis, put `Inf` into the corresponding slot in `sigma`. You may optionally specify the element type of the result, which for `Integer` or `FixedPoint` inputs defaults to `Float32`. """ function highpass(::Type{T}, data::AbstractArray, sigma) where {T} if any(isinf, sigma) datahp = convert(Array{T,ndims(data)}, data) else datahp = data - imfilter(T, data, KernelFactors.IIRGaussian(T, (sigma...,)), NA()) end datahp[datahp .< 0] .= 0 # truncate anything below 0 return datahp end highpass(data::AbstractArray{T}, sigma) where {T<:AbstractFloat} = highpass(T, data, sigma) highpass(data::AbstractArray, sigma) = highpass(Float32, data, sigma) """ `pp = PreprocessSNF(bias, sigmalp, sigmahp)` constructs an object that can be used to pre-process an image as `pp(img)`. The "SNF" part of the name means "shot-noise filtered," meaning that this preprocessor is specifically designed for situations in which you are dominated by shot noise (i.e., from photon-counting statistics). The processing is of the form ``` imgout = bandpass(√max(0,img-bias)) ``` i.e., the image is bias-subtracted, square-root transformed (to turn shot noise into constant variance), and then band-pass filtered using Gaussian filters of width `sigmalp` (for the low-pass) and `sigmahp` (for the high-pass). You can pass `sigmalp=zeros(n)` to skip low-pass filtering, and `sigmahp=fill(Inf, n)` to skip high-pass filtering. """ mutable struct PreprocessSNF # Shot-noise filtered bias::Float32 sigmalp::Vector{Float32} sigmahp::Vector{Float32} end # PreprocessSNF(bias::T, sigmalp, sigmahp) = PreprocessSNF{T}(bias, T[sigmalp...], T[sigmahp...]) function preprocess(pp::PreprocessSNF, A::AbstractArray) Af = sqrt_subtract_bias(A, pp.bias) return imfilter( highpass(Af, pp.sigmahp), KernelFactors.IIRGaussian((pp.sigmalp...,)), NA() ) end (pp::PreprocessSNF)(A::AbstractArray) = preprocess(pp, A) # For SubArrays, extend to the parent along any non-sliced # dimension. That way, we keep any information from padding. function (pp::PreprocessSNF)(A::SubArray) Bpad = preprocess(pp, paddedview(A)) return trimmedview(Bpad, A) end # ImageMeta method is defined under @require in __init__ function sqrt_subtract_bias(A, bias) # T = typeof(sqrt(one(promote_type(eltype(A), typeof(bias))))) T = Float32 out = Array{T}(undef, size(A)) for I in eachindex(A) @inbounds out[I] = sqrt(max(zero(T), convert(T, A[I]) - bias)) end return out end """ `Apad = paddedview(A)`, for a SubArray `A`, returns a SubArray that extends to the full parent along any non-sliced dimensions of the parent. See also [`trimmedview`](@ref). """ paddedview(A::SubArray) = _paddedview(A, (), (), A.indices...) function _paddedview(A::SubArray{T,N,P,I}, newindexes, newsize) where {T,N,P,I} return SubArray(A.parent, newindexes) end @inline function _paddedview(A, newindexes, newsize, index, indexes...) d = length(newindexes) + 1 return _paddedview( A, (newindexes..., pdindex(A.parent, d, index)), pdsize(A.parent, newsize, d, index), indexes..., ) end pdindex(A, d, i::Base.Slice) = i pdindex(A, d, i::Real) = i pdindex(A, d, i::UnitRange) = 1:size(A, d) pdindex(A, d, i) = error("Cannot pad with an index of type ", typeof(i)) pdsize(A, newsize, d, i::Base.Slice) = tuple(newsize..., size(A, d)) pdsize(A, newsize, d, i::Real) = newsize pdsize(A, newsize, d, i::UnitRange) = tuple(newsize..., size(A, d)) """ `B = trimmedview(Bpad, A::SubArray)` returns a SubArray `B` with `axes(B) = axes(A)`. `Bpad` must have the same size as `paddedview(A)`. """ function trimmedview(Bpad, A::SubArray) ndims(Bpad) == ndims(A) || throw( DimensionMismatch( "dimensions $(ndims(Bpad)) and $(ndims(A)) of Bpad and A must match" ), ) return _trimmedview(Bpad, A.parent, 1, (), A.indices...) end _trimmedview(Bpad, P, d, newindexes) = view(Bpad, newindexes...) @inline function _trimmedview(Bpad, P, d, newindexes, index::Real, indexes...) return _trimmedview(Bpad, P, d + 1, newindexes, indexes...) end @inline function _trimmedview(Bpad, P, d, newindexes, index, indexes...) dB = length(newindexes) + 1 Bsz = size(Bpad, dB) Psz = size(P, d) Bsz == Psz || throw( DimensionMismatch("dimension $dB of Bpad has size $Bsz, should have size $Psz") ) return _trimmedview(Bpad, P, d + 1, (newindexes..., index), indexes...) end # For faster and type-stable slicing struct ColonFun end ColonFun(::Int) = Colon() function __init__() @require ImageMetadata = "bc367c6b-8a6b-528e-b4bd-a4b897500b49" begin function (pp::PreprocessSNF)(A::ImageMetadata.ImageMeta) return ImageMetadata.shareproperties(A, pp(ImageMetadata.arraydata(A))) end end end include("deprecations.jl") end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
212
import Base: one @deprecate one(::Type{NumDenom{T}}) where T oneunit(NumDenom{T}) @deprecate one(p::NumDenom) oneunit(p) @deprecate ratio(mm::AbstractArray, args...) ratio.(mm, args...)
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
3236
module RegisterDeformation using ImageCore, ImageAxes, Interpolations, StaticArrays, HDF5, JLD2, ProgressMeter using ..RegisterUtilities, LinearAlgebra, Rotations, Base.Cartesian using Distributed, Statistics, SharedArrays using Base: tail using Interpolations: AbstractInterpolation, AbstractExtrapolation import ImageTransformations: warp, warp! # to avoid `scale` conflict with Interpolations, selectively import CoordinateTransformations: using CoordinateTransformations: AffineMap import CoordinateTransformations: compose using OffsetArrays: IdentityUnitRange # for Julia-version compatibility export # types AbstractDeformation, GridDeformation, WarpedArray, # functions arraysize, # TODO: don't export? centeraxes, compose, eachnode, extrapolate, extrapolate!, getindex!, griddeformations, interpolate, interpolate!, medfilt, nodegrid, regrid, similarΟ•, tform2deformation, tinterpolate, translate, vecindex, # TODO: don't export? vecgradient!, # TODO: don't export? warp, warp!, warpgrid, # old AffineTransfroms.jl code (TODO?: remove) tformtranslate, tformrotate, tformeye, rotation2, rotation3, rotationparameters, transform!, transform const DimsLike = Union{Vector{Int},Dims} const InterpExtrap = Union{AbstractInterpolation,AbstractExtrapolation} """ # RegisterDeformation A deformation (or warp) of space is represented by a function `Ο•(x)`. For an image, the warped version of the image is specified by "looking up" the pixel value at a location `Ο•(x) = x + u(x)`. `u(x)` thus expresses the displacement, in pixels, at position `x`. Note that a constant deformation, `u(x) = x0`, corresponds to a shift of the *coordinates* by `x0`, and therefore a shift of the *image* in the opposite direction. In reality, deformations will be represented on a grid, and interpolation is implied at locations between grid points. For a deformation defined directly from an array, make it interpolating using `Ο•i = interpolate(Ο•)`. The major functions/types exported by RegisterDeformation are: - `GridDeformation`: create a deformation - `tform2deformation`: convert an `AffineMap` to a deformation - `Ο•_old(Ο•_new)` and `compose`: composition of two deformations - `warp` and `warp!`: deform an image - `WarpedArray`: create a deformed array lazily - `warpgrid`: visualize a deformation """ RegisterDeformation abstract type AbstractDeformation{T,N} end Base.eltype(::Type{AbstractDeformation{T,N}}) where {T,N} = T Base.ndims(::Type{AbstractDeformation{T,N}}) where {T,N} = N Base.eltype(::Type{D}) where {D<:AbstractDeformation} = eltype(supertype(D)) Base.ndims(::Type{D}) where {D<:AbstractDeformation} = ndims(supertype(D)) Base.eltype(d::AbstractDeformation) = eltype(typeof(d)) Base.ndims(d::AbstractDeformation) = ndims(typeof(d)) include("griddeformation.jl") include("utils.jl") include("timeseries.jl") include("tformedarrays.jl") const Extrapolatable{T,N} = Union{TransformedArray{T,N},AbstractExtrapolation{T,N}} include("warpedarray.jl") include("warp.jl") include("visualize.jl") include("deprecated.jl") end # module
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2175
@inline function Base.getproperty(Ο•::GridDeformation, name::Symbol) if name === :u return getfield(Ο•, :u) elseif name === :nodes return getfield(Ο•, :nodes) elseif name === :knots Base.depwarn("the field name of `GridDeformation` has changed from `knots` to `nodes`.", :getproperty) return getfield(Ο•, :nodes) end error("field ", name, " is not available") end function GridDeformation(u::AbstractArray{FV,N}, sz::NTuple{N,L}) where {FV<:SVector,N,L<:Integer} Base.depwarn("`GridDeformation(u, size(fixed))` is deprecated, use `GridDeformation(u, axes(fixed))` instead.", :GridDeformation) return GridDeformation(u, map(Base.OneTo, sz)) end # The above causes an ambiguity, resolve it function GridDeformation(u::AbstractArray{FV,0}, nodes::Tuple{}) where FV<:SVector error("node tuple cannot be empty") end function GridDeformation(u, nodes::AbstractVector{<:Integer}) Base.depwarn("`GridDeformation(u, [size(fixed)...])` is deprecated, pass the axes of `fixed` instead.", :GridDeformation) GridDeformation(u, map(Base.OneTo, (nodes...,))) end function tform2deformation(tform::AffineMap{M,V}, arraysize::DimsLike, gridsize) where {M,V} Base.depwarn(""" `tform2deformation(tform, arraysize, gridsize)` is deprecated. Formerly, `tform` was defined so as to apply to `centered(img)`, which shifts the axes of `img` to put 0 at the midpoint of `img`. Now you should call this as `tform2deformation(tform, axs, gridsize)`, where `axs` represents the desired domain of `tform`. If you are transitioning old code, either use `axs = axes(fixed)` if `fixed` is already centered, or `axs = centeraxes(axes(fixed))` if not. """, :tform2deformation) axs = map((arraysize...,)) do sz halfsz = sz Γ· 2 IdentityUnitRange(1-halfsz:sz-halfsz) end return tform2deformation(tform, axs, (gridsize...,)) end import Base: getindex @deprecate getindex(Ο•::GridDeformation{T,N,A}, xs::Vararg{Number,N}) where {T,N,A<:AbstractInterpolation} Ο•(xs...) Base.@deprecate_binding eachknot eachnode Base.@deprecate_binding knotgrid nodegrid
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
17276
""" `Ο• = GridDeformation(u::Array{<:SVector}, axs)` creates a deformation `Ο•` for an array with axes `axs`. `u` specifies the "pixel-wise" displacement at a series of nodes that are evenly-spaced over the domain specified by `axs` (i.e., using node-vectors `range(first(axs[d]), stop=last(axs[d]), length=size(u,d))`). In particular, each corner of the array is the site of one node. `Ο• = GridDeformation(u::Array{<:SVector}, nodes)` specifies the node-vectors manually. `u` must have dimensions equal to `(length(nodes[1]), length(nodes[2]), ...)`. `Ο• = GridDeformation(u::Array{T<:Real}, ...)` constructs the deformation from a "plain" `u` array. For a deformation in `N` dimensions, `u` must have `N+1` dimensions, where the first dimension corresponds to the displacement along each axis (and therefore `size(u,1) == N`). Finally, `Ο• = GridDeformation((u1, u2, ...), ...)` allows you to construct the deformation using an `N`-tuple of shift-arrays, each with `N` dimensions. # Example To represent a two-dimensional deformation over a spatial region `1:100 Γ— 1:200` (e.g., for an image of that size), ```julia gridsize = (3, 5) # a coarse grid u = 10*randn(2, gridsize...) # each displacement is 2-dimensional, typically ~10 pixels nodes = (range(1, stop=100, length=gridsize[1]), range(1, stop=200, length=gridsize[2])) Ο• = GridDeformation(u, nodes) # this is a "naive" deformation (not ready for interpolation) ``` """ struct GridDeformation{T,N,A<:AbstractArray,L} <: AbstractDeformation{T,N} u::A nodes::NTuple{N,L} function GridDeformation{T,N,A,L}(u::AbstractArray{FV,N}, nodes::NTuple{N,L}) where {T,N,A,L,FV<:SVector} typeof(u) == A || error("typeof(u) = $(typeof(u)), which is different from $A") length(FV) == N || throw(DimensionMismatch("Dimensionality $(length(FV)) must match $N node vectors")) for d = 1:N size(u, d) == length(nodes[d]) || error("size(u) = $(size(u)), but the nodes specify a grid of size $(map(length, nodes))") end new{T,N,A,L}(u, nodes) end function GridDeformation{T,N,A,L}(u::ScaledInterpolation{FV,N}) where {T,N,A,L,FV<:SVector} new{T,N,A,L}(u, u.ranges) end end const InterpolatingDeformation{T,N,A<:AbstractInterpolation} = GridDeformation{T,N,A} # With node ranges function GridDeformation(u::AbstractArray{FV,N}, nodes::NTuple{N,L}) where {FV<:SVector,N,L<:AbstractVector} T = eltype(FV) length(FV) == N || throw(DimensionMismatch("$N-dimensional array requires SVector{$N,T}")) GridDeformation{T,N,typeof(u),L}(u, nodes) end # With image axes function GridDeformation(u::AbstractArray{FV,N}, axs::NTuple{N,L}) where {FV<:SVector,N,L<:AbstractUnitRange{<:Integer}} T = eltype(FV) length(FV) == N || throw(DimensionMismatch("$N-dimensional array requires SVector{$N,T}")) nodes = ntuple(N) do d ax = axs[d] range(first(ax), stop=last(ax), length=size(u,d)) end GridDeformation{T,N,typeof(u),typeof(nodes[1])}(u, nodes) end # Construct from a plain array function GridDeformation(u::AbstractArray{T}, nodes::NTuple{N}) where {T<:Number,N} ndims(u) == N+1 || error("`u` needs $(N+1) dimensions for $N-dimensional deformations") size(u, 1) == N || error("first dimension of u must be of length $N") uf = Array(convert_to_fixed(SVector{N,T}, u, tail(size(u)))) GridDeformation(uf, nodes) end # Construct from a (u1, u2, ...) tuple function GridDeformation(u::NTuple{N,AbstractArray}, nodes::NTuple{N}) where N ndims(u[1]) == N || error("Need $N dimensions for $N-dimensional deformations") ua = permutedims(cat(u..., dims=N+1), (N+1,(1:N)...)) uf = Array(convert_to_fixed(ua)) GridDeformation(uf, nodes) end # When nodes is a vector GridDeformation(u, nodes::AbstractVector{V}) where {V<:AbstractVector} = GridDeformation(u, (nodes...,)) function GridDeformation(u::ScaledInterpolation{FV}) where FV<:SVector N = length(FV) ndims(u) == N || throw(DimensionMismatch("Dimension $(ndims(u)) incompatible with vectors of length $N")) GridDeformation{eltype(FV),N,typeof(u),typeof(u.ranges[1])}(u) end function Base.show(io::IO, Ο•::GridDeformation{T}) where T if Ο•.u isa AbstractInterpolation print(io, "Interpolating ") end print(io, Base.dims2string(size(Ο•.u)), " GridDeformation{", T, "} over a domain ") for (i, n) in enumerate(Ο•.nodes) print(io, first(n), "..", last(n)) i < length(Ο•.nodes) && print(io, 'Γ—') end end """ `Ο•s = griddeformations(u, nodes)` constructs a vector `Ο•s` of seqeuential deformations. The last dimension of the array `u` should correspond to time; `Ο•s[i]` is produced from `u[:, ..., i]`. """ function griddeformations(u::AbstractArray{T}, nodes::NTuple{N}) where {N,T<:Number} ndims(u) == N+2 || error("Need $(N+2) dimensions for a vector of $N-dimensional deformations") size(u,1) == N || error("First dimension of u must be of length $N") uf = Array(convert_to_fixed(SVector{N,T}, u, Base.tail(size(u)))) griddeformations(uf, nodes) end function griddeformations(u::AbstractArray{FV}, nodes::NTuple{N}) where {N,FV<:SVector} ndims(u) == N+1 || error("Need $(N+1) dimensions for a vector of $N-dimensional deformations") length(FV) == N || throw(DimensionMismatch("Dimensionality $(length(FV)) must match $N node vectors")) colons = ntuple(d->Colon(), Val(N)) [GridDeformation(view(u, colons..., i), nodes) for i = 1:size(u, N+1)] end Base.:(==)(Ο•1::GridDeformation, Ο•2::GridDeformation) = Ο•1.u == Ο•2.u && Ο•1.nodes == Ο•2.nodes Base.copy(Ο•::GridDeformation{T,N,A,L}) where {T,N,A,L} = (u = copy(Ο•.u); GridDeformation{T,N,typeof(u),L}(u, map(copy, Ο•.nodes))) # # TODO: flesh this out # immutable VoroiDeformation{T,N,Vu<:AbstractVector,Vc<:AbstractVector} <: AbstractDeformation{T,N} # u::Vu # centers::Vc # simplexes::?? # end # (but there are several challenges, including the lack of a continuous gradient) """ Ο•i = interpolate(Ο•, BC=Flat(OnCell())) Create a deformation `Ο•i` suitable for interpolation, matching the displacements of `Ο•.u` at the nodes. A quadratic interpolation scheme is used, with default flat boundary conditions. """ function Interpolations.interpolate(Ο•::GridDeformation, BC=Flat(OnCell())) itp = scale(interpolate(Ο•.u, BSpline(Quadratic(BC))), Ο•.nodes...) GridDeformation(itp) end """ Ο•i = extrapolate(Ο•, BC=Flat(OnCell())) Create a deformation `Ο•i` suitable for interpolation, matching the displacements of `Ο•.u` at the nodes. A quadratic interpolation scheme is used, with default flat boundary conditions and `Line` extrapolation. !!! warning Extrapolation beyond the supported region of `Ο•` can yield poor results. """ function Interpolations.extrapolate(Ο•::GridDeformation, BC=Flat(OnCell())) etp = _extrapolate(Ο•.u, Ο•.nodes, BC) GridDeformation(etp) end _extrapolate(A::AbstractArray, nodes, BC) = _extrapolate(interpolate(A, BSpline(Quadratic(BC))), nodes, BC) _extrapolate(A::AbstractInterpolation, nodes, BC) = _extrapolate(extrapolate(A, Line()), nodes, BC) _extrapolate(A::AbstractExtrapolation, nodes, BC) = scale(A, nodes...) _extrapolate(A::ScaledInterpolation, nodes, BC) = _extrapolate(A.itp, nodes, BC) """ Ο•i = interpolate!(Ο•, BC=InPlace(OnCell())) Create a deformation `Ο•i` suitable for interpolation, matching the displacements of `Ο•.u` at the nodes. `Ο•` is destroyed in the process. A quadratic interpolation scheme is used, with the default being to use "InPlace" boundary conditions. !!! warning Because of the difference in default boundary conditions, `interpolate!(copy(Ο•))` does *not* yield a result identical to `interpolate(Ο•)`. When it matters, it is recommended that you annotate such calls with `# not same as interpolate(Ο•)` in your code. """ function Interpolations.interpolate!(Ο•::GridDeformation, BC=InPlace(OnCell())) itp = scale(interpolate!(Ο•.u, BSpline(Quadratic(BC))), Ο•.nodes...) GridDeformation(itp) end Interpolations.interpolate(Ο•::InterpolatingDeformation, args...) = error("Ο• is already interpolating") Interpolations.interpolate!(Ο•::InterpolatingDeformation, args...) = error("Ο• is already interpolating") """ Ο•i = extrapolate!(Ο•, BC=InPlace(OnCell())) Create a deformation `Ο•i` suitable for interpolation, matching the displacements of `Ο•.u` at the nodes. `Ο•` is destroyed in the process. A quadratic interpolation scheme is used, with the default being to use "InPlace" boundary conditions. !!! warning Because of the difference in default boundary conditions, `extrapolate!(copy(Ο•))` does *not* yield a result identical to `extrapolate(Ο•)`. When it matters, it is recommended that you annotate such calls with `# not same as extrapolate(Ο•)` in your code. """ function extrapolate!(Ο•::GridDeformation, BC=InPlace(OnCell())) etp = _extrapolate!(Ο•.u, Ο•.nodes, BC) GridDeformation(etp) end _extrapolate!(A, nodes, BC) = _extrapolate(interpolate!(A, BSpline(Quadratic(BC))), nodes, BC) _extrapolate!(A::AbstractInterpolation, nodes, BC) = error("Ο• is already interpolating") function vecindex(Ο•::GridDeformation{T,N,A}, x::SVector{N}) where {T,N,A<:AbstractInterpolation} x + vecindex(Ο•.u, x) end """ Ο• = similarΟ•(Ο•ref, coefs) Create a deformation with the same nodes as `Ο•ref` but using `coefs` for the data. This is primarily useful for testing purposes, e.g., computing gradients with `ForwardDiff` where the elements are `ForwardDiff.Dual` numbers. If `Ο•ref` is interpolating, `coefs` will be used for the interpolation coefficients, not the node displacements. Typically you want to create `Ο•ref` with Ο•ref = interpolate!(copy(Ο•0)) rather than `interpolate(Ο•0)` (see [`interpolate!`](@ref)). """ function similarΟ•(Ο•ref, coefs::AbstractArray{<:Number}) coefsref = getcoefs(Ο•ref) N = ndims(coefsref) udata = convert_to_fixed(SVector{N,eltype(coefs)}, coefs, size(coefsref)) return similarΟ•(Ο•ref, udata) end similarΟ•(Ο•ref, udata::AbstractArray{<:SVector}) = _similarΟ•(Ο•ref, udata) _similarΟ•(Ο•ref::GridDeformation, udata) = GridDeformation(udata, Ο•ref.nodes) function _similarΟ•(Ο•ref::InterpolatingDeformation, udata) scaleref = Ο•ref.u itpref = scaleref.itp itp = Interpolations.BSplineInterpolation(floattype(eltype(udata)), udata, itpref.it, itpref.parentaxes) return GridDeformation(scale(itp, Ο•ref.nodes...)) end # @generated function Base.getindex(Ο•::GridDeformation{T,N,A}, xs::Vararg{Number,N}) where {T,N,A<:AbstractInterpolation} # xindexes = [:(xs[$d]) for d = 1:N] # Ο•xindexes = [:(xs[$d]+ux[$d]) for d = 1:N] # quote # $(Expr(:meta, :inline)) # ux = Ο•.u($(xindexes...)) # SVector($(Ο•xindexes...)) # end # end @inline function (Ο•::GridDeformation{T,N,A})(xs::Vararg{Number,N}) where {T,N,A<:AbstractInterpolation} return Ο•.u(xs...) .+ xs end function (Ο•::GridDeformation{T,N})(xs::Vararg{Number,N}) where {T,N} error("call `Ο•i = interpolate(Ο•)` and use `Ο•i` for evaluating the deformation.") end @inline (Ο•::GridDeformation{T,N})(xs::SVector{N}) where {T,N} = Ο•(Tuple(xs)...) # Composition Ο•_old(Ο•_new(x)) function (Ο•_old::GridDeformation{T1,N,A})(Ο•_new::GridDeformation{T2,N}) where {T1,T2,N,A<:AbstractInterpolation} uold, nodes = Ο•_old.u, Ο•_old.nodes if !isa(Ο•_new.u, AbstractInterpolation) Ο•_new.nodes == nodes || error("If nodes are incommensurate, Ο•_new must be interpolating") end ucomp = _compose(uold, Ο•_new.u, nodes) GridDeformation(ucomp, nodes) end (Ο•_old::GridDeformation)(Ο•_new::GridDeformation) = error("Ο•_old must be interpolating") function _compose(uold, unew, nodes) sz = map(length, nodes) x = node(nodes, 1) out = _compose(uold, unew, x, 1) ucomp = similar(uold, typeof(out)) for I in CartesianIndices(sz) ucomp[I] = _compose(uold, unew, node(nodes, I), I) end ucomp end function _compose(uold, unew, x, i) dx = lookup(unew, x, i) dx + vecindex(uold, x+dx) end lookup(u::AbstractInterpolation, x, i) = vecindex(extrapolate(u,Flat()), x) # using extrpolate to resolve BoundsError lookup(u, x, i) = u[i] @inline function node(nodes::NTuple{N}, i::Integer) where N I = CartesianIndices(map(length, nodes))[i] return node(nodes, I) end @inline function node(nodes::NTuple{N}, I::CartesianIndex{N}) where N return SVector(map(getindex, nodes, Tuple(I))) end arraysize(nodes::NTuple) = map(n->Int(maximum(n) - minimum(n) + 1), nodes) struct NodeIterator{K,N} nodes::K iter::CartesianIndices{N} end """ iter = eachnode(Ο•) Create an iterator for visiting all the nodes of `Ο•`. """ eachnode(Ο•::GridDeformation) = eachnode(Ο•.nodes) eachnode(nodes) = NodeIterator(nodes, CartesianIndices(map(length, nodes))) function Base.iterate(ki::NodeIterator) iterate(ki.iter) == nothing && return nothing I, state = iterate(ki.iter) k = node(ki.nodes, I) k, state end function Base.iterate(ki::NodeIterator, state) iterate(ki.iter, state) == nothing && return nothing I, state = iterate(ki.iter, state) k = node(ki.nodes, I) k, state end """ Ο•new = regrid(Ο•, gridsize) Reparametrize the deformation `Ο•` so that it has a grid size `gridsize`. # Example ``` Ο•new = regrid(Ο•, (13,11,7)) ``` for a 3-dimensional deformation `Ο•`. """ function regrid(Ο•::InterpolatingDeformation{T,N}, sz::Dims{N}) where {T,N} nodes_new = map((r,n)->range(first(r), stop=last(r), length=n), Ο•.nodes, sz) u = Array{SVector{N,T},N}(undef, sz) for (i, k) in enumerate(eachnode(nodes_new)) u[i] = Ο•.u(k...) end GridDeformation(u, nodes_new) end regrid(Ο•::GridDeformation{T,N}, sz::Dims{N}) where {T,N} = regrid(interpolate(Ο•), sz) """ `Ο•_c = Ο•_old(Ο•_new)` computes the composition of two deformations, yielding a deformation for which `Ο•_c(x) β‰ˆ Ο•_old(Ο•_new(x))`. `Ο•_old` must be interpolating (see `interpolate(Ο•_old)`). `Ο•_c, g = compose(Ο•_old, Ο•_new)` also yields the gradient `g` of `Ο•_c` with respect to `u_new`. `g[i,j,...]` is the Jacobian matrix at grid position `(i,j,...)`. You can use `_, g = compose(identity, Ο•_new)` if you need the gradient for when `Ο•_old` is equal to the identity transformation. """ function compose(Ο•_old::GridDeformation{T1,N,A}, Ο•_new::GridDeformation{T2,N}) where {T1,T2,N,A<:AbstractInterpolation} u, nodes = Ο•_old.u, Ο•_old.nodes Ο•_new.nodes == nodes || error("Not yet implemented for incommensurate nodes") unew = Ο•_new.u sz = map(length, nodes) x = node(nodes, 1) out = _compose(u, unew, x, 1) ucomp = similar(u, typeof(out)) TG = similar_type(SArray, eltype(out), Size(N, N)) g = Array{TG}(undef, size(u)) gtmp = Vector{typeof(out)}(undef, N) eyeN = TG(1.0I) # eye(TG) for I in CartesianIndices(sz) x = node(nodes, I) dx = lookup(unew, x, I) y = x + dx ucomp[I] = dx + vecindex(u, y) vecgradient!(gtmp, u, y) g[I] = hcat(ntuple(d->gtmp[d], Val(N))...) + eyeN end GridDeformation(ucomp, nodes), g end """ `Ο•si_old` and `Ο•s_new` will generate `Ο•s_c` vector and `g` vector `Ο•si_old` is interpolated ``Ο•s_old`: e.g) `Ο•si_old = map(Interpolations.interpolate!, copy(Ο•s_old))` """ function compose(Ο•si_old::AbstractVector{G1}, Ο•s_new::AbstractVector{G2}) where {G1<:GridDeformation, G2<:GridDeformation} n = length(Ο•s_new) length(Ο•si_old) == n || throw(DimensionMismatch("vectors-of-deformations must have the same length, got $(length(Ο•si_old)) and $n")) Ο•c1, g1 = compose(first(Ο•si_old), first(Ο•s_new)) Ο•s_c = Vector{typeof(Ο•c1)}(undef, n) gs = Vector{typeof(g1)}(undef, n) Ο•s_c[1], gs[1] = Ο•c1, g1 for i in 2:n Ο•s_c[i], gs[i] = compose(Ο•si_old[i], Ο•s_new[i]); end Ο•s_c, gs end function compose(f::Function, Ο•_new::GridDeformation{T,N}) where {T,N} f == identity || error("Only the identity function is supported") Ο•_new, fill(similar_type(SArray, T, Size(N, N))(1.0I), size(Ο•_new.u)) end """ Ο• = tform2deformation(tform, imgaxes, gridsize) Construct a deformation `Ο•` from the affine transform `tform` suitable for warping arrays with axes `imgaxes`. The array of grid points defining `Ο•` has size specified by `gridsize`. The dimensionality of `tform` must match that specified by `arraysize` and `gridsize`. Note it's more accurate to `warp(img, tform)` directly; the main use of this function is to initialize a GridDeformation for later optimization. """ function tform2deformation(tform::AffineMap{M,V}, imgaxes::NTuple{N,<:AbstractUnitRange}, gridsize::NTuple{N,<:Integer}) where {M,V,N} A = deltalinear(tform.linear) u = Array{SVector{N,eltype(M)}}(undef, gridsize...) nodes = map(imgaxes, gridsize) do ax, g range(first(ax), stop=last(ax), length=g) end for I in CartesianIndices(gridsize) x = SVector(map(getindex, nodes, Tuple(I))) u[I] = A*x + tform.translation end GridDeformation(u, nodes) end """ deltalinear(linear) Compute the difference between `linear` and the identity transformation. """ deltalinear(scale::Number) = (scale - 1)*I deltalinear(mtrx::AbstractMatrix) = mtrx - I
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
6349
using CoordinateTransformations, Requires import Interpolations: AbstractExtrapolation export TransformedArray """ A `TransformedArray` is an `AbstractArray` type with an affine coordinate shift: `A[i,j]` evaluates the "parent" array `P` used to construct `A` at a location `x,y` given by `[x, y] = tfm*[i,j]`. It therefore allows you to use lazy-evaluation to perform affine coordinate transformations. ``` A = TransformedArray(etp, tfm) ``` where `etp` is an extrapolation object as defined by the Interpolations package, and `tfm` is an `AffineMap`. """ struct TransformedArray{T,N,E<:AbstractExtrapolation,Tf<:AffineMap} <: AbstractArray{T,N} data::E tform::Tf end TransformedArray(etp::AbstractExtrapolation{T,N}, a::AffineMap) where {T,N} = TransformedArray{T,N,typeof(etp),typeof(a)}(etp, a) function TransformedArray(A::AbstractInterpolation, a::AffineMap) etp = extrapolate(A, NaN) TransformedArray(etp, a) end function TransformedArray(A::AbstractArray, a::AffineMap) itp = interpolate(A, BSpline(Linear())) TransformedArray(itp, a) end Base.size(A::TransformedArray) = size(A.data) function Base.getindex(A::TransformedArray{T,2}, i::Number, j::Number) where T x, y = A.tform([i,j]) #tformfwd(A.tform, i, j) A.data(x, y) end function Base.getindex(A::TransformedArray{T,3}, i::Number, j::Number, k::Number) where T x, y, z = A.tform([i,j,k]) #tformfwd(A.tform, i, j, k) A.data(x, y, z) end Base.similar(A::TransformedArray, ::Type{T}, dims::Dims) where T = Array{T}(dims) """ `transform(A, tfm; origin_dest=center(A), origin_src=center(A)` computes the transformed `A` over its entire domain. By default the transformation is assumed to operate around the center of the input array, and output coordinates are referenced relative to the center of the output. If `A` is a TransformedArray, then the syntax is just `transform(A; origin_dest=center(A), origin_src=center(A))`. This is different from the behavior of `A[:,:]`, which assumes the origin of coordinates to be all-zeros. To obtain behavior equivalent to `getindex`, supply zero-vectors for both of them. Alternatively to make `getindex` behave as `transform`, offset the origin of the transform used to construct `A` by ``` origin_src - tform.linear*origin_dest ``` """ function transform(A::TransformedArray{T,N}; kwargs...) where {T,N} y = A.tform(ones(Int, N)) yt = (y...,)::NTuple{N,eltype(y)} a = A.data(yt...) dest = Array{typeof(a)}(undef, size(A)) transform!(dest, A; kwargs...) dest end transform(A, a::AffineMap; kwargs...) = transform(TransformedArray(A, a); kwargs...) """ `transform!(dest, src, tfm; origin_dest=center(dest), origin_src=center(src))` is like `transform`, but using a pre-allocated output array `dest`. If `src` is already a TransformedArray, use `transform!(dest, src; kwargs...)`. """ function transform!(dest::AbstractArray{S,N}, src::TransformedArray{T,N}; origin_dest = center(dest), origin_src = center(src)) where {S,T,N} tform = src.tform if tform.linear == Matrix{T}(I, N, N) && tform.translation == zeros(N) && size(dest) == size(src) && origin_dest == origin_src copyto!(dest, src) return dest end offset = tform.translation - tform.linear*origin_dest + origin_src _transform!(dest, src, offset) end transform!(dest, src, a::AffineMap; kwargs...) = transform!(dest, TransformedArray(src, a); kwargs...) @require ImageMetadata="bc367c6b-8a6b-528e-b4bd-a4b897500b49" begin transform(A::ImageMetadata.ImageMeta, a::AffineMap; kwargs...) = ImageMetadata.copyproperties(A, transform(ImageMetadata.data(A), a; kwargs...)) transform!(dest, A::ImageMetadata.ImageMeta, a::AffineMap; kwargs...) = ImageMetadata.copyproperties(A, transform!(dest, ImageMetadata.data(A), a; kwargs...)) end # For a FilledExtrapolation, this is designed to (usually) avoid evaluating # the interpolation unless it is in-bounds. This often improves performance. @generated function _transform!(dest::AbstractArray{S,N}, src::TransformedArray{T,N,E}, offset) where {S,T,N,E<:Interpolations.FilledExtrapolation} # Initialize the final column of s "matrix," e.g., s_1_3 = A_1_3 + o_3 # s stands for source-coordinates. The first "column," s_d_1, corresponds # to the actual interpolation position. The later columns simply cache # previous computations. sN = ntuple(i->Expr(:(=), Symbol(string("s_",i,"_$N")), Expr(:call, :+, Symbol(string("A_",i,"_$N")), Symbol(string("o_",i)))), N) quote tform = src.tform data = src.data @nexprs $N d->(o_d = offset[d]) @nexprs $N j->(@nexprs $N i->(A_i_j = tform.linear[i,j])) fill!(dest, data.fillvalue) $(sN...) @nloops($N,i,d->(d>1 ? (1:size(dest,d)) : (imin:imax)), # The pre-expression chooses the range within each column that will be in-bounds d->(d > 2 ? (@nexprs $N e->s_e_{d-1}=A_e_{d-1}+s_e_d) : d == 2 ? begin imin = 1 imax = size(dest,1) @nexprs $N e->((imin, imax) = irange(imin, imax, A_e_1, s_e_2, size(data, e))) @nexprs $N e->(s_e_1=A_e_1*imin+s_e_d) end : nothing), # pre d->(@nexprs $N e->(s_e_d += A_e_d)), # post # Perform the interpolation of the source data @inbounds (@nref $N dest i) = (@ncall $N data d->s_d_1) ) dest end end center(A::AbstractArray) = [(size(A,d)+1)/2 for d = 1:ndims(A)] # Find i such that # imin <= i <= imax # 1 <= coef*i+offset <= upper function irange(imin::Int, imax::Int, coef, offset, upper) thresh = 10^4/typemax(Int) # needed to avoid InexactError for results with abs() bigger than typemax if coef > thresh return max(imin, floor(Int, (1-offset)/coef)), min(imax, ceil(Int, (upper-offset)/coef)) elseif coef < -thresh return max(imin, floor(Int, (upper-offset)/coef)), min(imax, ceil(Int, (1-offset)/coef)) else if 1 <= offset <= upper return imin, imax else return 1, 0 # empty range end end end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2275
""" `Ο•s = tinterpolate(Ο•sindex, tindex, nstack)` uses linear interpolation/extrapolation in time to "fill out" to times `1:nstack` a deformation defined intermediate times `tindex` . Note that `Ο•s[tindex] == Ο•sindex`. """ function tinterpolate(Ο•sindex, tindex, nstack) Ο•s = Vector{eltype(Ο•sindex)}(undef, nstack) # Before the first tindex k = 0 for i in 1:tindex[1]-1 Ο•s[k+=1] = Ο•sindex[1] end # Within tindex for i in 2:length(tindex) Ο•1 = Ο•sindex[i-1] Ο•2 = Ο•sindex[i] Ξ”t = tindex[i] - tindex[i-1] for j = 0:Ξ”t-1 Ξ± = convert(eltype(eltype(Ο•1.u)), j/Ξ”t) Ο•s[k+=1] = GridDeformation((1-Ξ±)*Ο•1.u + Ξ±*Ο•2.u, Ο•2.nodes) end end # After the last tindex for i in tindex[end]:nstack Ο•s[k+=1] = Ο•sindex[end] end return Ο•s end """ Ο•sβ€² = medfilt(Ο•s) Perform temporal median-filtering on a sequence of deformations. This is a form of smoothing that does not "round the corners" on sudden (but persistent) shifts. """ function medfilt(Ο•s::AbstractVector{D}, n) where D<:AbstractDeformation nhalf = n>>1 2nhalf+1 == n || error("filter size must be odd") T = eltype(eltype(D)) v = Array{T}(undef, ndims(D), n) vs = ntuple(d->view(v, d, :), ndims(D)) Ο•1 = copy(Ο•s[1]) Ο•out = Vector{typeof(Ο•1)}(undef, length(Ο•s)) Ο•out[1] = Ο•1 _medfilt!(Ο•out, Ο•s, v, vs) # function barrier due to instability of vs end @noinline function _medfilt!(Ο•out, Ο•s, v, vs::NTuple{N,T}) where {N,T} n = size(v,2) nhalf = n>>1 tmp = Vector{eltype(T)}(undef, N) u1 = Ο•out[1].u for i = 1+nhalf:length(Ο•s)-nhalf u = similar(u1) for I in eachindex(Ο•s[i].u) for j = -nhalf:nhalf utmp = Ο•s[i+j].u[I] for d = 1:N v[d, j+nhalf+1] = utmp[d] end end for d = 1:N tmp[d] = median!(vs[d]) end u[I] = tmp end Ο•out[i] = GridDeformation(u, Ο•s[i].nodes) end # Copy the beginning and end for i = 2:nhalf # we did [1] in medfilt Ο•out[i] = copy(Ο•s[i]) end for i = length(Ο•s)-nhalf+1:length(Ο•s) Ο•out[i] = copy(Ο•s[i]) end Ο•out end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
6615
""" caxs = centeraxes(axs) Return a set of axes centered on zero. Specifically, if `axs[i]` is a range, then `caxs[i]` is a UnitRange of the same length that is approximately symmetric around 0. """ centeraxes(axs) = map(centeraxis, axs) function centeraxis(ax) f, l = first(ax), last(ax) n = l - f + 1 nhalf = (n+1) Γ· 2 return 1-nhalf:n-nhalf end function extract1(u::AbstractArray{V}, N, ssz) where V<:SVector if ndims(u) == N+1 Ο• = GridDeformation(reshape(u, size(u)[1:end-1]), ssz) else Ο• = GridDeformation(u, ssz) end Ο• end extract1(Ο•s::Vector{D}, N, ssz) where {D<:AbstractDeformation} = Ο•s[1] function extracti(u::AbstractArray{V}, i, ssz) where V<:SVector colons = [Colon() for d = 1:ndims(u)-1] GridDeformation(u[colons..., i], ssz) end extracti(Ο•s::Vector{D}, i, _) where {D<:AbstractDeformation} = Ο•s[i] function checkΟ•dims(u::AbstractArray{V}, N, n) where V<:SVector ndims(u) == N+1 || error("u's dimensionality $(ndims(u)) is inconsistent with the number of spatial dimensions $N of the image") if size(u)[end] != n error("Must have one `u` slice per image") end nothing end checkΟ•dims(Ο•s::Vector{D}, N, n) where {D<:AbstractDeformation} = length(Ο•s) == n || error("Must have one `Ο•` per image") # TODO?: do we need to return real values beyond-the-edge for a SubArray? floattype(::Type{T}) where T<:AbstractFloat = T floattype(::Type{<:Integer}) = Float64 floattype(::Type{SVector{N,T}}) where {N,T} = floattype(T) nanvalue(::Type{T}) where T<:Real = convert(promote_type(T, Float32), NaN) nanvalue(::Type{C}) where C<:AbstractGray = Gray(nanvalue(eltype(C))) nanvalue(::Type{C}) where C<:AbstractRGB = (x = nanvalue(eltype(C)); RGB(x, x, x)) to_etp(img) = extrapolate(interpolate(img, BSpline(Linear())), nanvalue(eltype(img))) to_etp(itp::AbstractInterpolation) = extrapolate(itp, convert(promote_type(eltype(itp), Float32), NaN)) to_etp(etp::AbstractExtrapolation) = etp to_etp(img, A::AffineMap) = TransformedArray(to_etp(img), A) getcoefs(Ο•::GridDeformation) = getcoefs(Ο•.u) getcoefs(itp::AbstractInterpolation) = getcoefs(itp.itp) getcoefs(itp::Interpolations.BSplineInterpolation) = itp.coefs getcoefs(u::AbstractArray{<:SVector}) = u # Extensions to Interpolations and StaticArrays @generated function vecindex(A::AbstractArray, x::SVector{N}) where N args = [:(x[$d]) for d = 1:N] meta = Expr(:meta, :inline) quote $meta getindex(A, $(args...)) end end @generated function vecindex(A::AbstractInterpolation, x::SVector{N}) where N args = [:(x[$d]) for d = 1:N] meta = Expr(:meta, :inline) quote $meta A($(args...)) end end @generated function vecgradient!(g, itp::AbstractArray, x::SVector{N}) where N args = [:(x[$d]) for d = 1:N] meta = Expr(:meta, :inline) quote $meta Interpolations.gradient!(g, itp, $(args...)) end end function convert_to_fixed(u::Array{T}, sz=size(u)) where T N = sz[1] convert_to_fixed(SVector{N, T}, u, tail(sz)) end # Unlike the one above, this is type-stable function convert_to_fixed(::Type{SVector{N,T}}, u::AbstractArray{T}, sz=tail(size(u))) where {T,N} reshape(reinterpret(SVector{N,T}, vec(u)), sz) end @generated function copy_ctf!(dest::Array{SVector{N,T}}, src::Array) where {N,T} exvec = [:(src[offset+$d]) for d=1:N] quote for i = 1:length(dest) offset = (i-1)*N dest[i] = SVector($(exvec...)) end dest end end function convert_from_fixed(uf::AbstractArray{SVector{N,T}}, sz=size(uf)) where {N,T} if isbitstype(T) && isa(uf, Array) u = reshape(reinterpret(T, vec(uf)), (N, sz...)) else u = Array{T}(undef, N, sz...) for i = 1:length(uf) for d = 1:N u[d,i] = uf[i][d] end end end u end # # Note this is a bit unsafe as it requires the user to specify C correctly # @generated function Base.convert{R,C,T}(::Type{SMatrix{Tuple{R,C},T}}, v::Vector{SVector{R,T}}) # args = [:(Tuple(v[$d])) for d = 1:C] # :(SMatrix{Tuple{R,C},T}(($(args...),))) # end # Wrapping functions to interface with CoordinateTransfromations instead of AffineTransfroms module tformeye(m::Int) = AffineMap(Matrix{Float64}(I,m,m), zeros(m)) tformtranslate(trans::Vector) = (m = length(trans); AffineMap(Matrix{Float64}(I,m,m), trans)) rotation2(angle) = RotMatrix(angle) function tformrotate(angle) A = RotMatrix(angle) AffineMap(A, zeros(eltype(A),2)) end function rotationparameters(R::Matrix) size(R, 1) == size(R, 2) || error("Matrix must be square") if size(R, 1) == 2 return [atan(-R[1,2],R[1,1])] elseif size(R, 1) == 3 aa = AngleAxis(R) return rotation_angle(aa)*rotation_axis(aa) else error("Rotations in $(size(R, 1)) dimensions not supported") end end function rotation3(axis::Vector{T}, angle) where T n = norm(axis) axisn = n>0 ? axis/n : (tmp = zeros(T,length(axis)); tmp[1] = 1; tmp) AngleAxis(angle, axisn...) end function rotation3(axis::Vector{T}) where T n = norm(axis) axisn = n>0 ? axis/n : (tmp = zeros(typeof(one(T)/1),length(axis)); tmp[1] = 1; tmp) AngleAxis(n, axisn...) end function tformrotate(axis::Vector, angle) if length(axis) == 3 return AffineMap(rotation3(axis, angle), zeros(eltype(axis),3)) else error("Dimensionality ", length(axis), " not supported") end end function tformrotate(x::Vector) if length(x) == 3 return AffineMap(rotation3(x), zeros(eltype(x),3)) else error("Dimensionality ", length(x), " not supported") end end #= # The following assumes uaxis is normalized function _rotation3(uaxis::Vector, angle) if length(uaxis) != 3 error("3d rotations only") end ux, uy, uz = uaxis[1], uaxis[2], uaxis[3] c = cos(angle) s = sin(angle) cm = one(typeof(c)) - c R = [c+ux*ux*cm ux*uy*cm-uz*s ux*uz*cm+uy*s; uy*ux*cm+uz*s c+uy*uy*cm uy*uz*cm-ux*s; uz*ux*cm-uy*s uz*uy*cm+ux*s c+uz*uz*cm] end function rotation3{T}(axis::Vector{T}, angle) n = norm(axis) axisn = n>0 ? axis/n : (tmp = zeros(T,length(axis)); tmp[1] = 1) _rotation3(axisn, angle) end # Angle/axis representation where the angle is the norm of the vector (so axis is not normalized) function rotation3{T}(axis::Vector{T}) n = norm(axis) axisn = n>0 ? axis/n : (tmp = zeros(typeof(one(T)/1),length(axis)); tmp[1] = 1; tmp) _rotation3(axisn, n) end =#
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2267
""" img = nodegrid(T, nodes) img = nodegrid(nodes) img = nodegrid([T], Ο•) Returns an image `img` which has value 1 at points that are "on the nodes." If `nodes`/`Ο•` is two-dimensional, the image will consist of grid lines; for three-dimensional inputs, the image will have grid planes. The meaning of "on the nodes" is that `x[d] == nodes[d][i]` for some dimension `d` and node index `i`. An exception is made for the edge values, which are brought inward by one pixel to prevent complete loss under subpixel deformations. Optionally specify the element type `T` of `img`. See also [`warpgrid`](@ref). """ function nodegrid(::Type{T}, nodes::NTuple{N,AbstractRange}) where {T,N} @assert all(r->first(r)==1, nodes) inds = map(r->Base.OneTo(ceil(Int, last(r))), nodes) img = Array{T}(undef, map(length, inds)) fill!(img, zero(T)) for idim = 1:N indexes = Any[inds...] indexes[idim] = map(x->clamp(round(Int, x), first(inds[idim])+1, last(inds[idim])-1), nodes[idim]) img[indexes...] .= one(T) end img end nodegrid(::Type{T}, Ο•::GridDeformation) where {T} = nodegrid(T, Ο•.nodes) nodegrid(arg) = nodegrid(Bool, arg) """ img = warpgrid(Ο•; [scale=1, showidentity=false]) Returns an image `img` that permits visualization of the deformation `Ο•`. The output is a warped rectangular grid with nodes centered on the control points as specified by the nodes of `Ο•`. If `Ο•` is a two-dimensional deformation, the image will consist of grid lines; for a three-dimensional deformation, the image will have grid planes. `scale` multiplies `Ο•.u`, effectively making the deformation stronger (for `scale > 1`). This can be useful if you are trying to visualize subtle changes. If `showidentity` is `true`, an RGB image is returned that has the warped grid in magenta and the original grid in green. See also [`nodegrid`](@ref). """ function warpgrid(Ο•; scale=1, showidentity::Bool=false) img = nodegrid(Ο•) if scale != 1 Ο• = GridDeformation(scale*Ο•.u, Ο•.nodes) end wimg = warp(img, Ο•) if showidentity n = ndims(img)+1 return reshape(reinterpret(RGB{Float32}, permutedims(cat(wimg, img, wimg, dims=n), (n,1:ndims(img)...))),(size(img)...,)) end wimg end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
5770
""" `wimg = warp(img, Ο•)` warps the array `img` according to the deformation `Ο•`. """ function warp(img::AbstractArray, Ο•::AbstractDeformation) wimg = WarpedArray(img, Ο•) dest = similar(img, warp_type(img)) warp!(dest, wimg) end warp_type(img::AbstractArray{T}) where {T<:AbstractFloat} = T warp_type(img::AbstractArray{T}) where {T<:Number} = Float32 warp_type(img::AbstractArray{C}) where {C<:Colorant} = warp_type(img, eltype(eltype(C))) warp_type(img::AbstractArray{C}, ::Type{T}) where {C<:Colorant, T<:AbstractFloat} = C warp_type(img::AbstractArray{C}, ::Type{T}) where {C<:Colorant, T} = base_colorant_type(C){Float32} """ `warp!(dest, src::WarpedArray)` instantiates a `WarpedArray` in the output `dest`. """ function warp!(dest::AbstractArray{T,N}, src::WarpedArray) where {T,N} axes(dest) == axes(src) || throw(DimensionMismatch("dest must have the same axes as src")) destiter = CartesianIndices(axes(dest)) I, deststate = iterate(destiter) for ux in eachvalue(src.Ο•.u) dest[I] = src.data((Tuple(I) .+ ux)...) if deststate == last(destiter) break end I, deststate = iterate(destiter, deststate) end return dest end """ `warp!(dest, img, Ο•)` warps `img` using the deformation `Ο•`. The result is stored in `dest`. """ function warp!(dest::AbstractArray, img::AbstractArray, Ο•::AbstractDeformation) wimg = WarpedArray(to_etp(img), Ο•) warp!(dest, wimg) end """ `warp!(dest, img, tform, Ο•)` warps `img` using a combination of the affine transformation `tform` followed by deformation with `Ο•`. The result is stored in `dest`. """ function warp!(dest::AbstractArray, img::AbstractArray, A::AffineMap, Ο•::AbstractDeformation) wimg = WarpedArray(to_etp(img, A), Ο•) warp!(dest, wimg) end """ `warp!(T, io, img, Ο•s; [nworkers=1])` writes warped images to disk. `io` is an `IO` object or HDF5/JLD2 dataset (the latter must be pre-allocated using `d_create` to be of the proper size). `img` is an image sequence, and `Ο•s` is a vector of deformations, one per image in `img`. If `nworkers` is greater than one, it will spawn additional processes to perform the deformation. An alternative syntax is `warp!(T, io, img, uarray; [nworkers=1])`, where `uarray` is an array of `u` values with `size(uarray)[end] == nimages(img)`. """ function warp!(::Type{T}, dest::Union{IO,HDF5.Dataset,JLD2.JLDFile}, img, Ο•s; nworkers=1) where T n = nimages(img) saxs = indices_spatial(img) ssz = map(length, saxs) if n == 1 Ο• = extract1(Ο•s, sdims(img), saxs) destarray = Array{T}(undef, ssz) warp!(destarray, img, Ο•) warp_write(dest, destarray) return nothing end checkΟ•dims(Ο•s, sdims(img), n) if nworkers > 1 return _warp!(T, dest, img, Ο•s, nworkers) end destarray = Array{T}(undef, ssz) @showprogress 1 "Stacks:" for i = 1:n Ο• = extracti(Ο•s, i, saxs) warp!(destarray, view(img, timeaxis(img)(i)), Ο•) warp_write(dest, destarray, i) end nothing end warp!(::Type{T}, dest::Union{IO,HDF5.Dataset,JLD2.JLDFile}, img, u::AbstractArray{R}; kwargs...) where {T,R<:Real} = warp!(T, dest, img, Array(convert_to_fixed(u)); kwargs...) warp!(dest::Union{HDF5.Dataset,JLD2.JLDFile}, img, u; nworkers=1) = warp!(eltype(dest), dest, img, u; nworkers=nworkers) function _warp!(::Type{T}, dest, img, Ο•s, nworkers) where T n = nimages(img) saxs = indices_spatial(img) ssz = map(length, saxs) wpids = addprocs(nworkers) simg = Vector{Any}() swarped = Vector{Any}() rrs = Vector{RemoteChannel}() mydir = splitdir(@__FILE__)[1] pkgbase = String(chop(mydir,tail=4)) for p in wpids remotecall_fetch(Main.eval, p, :(using Pkg)) remotecall_fetch(Main.eval, p, :(Pkg.activate($pkgbase))) remotecall_fetch(Main.eval, p, :(push!(LOAD_PATH, $mydir))) remotecall_fetch(Main.eval, p, :(using RegisterDeformation)) push!(simg, SharedArray{eltype(img)}(ssz, pids=[myid(),p])) push!(swarped, SharedArray{T}(ssz, pids=[myid(),p])) end nextidx = 0 getnextidx() = nextidx += 1 writing_mutex = RemoteChannel() prog = Progress(n, 1, "Stacks:") @sync begin for i = 1:nworkers p = wpids[i] src = simg[i] warped = swarped[i] @async begin while (idx = getnextidx()) <= n Ο• = extracti(Ο•s, idx, saxs) copyto!(src, view(img, timeaxis(img)(idx))) remotecall_fetch(warp!, p, warped, src, Ο•) put!(writing_mutex, true) warp_write(dest, warped, idx) update!(prog, idx) take!(writing_mutex) end end end end finish!(prog) nothing end warp_write(io::IO, destarray) = write(io, destarray) function warp_write(io::IO, destarray, i) offset = (i-1)*length(destarray)*sizeof(eltype(destarray)) seek(io, offset) write(io, destarray) end function warp_write(dest, destarray, i) colons = [Colon() for d = 1:ndims(destarray)] dest[colons..., i] = destarray end """ `Atrans = translate(A, displacement)` shifts `A` by an amount specified by `displacement`. Specifically, in simple cases `Atrans[i, j, ...] = A[i+displacement[1], j+displacement[2], ...]`. More generally, `displacement` is applied only to the spatial coordinates of `A`. `NaN` is filled in for any missing pixels. """ function translate(A::AbstractArray, displacement::DimsLike) disp = zeros(Int, ndims(A)) disp[[coords_spatial(A)...]] = displacement indx = UnitRange{Int}[ axes(A, i) .+ disp[i] for i = 1:ndims(A) ] get(A, indx, NaN) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1667
### WarpedArray """ A `WarpedArray` `W` is an AbstractArray for which `W[x] = A[Ο•(x)]` for some parent array `A` and some deformation `Ο•`. The object is created lazily, meaning that computation of the displaced values occurs only when you ask for them explicitly. Create a `WarpedArray` like this: ``` W = WarpedArray(A, Ο•) ``` where - The first argument `A` is an `AbstractExtrapolation` that can be evaluated anywhere. See the Interpolations package. - Ο• is an `AbstractDeformation` """ struct WarpedArray{T,N,A<:Extrapolatable,D<:AbstractDeformation} <: AbstractArray{T,N} data::A Ο•::D end # User already supplied an interpolatable Ο• function WarpedArray(data::Extrapolatable{T,N}, Ο•::GridDeformation{S,N,A}) where {T,N,S,A<:AbstractInterpolation} WarpedArray{T,N,typeof(data),typeof(Ο•)}(data, Ο•) end # Create an interpolatable Ο• function WarpedArray(data::Extrapolatable{T,N}, Ο•::GridDeformation) where {T,N} itp = scale(interpolate(Ο•.u, BSpline(Quadratic(Flat(OnCell())))), Ο•.nodes...) Ο•β€² = GridDeformation(itp, Ο•.nodes) WarpedArray{T,N,typeof(data),typeof(Ο•β€²)}(data, Ο•β€²) end WarpedArray(data, Ο•::GridDeformation) = WarpedArray(to_etp(data), Ο•) Base.size(A::WarpedArray) = size(A.data) Base.size(A::WarpedArray, i::Integer) = size(A.data, i) Base.axes(A::WarpedArray) = axes(A.data) Base.axes(A::WarpedArray, i::Integer) = axes(A.data, i) @inline function Base.getindex(W::WarpedArray{T,N}, I::Vararg{Number,N}) where {T,N} Ο•x = W.Ο•(I...) return W.data(Ο•x...) end ImageAxes.getindex!(dest, W::WarpedArray{T,N}, coords::Vararg{Any,N}) where {T,N} = Base._unsafe_getindex!(dest, W, coords...)
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
12326
module RegisterMismatch import Base: copy, eltype, isnan, ndims using ImageCore using ..RFFT, FFTW using ..RegisterCore, PaddedViews, MappedArrays using Printf using Reexport @reexport using ..RegisterMismatchCommon import ..RegisterMismatchCommon: mismatch0, mismatch, mismatch_apertures export CMStorage, fillfixed!, mismatch0, mismatch, mismatch!, mismatch_apertures, mismatch_apertures! """ The major types and functions exported are: - `mismatch` and `mismatch!`: compute the mismatch between two images - `mismatch_apertures` and `mismatch_apertures!`: compute apertured mismatch between two images - `mismatch0`: simple direct mismatch calculation with no shift - `nanpad`: pad the smaller image with NaNs - `highpass`: highpass filter an image - `correctbias!`: replace corrupted mismatch data (due to camera bias inhomogeneity) with imputed data - `truncatenoise!`: threshold mismatch computation to prevent problems from roundoff - `aperture_grid`: create a regular grid of apertures - `allocate_mmarrays`: create storage for output of `mismatch_apertures!` - `CMStorage`: a type that facilitates re-use of intermediate storage during registration computations """ RegisterMismatch FFTW.set_num_threads(min(Sys.CPU_THREADS, 8)) set_FFTPROD([2, 3]) mutable struct NanCorrFFTs{T<:AbstractFloat,N,RCType<:RCpair{T,N}} I0::RCType I1::RCType I2::RCType end copy(x::NanCorrFFTs) = NanCorrFFTs(copy(x.I0), copy(x.I1), copy(x.I2)) """ CMStorage{T}(undef, aperture_width, maxshift; flags=FFTW.ESTIMATE, timelimit=Inf, display=true) Prepare for FFT-based mismatch computations over domains of size `aperture_width`, computing the mismatch up to shifts of size `maxshift`. The keyword arguments allow you to control the planning process for the FFTs. """ mutable struct CMStorage{ T<:AbstractFloat,N,RCType<:RCpair{T,N},FFT<:Function,IFFT<:Function } aperture_width::Vector{Float64} maxshift::Vector{Int} getindices::Vector{UnitRange{Int}} # indices for pulling padded data, in source-coordinates padded::Array{T,N} fixed::NanCorrFFTs{T,N,RCType} moving::NanCorrFFTs{T,N,RCType} buf1::RCType buf2::RCType # the next two store the result of calling plan_fft! and plan_ifft! fftfunc!::FFT ifftfunc!::IFFT shiftindices::Vector{Vector{Int}} # indices for performing fftshift & snipping from -maxshift:maxshift end function CMStorage{T,N}( ::UndefInitializer, aperture_width::NTuple{N,<:Real}, maxshift::Dims{N}; flags=FFTW.ESTIMATE, timelimit=Inf, display=true, ) where {T,N} blocksize = map(x -> ceil(Int, x), aperture_width) padsz = padsize(blocksize, maxshift) padded = Array{T}(undef, padsz) getindices = padranges(blocksize, maxshift) maxshiftv = [maxshift...] region = findall(maxshiftv .> 0) fixed = NanCorrFFTs( RCpair{T}(undef, padsz, region), RCpair{T}(undef, padsz, region), RCpair{T}(undef, padsz, region), ) moving = NanCorrFFTs( RCpair{T}(undef, padsz, region), RCpair{T}(undef, padsz, region), RCpair{T}(undef, padsz, region), ) buf1 = RCpair{T}(undef, padsz, region) buf2 = RCpair{T}(undef, padsz, region) tcalib = 0 if display && flags != FFTW.ESTIMATE print("Planning FFTs (maximum $timelimit seconds)...") flush(stdout) tcalib = time() end fftfunc = plan_rfft!(fixed.I0; flags=flags, timelimit=timelimit / 2) ifftfunc = plan_irfft!(fixed.I0; flags=flags, timelimit=timelimit / 2) if display && flags != FFTW.ESTIMATE dt = time() - tcalib @printf("done (%.2f seconds)\n", dt) end shiftindices = Vector{Int}[ [size(padded, i) .+ ((-maxshift[i] + 1):0); 1:(maxshift[i] + 1)] for i in 1:length(maxshift) ] return CMStorage{T,N,typeof(buf1),typeof(fftfunc),typeof(ifftfunc)}( Float64[aperture_width...], maxshiftv, getindices, padded, fixed, moving, buf1, buf2, fftfunc, ifftfunc, shiftindices, ) end function CMStorage{T}( ::UndefInitializer, aperture_width::NTuple{N,<:Real}, maxshift::Dims{N}; kwargs... ) where {T<:Real,N} return CMStorage{T,N}(undef, aperture_width, maxshift; kwargs...) end eltype(cms::CMStorage{T,N}) where {T,N} = T ndims(cms::CMStorage{T,N}) where {T,N} = N """ mm = mismatch([T], fixed, moving, maxshift; normalization=:intensity) Compute the mismatch between `fixed` and `moving` as a function of translations (shifts) up to size `maxshift`. Optionally specify the element-type of the mismatch arrays (default `Float32` for Integer- or FixedPoint-valued images) and the normalization scheme (`:intensity` or `:pixels`). `fixed` and `moving` must have the same size; you can pad with `NaN`s as needed. See `nanpad`. """ function mismatch( ::Type{T}, fixed::AbstractArray, moving::AbstractArray, maxshift::DimsLike; normalization=:intensity, ) where {T<:Real} msz = 2 .* maxshift .+ 1 mm = MismatchArray(T, msz...) cms = CMStorage{T}(undef, size(fixed), maxshift) fillfixed!(cms, fixed) erng = shiftrange.((cms.getindices...,), first.(axes(fixed)) .- 1) # expanded rng mpad = PaddedView(convert(T, NaN), of_eltype(T, moving), erng) mismatch!(mm, cms, mpad; normalization=normalization) return mm end """ `mismatch!(mm, cms, moving; [normalization=:intensity])` computes the mismatch as a function of shift, storing the result in `mm`. The `fixed` image has been prepared in `cms`, a `CMStorage` object. """ function mismatch!( mm::MismatchArray, cms::CMStorage, moving::AbstractArray; normalization=:intensity ) # Pad the moving snippet using any available data, including # regions that might be in the parent Array but are not present # within the boundaries of the SubArray. Use NaN only for pixels # truly lacking data. checksize_maxshift(mm, cms.maxshift) copyto!(cms.padded, CartesianIndices(cms.padded), moving, CartesianIndices(moving)) fftnan!(cms.moving, cms.padded, cms.fftfunc!) # Compute the mismatch f0 = complex(cms.fixed.I0) f1 = complex(cms.fixed.I1) f2 = complex(cms.fixed.I2) m0 = complex(cms.moving.I0) m1 = complex(cms.moving.I1) m2 = complex(cms.moving.I2) tnum = complex(cms.buf1) tdenom = complex(cms.buf2) if normalization == :intensity @inbounds Threads.@threads for i in 1:length(tnum) c = 2 * conj(f1[i]) * m1[i] q = conj(f2[i]) * m0[i] + conj(f0[i]) * m2[i] tdenom[i] = q tnum[i] = q - c end elseif normalization == :pixels @inbounds Threads.@threads for i in 1:length(tnum) f0i, m0i = f0[i], m0[i] tdenom[i] = conj(f0i) * m0i tnum[i] = conj(f2[i]) * m0i - 2 * conj(f1[i]) * m1[i] + conj(f0i) * m2[i] end else error("normalization $normalization not recognized") end cms.ifftfunc!(cms.buf1) cms.ifftfunc!(cms.buf2) copyto!( mm, ( view(real(cms.buf1), cms.shiftindices...), view(real(cms.buf2), cms.shiftindices...), ), ) return mm end """ `mms = mismatch_apertures([T], fixed, moving, gridsize, maxshift; [normalization=:pixels], [flags=FFTW.MEASURE], kwargs...)` computes the mismatch between `fixed` and `moving` over a regularly-spaced grid of aperture centers, effectively breaking the images up into chunks. The maximum-allowed shift in any aperture is `maxshift`. `mms = mismatch_apertures([T], fixed, moving, aperture_centers, aperture_width, maxshift; kwargs...)` computes the mismatch between `fixed` and `moving` over a list of apertures of size `aperture_width` at positions defined by `aperture_centers`. `fixed` and `moving` must have the same size; you can pad with `NaN`s as needed to ensure this. You can optionally specify the real-valued element type mm; it defaults to the element type of `fixed` and `moving` or, for Integer- or FixedPoint-valued images, `Float32`. On output, `mms` will be an Array-of-MismatchArrays, with the outer array having the same "grid" shape as `aperture_centers`. The centers can in general be provided as an vector-of-tuples, vector-of-vectors, or a matrix with each point in a column. If your centers are arranged in a rectangular grid, you can use an `N`-dimensional array-of-tuples (or array-of-vectors) or an `N+1`-dimensional array with the center positions specified along the first dimension. See `aperture_grid`. """ function mismatch_apertures( ::Type{T}, fixed::AbstractArray, moving::AbstractArray, aperture_centers::AbstractArray, aperture_width::WidthLike, maxshift::DimsLike; normalization=:pixels, flags=FFTW.MEASURE, kwargs..., ) where {T} nd = sdims(fixed) (length(aperture_width) == nd && length(maxshift) == nd) || error("Dimensionality mismatch") mms = allocate_mmarrays(T, aperture_centers, maxshift) cms = CMStorage{T}(undef, aperture_width, maxshift; flags=flags, kwargs...) return mismatch_apertures!( mms, fixed, moving, aperture_centers, cms; normalization=normalization ) end """ `mismatch_apertures!(mms, fixed, moving, aperture_centers, cms; [normalization=:pixels])` computes the mismatch between `fixed` and `moving` over a list of apertures at positions defined by `aperture_centers`. The parameters and working storage are contained in `cms`, a `CMStorage` object. The results are stored in `mms`, an Array-of-MismatchArrays which must have length equal to the number of aperture centers. """ function mismatch_apertures!( mms, fixed, moving, aperture_centers, cms::CMStorage{T}; normalization=:pixels ) where {T} N = ndims(cms) fillvalue = convert(T, NaN) getinds = (cms.getindices...,)::NTuple{ndims(fixed),UnitRange{Int}} fixedT, movingT = of_eltype(T, fixed), of_eltype(T, moving) for (mm, center) in zip(mms, each_point(aperture_centers)) rng = aperture_range(center, cms.aperture_width) fsnip = PaddedView(fillvalue, fixedT, rng) erng = shiftrange.(getinds, first.(rng) .- 1) # expanded rng msnip = PaddedView(fillvalue, movingT, erng) # Perform the calculation fillfixed!(cms, fsnip) mismatch!(mm, cms, msnip; normalization=normalization) end return mms end # Calculate the components needed to "nancorrelate" function fftnan!( out::NanCorrFFTs{T}, A::AbstractArray{T}, fftfunc!::Function ) where {T<:Real} I0 = real(out.I0) I1 = real(out.I1) I2 = real(out.I2) _fftnan!(parent(I0), parent(I1), parent(I2), A) fftfunc!(out.I0) fftfunc!(out.I1) fftfunc!(out.I2) return out end function _fftnan!(I0, I1, I2, A::AbstractArray{T}) where {T<:Real} @inbounds Threads.@threads for i in CartesianIndices(size(A)) a = A[i] f = !isnan(a) I0[i] = f af = f ? a : zero(T) I1[i] = af I2[i] = af * af end end function fillfixed!(cms::CMStorage{T}, fixed::AbstractArray) where {T} fill!(cms.padded, NaN) pinds = CartesianIndices( ntuple(d -> (1:size(fixed, d)) .+ cms.maxshift[d], ndims(fixed)) ) copyto!(cms.padded, pinds, fixed, CartesianIndices(fixed)) return fftnan!(cms.fixed, cms.padded, cms.fftfunc!) end #### Utilities Base.isnan(A::Array{Complex{T}}) where {T} = isnan(real(A)) | isnan(imag(A)) function sumsq_finite(A) s = 0.0 for a in A if isfinite(a) s += a * a end end if s == 0 error("No finite values available") end return s end ### Deprecations function CMStorage{T}( ::UndefInitializer, aperture_width::WidthLike, maxshift::WidthLike; kwargs... ) where {T<:Real} Base.depwarn( "CMStorage with aperture_width::$(typeof(aperture_width)) and maxshift::$(typeof(maxshift)) is deprecated, use tuples instead", :CMStorage, ) (N = length(aperture_width)) == length(maxshift) || error("Dimensionality mismatch") return CMStorage{T,N}(undef, (aperture_width...,), (maxshift...,); kwargs...) end @deprecate CMStorage(::Type{T}, aperture_width, maxshift; kwargs...) where {T} CMStorage{T}( undef, aperture_width, maxshift; kwargs... ) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
17531
module RegisterMismatchCommon using ..RegisterCore using ..CenterIndexedArrays, ImageCore export correctbias!, nanpad, mismatch0, aperture_grid, allocate_mmarrays, default_aperture_width, truncatenoise! export DimsLike, WidthLike, each_point, aperture_range, assertsamesize, tovec, mismatch, padsize, set_FFTPROD export padranges, shiftrange, checksize_maxshift, register_translate const DimsLike = Union{AbstractVector{Int},Dims} # try to avoid these and just use Dims tuples for sizes const WidthLike = Union{AbstractVector,Tuple} FFTPROD = [2, 3] set_FFTPROD(v) = global FFTPROD = v function mismatch( fixed::AbstractArray{T}, moving::AbstractArray{T}, maxshift::DimsLike; normalization=:intensity, ) where {T<:AbstractFloat} return mismatch(T, fixed, moving, maxshift; normalization=normalization) end function mismatch( fixed::AbstractArray, moving::AbstractArray, maxshift::DimsLike; normalization=:intensity, ) return mismatch(Float32, fixed, moving, maxshift; normalization=normalization) end function mismatch_apertures( fixed::AbstractArray{T}, moving::AbstractArray{T}, args...; kwargs... ) where {T<:AbstractFloat} return mismatch_apertures(T, fixed, moving, args...; kwargs...) end function mismatch_apertures(fixed::AbstractArray, moving::AbstractArray, args...; kwargs...) return mismatch_apertures(Float32, fixed, moving, args...; kwargs...) end function mismatch_apertures( ::Type{T}, fixed::AbstractArray, moving::AbstractArray, gridsize::DimsLike, maxshift::DimsLike; kwargs..., ) where {T} cs = coords_spatial(fixed) aperture_centers = aperture_grid(map(d -> size(fixed, d), cs), gridsize) aperture_width = default_aperture_width(fixed, gridsize) return mismatch_apertures( T, fixed, moving, aperture_centers, aperture_width, maxshift; kwargs... ) end """ `correctbias!(mm::MismatchArray)` replaces "suspect" mismatch data with imputed data. If each pixel in your camera has a different bias, then matching that bias becomes an incentive to avoid shifts. Likewise, CMOS cameras tend to have correlated row/column noise. These two factors combine to imply that `mm[i,j,...]` is unreliable whenever `i` or `j` is zero. Data are imputed by averaging the adjacent non-suspect values. This function works in-place, overwriting the original `mm`. """ function correctbias!(mm::MismatchArray{ND,N}, w=correctbias_weight(mm)) where {ND,N} T = eltype(ND) mxshift = maxshift(mm) Imax = CartesianIndex(mxshift) Imin = CartesianIndex(map(x -> -x, mxshift)::NTuple{N,Int}) I1 = CartesianIndex(ntuple(d -> d > 2 ? 0 : 1, N)::NTuple{N,Int}) # only first 2 dims for I in eachindex(mm) if w[I] == 0 mms = NumDenom{T}(0, 0) ws = zero(T) strt = max(Imin, I - I1) stop = min(Imax, I + I1) for J in CartesianIndices(ntuple(d -> strt[d]:stop[d], N)) wJ = w[J] if wJ != 0 mms += wJ * mm[J] ws += wJ end end mm[I] = mms / ws end end return mm end "`correctbias!(mms)` runs `correctbias!` on each element of an array-of-MismatchArrays." function correctbias!(mms::AbstractArray{M}) where {M<:MismatchArray} for mm in mms correctbias!(mm) end return mms end function correctbias_weight(mm::MismatchArray{ND,N}) where {ND,N} T = eltype(ND) w = CenterIndexedArray(ones(T, size(mm))) for I in eachindex(mm) anyzero = false for d in 1:min(N, 2) # only first 2 dims anyzero |= I[d] == 0 end if anyzero w[I] = 0 end end return w end """ `fixedpad, movingpad = nanpad(fixed, moving)` will pad `fixed` and/or `moving` with NaN as needed to ensure that `fixedpad` and `movingpad` have the same size. """ function nanpad(fixed, moving) ndims(fixed) == ndims(moving) || error("fixed and moving must have the same dimensionality") if size(fixed) == size(moving) return fixed, moving end rng = map(d -> 1:max(size(fixed, d), size(moving, d)), 1:ndims(fixed)) T = promote_type(eltype(fixed), eltype(moving)) return get(fixed, rng, nanval(T)), get(moving, rng, nanval(T)) end nanval(::Type{T}) where {T<:AbstractFloat} = convert(T, NaN) nanval(::Type{T}) where {T} = convert(Float32, NaN) """ `mm0 = mismatch0(fixed, moving, [normalization])` computes the "as-is" mismatch between `fixed` and `moving`, without any shift. `normalization` may be either `:intensity` (the default) or `:pixels`. """ function mismatch0( fixed::AbstractArray{Tf,N}, moving::AbstractArray{Tm,N}; normalization=:intensity ) where {Tf,Tm,N} size(fixed) == size(moving) || throw( DimensionMismatch( "Size $(size(fixed)) of fixed is not equal to size $(size(moving)) of moving", ), ) return _mismatch0( zero(Float64), zero(Float64), fixed, moving; normalization=normalization ) end function _mismatch0( num::T, denom::T, fixed::AbstractArray{Tf,N}, moving::AbstractArray{Tm,N}; normalization=:intensity, ) where {T,Tf,Tm,N} if normalization == :intensity for i in eachindex(fixed, moving) vf = T(fixed[i]) vm = T(moving[i]) if isfinite(vf) && isfinite(vm) num += (vf - vm)^2 denom += vf^2 + vm^2 end end elseif normalization == :pixels for i in eachindex(fixed, moving) vf = T(fixed[i]) vm = T(moving[i]) if isfinite(vf) && isfinite(vm) num += (vf - vm)^2 denom += 1 end end else error("Normalization $normalization not recognized") end return NumDenom(num, denom) end """ `mm0 = mismatch0(mms)` computes the "as-is" mismatch between `fixed` and `moving`, without any shift. The mismatch is represented in `mms` as an aperture-wise Arrays-of-MismatchArrays. """ function mismatch0(mms::AbstractArray{M}) where {M<:MismatchArray} mm0 = eltype(M)(0, 0) cr = eachindex(first(mms)) z = first(cr) + last(cr) # all-zeros CartesianIndex for mm in mms mm0 += mm[z] end return mm0 end """ `ag = aperture_grid(ssize, gridsize)` constructs a uniformly-spaced grid of aperture centers. The grid has size `gridsize`, and is constructed for an image of spatial size `ssize`. Along each dimension the first and last elements are at the image corners. """ function aperture_grid(ssize::Dims{N}, gridsize) where {N} if length(gridsize) != N if length(gridsize) == N - 1 @info( "ssize and gridsize disagree; possible fix is to use a :time axis (AxisArrays) for the image" ) end error("ssize and gridsize must have the same length, got $ssize and $gridsize") end grid = Array{NTuple{N,Float64},N}(undef, (gridsize...,)) centers = map( i -> if gridsize[i] > 1 collect(range(1; stop=ssize[i], length=gridsize[i])) else [(ssize[i] + 1) / 2] end, 1:N, ) for I in CartesianIndices(size(grid)) grid[I] = ntuple(i -> centers[i][I[i]], N) end return grid end """ `mms = allocate_mmarrays(T, gridsize, maxshift)` allocates storage for aperture-wise mismatch computation. `mms` will be an Array-of-MismatchArrays with element type `NumDenom{T}` and half-size `maxshift`. `mms` will be an array of size `gridsize`. This syntax is recommended when your apertures are centered at points of a grid. `mms = allocate_mmarrays(T, aperture_centers, maxshift)` returns `mms` with a shape that matches that of `aperture_centers`. The centers can in general be provided as an vector-of-tuples, vector-of-vectors, or a matrix with each point in a column. If your centers are arranged in a rectangular grid, you can use an `N`-dimensional array-of-tuples (or array-of-vectors) or an `N+1`-dimensional array with the center positions specified along the first dimension. (But you may find the `gridsize` syntax to be simpler.) """ function allocate_mmarrays( ::Type{T}, aperture_centers::AbstractArray{C}, maxshift ) where {T,C<:Union{AbstractVector,Tuple}} isempty(aperture_centers) && error("aperture_centers is empty") N = length(first(aperture_centers)) sz = map(x -> 2 * x + 1, maxshift) mm = MismatchArray(T, sz...) mms = Array{typeof(mm)}(undef, size(aperture_centers)) f = true for i in eachindex(mms) if f mms[i] = mm f = false else mms[i] = MismatchArray(T, sz...) end end return mms end function allocate_mmarrays( ::Type{T}, aperture_centers::AbstractArray{R}, maxshift ) where {T,R<:Real} N = ndims(aperture_centers) - 1 mms = Array{MismatchArray{T,N}}(undef, size(aperture_centers)[2:end]) sz = map(x -> 2 * x + 1, maxshift) for i in eachindex(mms) mms[i] = MismatchArray(T, sz...) end return mms end function allocate_mmarrays(::Type{T}, gridsize::NTuple{N,Int}, maxshift) where {T<:Real,N} mms = Array{MismatchArray{NumDenom{T},N}}(undef, gridsize) sz = map(x -> 2 * x + 1, maxshift) for i in eachindex(mms) mms[i] = MismatchArray(T, sz...) end return mms end struct ContainerIterator{C} data::C end Base.iterate(iter::ContainerIterator) = iterate(iter.data) Base.iterate(iter::ContainerIterator, state) = iterate(iter.data, state) struct FirstDimIterator{A<:AbstractArray,R<:CartesianIndices} data::A rng::R function FirstDimIterator{A,R}(data::A) where {A,R} return new{A,R}(data, CartesianIndices(Base.tail(size(data)))) end end function FirstDimIterator(A::AbstractArray) return FirstDimIterator{typeof(A),typeof(CartesianIndices(Base.tail(size(A))))}(A) end function Base.iterate(iter::FirstDimIterator) isempty(iter.rng) && return nothing index, state = iterate(iter.rng) return iter.data[:, index], state end function Base.iterate(iter::FirstDimIterator, state) state == last(iter.rng) && return nothing index, state = iterate(iter.rng, state) return iter.data[:, index], state end """ `iter = each_point(points)` yields an iterator `iter` over all the points in `points`. `points` may be represented as an AbstractArray-of-tuples or -AbstractVectors, or may be an `AbstractArray` where each point is represented along the first dimension (e.g., columns of a matrix). """ function each_point( aperture_centers::AbstractArray{C} ) where {C<:Union{AbstractVector,Tuple}} return ContainerIterator(aperture_centers) end function each_point(aperture_centers::AbstractArray{R}) where {R<:Real} return FirstDimIterator(aperture_centers) end """ `rng = aperture_range(center, width)` returns a tuple of `UnitRange{Int}`s that, for dimension `d`, is centered on `center[d]` and has width `width[d]`. """ function aperture_range(center, width) length(center) == length(width) || error("center and width must have the same length") return ntuple( d -> leftedge(center[d], width[d]):rightedge(center[d], width[d]), length(center) ) end """ `aperturesize = default_aperture_width(img, gridsize, [overlap])` calculates the aperture width for a regularly-spaced grid of aperture centers with size `gridsize`. Apertures that are adjacent along dimension `d` may overlap by a number pixels specified by `overlap[d]`; the default value is 0. For non-negative `overlap`, the collection of apertures will yield full coverage of the image. """ function default_aperture_width( img, gridsize::DimsLike, overlap::DimsLike=zeros(Int, sdims(img)) ) sc = coords_spatial(img) length(sc) == length(gridsize) == length(overlap) || error( "gridsize and overlap must have length equal to the number of spatial dimensions in img", ) for i in 1:length(sc) if gridsize[i] > size(img, sc[i]) error( "gridsize $gridsize is too large, given the size $(size(img)[sc]) of the image", ) end end gsz1 = max.(1, [gridsize...] .- 1) gflag = [gridsize...] .> 1 return tuple( (([map(d -> size(img, d), sc)...] - gflag) ./ gsz1 + 2 * [overlap...] .* gflag)... ) end """ `truncatenoise!(mm, thresh)` zeros out any entries of the MismatchArray `mm` whose `denom` values are less than `thresh`. """ function truncatenoise!(mm::AbstractArray{NumDenom{T}}, thresh::Real) where {T<:Real} for I in eachindex(mm) if mm[I].denom <= thresh mm[I] = NumDenom{T}(0, 0) end end return mm end function truncatenoise!(mms::AbstractArray{A}, thresh::Real) where {A<:MismatchArray} for i in 1:length(denoms) truncatenoise!(mms[i], thresh) end return nothing end """ `shift = register_translate(fixed, moving, maxshift, [thresh])` computes the integer-valued translation which best aligns images `fixed` and `moving`. All shifts up to size `maxshift` are considered. Optionally specify `thresh`, the fraction (0<=thresh<=1) of overlap required between `fixed` and `moving` (default 0.25). """ function register_translate(fixed, moving, maxshift, thresh=nothing) mm = mismatch(fixed, moving, maxshift) _, denom = separate(mm) if thresh == nothing thresh = 0.25maximum(denom) end return indmin_mismatch(mm, thresh) end function checksize_maxshift(A::AbstractArray, maxshift) ndims(A) == length(maxshift) || error( "Array is $(ndims(A))-dimensional, but maxshift has length $(length(maxshift))" ) for i in 1:ndims(A) size(A, i) == 2 * maxshift[i] + 1 || error( "Along dimension $i, the output size $(size(A,i)) does not agree with maxshift[$i] = $(maxshift[i])", ) end return nothing end function padranges(blocksize, maxshift) padright = [maxshift...] transformdims = findall(padright .> 0) paddedsz = [blocksize...] + 2 * padright for i in transformdims # Pick a size for which one can efficiently calculate ffts padright[i] += padsize(blocksize, maxshift, i) - paddedsz[i] end return rng = UnitRange{Int}[ (1 - maxshift[i]):(blocksize[i] + padright[i]) for i in 1:length(blocksize) ] end function padsize(blocksize::Dims{N}, maxshift::Dims{N}) where {N} return map(padsize, blocksize, maxshift, ntuple(identity, Val(N))) end function padsize(blocksize::Int, maxshift::Int, dim::Int) p = blocksize + 2maxshift return maxshift > 0 ? (dim == 1 ? nextpow(2, p) : nextprod(FFTPROD, p)) : p # we won't FFT along dimensions with maxshift 0 end function assertsamesize(A, B) if !issamesize(A, B) error("Arrays are not the same size") end end function issamesize(A::AbstractArray, B::AbstractArray) n = ndims(A) ndims(B) == n || return false for i in 1:n axes(A, i) == axes(B, i) || return false end return true end function issamesize(A::AbstractArray, indices) n = ndims(A) length(indices) == n || return false for i in 1:n size(A, i) == length(indices[i]) || return false end return true end # This yields the _effective_ overlap, i.e., sets to zero if gridsize==1 along a coordinate # imgssz = image spatial size function computeoverlap(imgssz, blocksize, gridsize) gsz1 = max(1, [gridsize...] .- 1) tmp = [imgssz...] ./ gsz1 return blocksize - [ceil(Int, x) for x in tmp] end leftedge(center, width) = ceil(Int, center - width / 2) rightedge(center, width) = leftedge(center + width, width) - 1 # These avoid making a copy if it's not necessary tovec(v::AbstractVector) = v tovec(v::Tuple) = [v...] shiftrange(r, s) = r .+ s ### Utilities for unsafe indexing of views # TODO: redesign this whole thing to be safer? using Base: ViewIndex, to_indices, unsafe_length, index_shape, tail @inline function extraunsafe_view(V::SubArray{T,N}, I::Vararg{ViewIndex,N}) where {T,N} idxs = unsafe_reindex(V, V.indices, to_indices(V, I)) return SubArray(V.parent, idxs) end function get_index_wo_boundcheck(r::AbstractUnitRange, s::AbstractUnitRange{<:Integer}) # BlockRegistration issue #36 f = first(r) st = oftype(f, f + first(s) - 1) return range(st; length=length(s)) end function unsafe_reindex( V, idxs::Tuple{UnitRange,Vararg{Any}}, subidxs::Tuple{UnitRange,Vararg{Any}} ) (Base.@_propagate_inbounds_meta; @inbounds new1 = get_index_wo_boundcheck(idxs[1], subidxs[1]); (new1, unsafe_reindex(V, tail(idxs), tail(subidxs))...)) end unsafe_reindex(V, idxs, subidxs) = Base.reindex(V, idxs, subidxs) ### Deprecations function padsize(blocksize, maxshift) Base.depwarn( "padsize(::$(typeof(blocksize)), ::$(typeof(maxshift)) is deprecated, use Dims-tuples instead", :padsize, ) sz = Vector{Int}(undef, length(blocksize)) return padsize!(sz, blocksize, maxshift) end function padsize!(sz::Vector, blocksize, maxshift) n = length(blocksize) for i in 1:n sz[i] = padsize(blocksize, maxshift, i) end return sz end function padsize(blocksize, maxshift, dim) m = maxshift[dim] p = blocksize[dim] + 2m return m > 0 ? (dim == 1 ? nextpow(2, p) : nextprod(FFTPROD, p)) : p # we won't FFT along dimensions with maxshift[i]==0 end end #module
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1317
module RegisterQD using Images, CoordinateTransformations, ..QuadDIRECT using ..RegisterMismatchCommon using ..RegisterCore using ..RegisterDeformation, PaddedViews, MappedArrays using Rotations using Interpolations, ..CenterIndexedArrays, StaticArrays, OffsetArrays using LinearAlgebra using Images.ImageTransformations: CornerIterator const VecLike = Union{AbstractVector{<:Number},Tuple{Number,Vararg{Number}}} include("util.jl") include("translations.jl") include("rigid.jl") include("affine.jl") include("gridsearch.jl") export qd_translate, qd_rigid, qd_affine, arrayscale, grid_rotations, rotation_gridsearch, getSD, qsmooth # Deprecations function qd_rigid( fixed, moving, mxshift::VecLike, mxrot::Union{Number,VecLike}, minwidth_rot::VecLike, SD::AbstractMatrix=I; kwargs..., ) return error(""" `qd_rigid` has a new syntax, see the help (`?qd_rigid`) and `NEWS.md`. """) end function qd_affine( fixed, moving, mxshift, linmins, linmaxs, SD; thresh=0.5 * sum(_abs2.(fixed[.!(isnan.(fixed))])), initial_tfm=IdentityTransformation(), print_interval=100, kwargs..., ) return error(""" `qd_affine` has a new syntax, see the help (`?qd_affine`) and `NEWS.md`. """) end end # module
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
11887
""" tfm = linmap(mat, img, initial_tfm=IdentityTransformation()) Construct a linear transformation from the values in `mat`. `mat` can be any list of `N^2` values, where `N` is the dimensionality. `img` is the array (or array of the same dimensionality) that `tfm` will be applied to. If `initial_tfm` is supplied, it will be composed with the one from `mat`. See also [`RegisterQD.aff`](@ref), which includes a translational component. """ function linmap(mat, img::AbstractArray{T,N}, initial_tfm=IdentityTransformation()) where {T,N} # img isn't used *except* to get the dimensionality in an inferrable way, so that # the (static) size of the array in `tfm` is known. mat = [mat...] mat = reshape(mat, N,N) lm = LinearMap(SMatrix{N,N}(mat)) # The order below is subtle: you might think that `initial_tfm` should be applied # to `x` first, so that the order of composition should be `lm ∘ initial_tfm`. # But what we're going to be doing is calculating an `lm` that aligns # imgw(x) = moving(initial_tfm(x)) # to `fixed`. The final aligned image is # imgw2(x) = imgw(lm(x)) # Putting these two together, we see that # imgw2(x) = moving(initial_tfm(lm(x))) # and thus the resulting transformation is # initial_tfm ∘ lm return initial_tfm ∘ lm end """ tfm = aff(params, img, initial_tfm=IdentityTransformation()) Construct an affine transformation from the values in `params`. `params` can be any list of `N + N^2` values, where `N` is the dimensionality; the first `N` are for the translation, and the last `N^2` are for the linear portion (see [`RegisterQD.linmap`](@ref)). `img` is the array (or array of the same dimensionality) that `tfm` will be applied to. If `initial_tfm` is supplied, it will be composed with the one from `params`. """ function aff(params, img::AbstractArray{T,N}, initial_tfm=IdentityTransformation()) where {T,N} # img isn't used *except* to get the dimensionality in an inferrable way, so that # the (static) sizes of the arrays in `tfm` are known. params = [params...] length(params) == (N+N^2) || throw(DimensionMismatch("expected $(N+N^2) parameters, got $(length(params))")) offs = Float64.(params[1:N]) mat = Float64.(params[(N+1):end]) mat = reshape(mat,N,N) # The order below is explained in `linmap` return initial_tfm ∘ AffineMap(SMatrix{N,N}(mat), SVector{N}(offs)) end # This acts as the objective function during optimization, see qd_affine_coarse # which defines `f(x)` in terms of this function. # here params contains parameters of a linear map # The "fast" part means that it handles translation using `best_shift`, so this is # concerned only with the linear-map portion of the affine transformation. function affine_mm_fast(params, mxshift, fixed, moving, thresh, SD; initial_tfm=IdentityTransformation()) tfm = arrayscale(linmap(params, moving, initial_tfm), SD) moving, fixed = warp_and_intersect(moving, fixed, tfm) bshft, mm = best_shift(fixed, moving, mxshift, thresh; normalization=:intensity) return mm end # Similar to the above but includes the translation in `params` # This is used for optimization of the complete affine transformation. function affine_mm_slow(params, fixed, moving, thresh, SD; initial_tfm=IdentityTransformation()) tfm = arrayscale(aff(params, moving, initial_tfm), SD) moving, fixed = warp_and_intersect(moving, fixed, tfm) mm = mismatch0(fixed, moving; normalization=:intensity) return ratio(mm, thresh, Inf) end """ tfm, mm = qd_affine_coarse(fixed, moving, mxshift, linmins, linmaxs; kwargs...) Compute an affine transformation `tfm` that coarsely minimizes the mismatch between `fixed(x)` and `moving(tfm(x))`. `mm` is the total mismatch. The translational component is handled at the level of integer-pixel shifts, which is why this is "coarse" optimization. """ function qd_affine_coarse(fixed, moving, mxshift, linmins, linmaxs; SD=I, initial_tfm=IdentityTransformation(), thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), minwidth=default_lin_minwidths(moving), maxevals=5e4, kwargs...) # Define the objective function for the coarse stage f(x) = affine_mm_fast(x, mxshift, fixed, moving, thresh, SD; initial_tfm=initial_tfm) # QuadDIRECT benefits from bounds on the search region, build those bounds upper = linmaxs lower = linmins # Try to find the global minimum (within the needed precision) root, x0 = _analyze(f, lower, upper; minwidth=minwidth, print_interval=100, maxevals=maxevals, kwargs..., atol=0, rtol=1e-3) box = minimum(root) # Convert the coarse-minimum into a complete affine transformation params = position(box, x0) tfmcoarse0 = linmap(params, moving, initial_tfm) best_shft, mm = best_shift(fixed, moving, mxshift, thresh; normalization=:intensity, initial_tfm=arrayscale(tfmcoarse0, SD)) tfmcoarse = tfmcoarse0 ∘ pscale(Translation(best_shft), SD) return tfmcoarse, mm end """ tfm, mm = qd_affine_fine(fixed, moving, linmins, linmaxs; initial_tfm=IdentityTransformation(), kwargs...) Compute an affine transformation `tfm` that minimizes the mismatch between `fixed(x)` and `moving(tfm(x))`. `mm` is the total mismatch. This only allows small translations (just a couple of pixels). As a consequence, any large translations must be supplied with reasonable accuracy in `initial_tfm` (see [`RegisterQD.qd_affine_coarse`](@ref)). """ function qd_affine_fine(fixed, moving, linmins, linmaxs; SD=I, initial_tfm=IdentityTransformation(), thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), minwidth_mat=default_lin_minwidths(fixed)./10, maxevals=5e4, kwargs...) # Define the objective function f(x) = affine_mm_slow(x, fixed, moving, thresh, SD; initial_tfm=initial_tfm) # Limit translations to only a couple of pixels upper_shft = fill(2.0, ndims(fixed)) # Combine translation limits with the affine-transform limits upper = vcat(upper_shft, linmaxs) lower = vcat(-upper_shft, linmins) # Don't worry about translations that less than 1% of a pixel minwidth_shfts = fill(0.01, ndims(fixed)) minwidth = vcat(minwidth_shfts, minwidth_mat) # Try to find the global minimum root, x0 = _analyze(f, lower, upper; minwidth=minwidth, print_interval=100, maxevals=maxevals, kwargs...) box = minimum(root) # Convert the result to an affine transformation params = position(box, x0) tfmfine = aff(params, moving, initial_tfm) return tfmfine, value(box) end #TODO oops maybe dmax and ndax is too closely related to linmax and linmin? # Response: dmax and ndmax are designed to allow you to control linmax and linmin. # You supply one or the other, so I don't see a problem. #TODO I think that this is a tad loquatious, and not enough examples. Permission to rework it? """ `tform, mm = qd_affine(fixed, moving, mxshift, linmins, linmaxs, SD=I; presmoothed=false, thresh, initial_tfm, kwargs...)` `tform, mm = qd_affine(fixed, moving, mxshift, SD=I; presmoothed=false, thresh, initial_tfm, kwargs...)` optimizes an affine transformation (linear map + translation) to minimize the mismatch between `fixed` and `moving` using the QuadDIRECT algorithm. The algorithm is run twice: the first step samples the search space at a coarser resolution than the second. `kwargs...` may contain any keyword argument that can be passed to `QuadDIRECT.analyze`. It's recommended that you pass your own stopping criteria when possible (i.e. `rtol`, `atol`, and/or `fvalue`). If you provide `rtol` and/or `atol` they will apply only to the second (fine) step of the registration; the user may not adjust these criteria for the coarse step. `tform` will be centered on the origin-of-coordinates, i.e. (0,0) for a 2D image. Usually it is more natural to consider rotations around the center of the image. If you would like `mxrot` and the returned rotation to act relative to the center of the image, then you must move the origin to the center of the image by calling `centered(img)` from the `ImageTransformations` package. Call `centered` on both the fixed and moving image to generate the `fixed` and `moving` that you provide as arguments. If you later want to apply the returned transform to an image you must remember to call `centered` on that image as well. Alternatively you can re-encode the transformation in terms of a different origin by calling `recenter(tform, newctr)` where `newctr` is the displacement of the new center from the old center. The `linmins` and `linmaxs` arguments set the minimum and maximum allowable values in the linear map matrix. They can be supplied as NxN matrices or flattened vectors. If omitted then a modest default search space is chosen. `mxshift` sets the magnitude of the largest allowable translation in each dimension (It's a vector of length N). This default search-space allows for very little rotation. Alternatively, you can submit `dmax` or `ndmax` values as keyword functions, which will use diagonal or non-diagonal variation from the identity matrix to generate less modest `linmins` and `linmaxs` arguments for you. Use `presmoothed=true` if you have called [`qsmooth`](@ref) on `fixed` before calling `qd_affine`. Do not smooth `moving`. `kwargs...` can also include any other keyword argument that can be passed to `QuadDIRECT.analyze`. It's recommended that you pass your own stopping criteria when possible (i.e. `rtol`, `atol`, and/or `fvalue`). If you have a good initial guess at the solution, pass it with the `initial_tfm` kwarg to jump-start the search. Use `SD` if your axes are not uniformly sampled, for example `SD = diagm(voxelspacing)` where `voxelspacing` is a vector encoding the spacing along all axes of the image. `thresh` enforces a certain amount of sum-of-squared-intensity overlap between the two images; with non-zero `thresh`, it is not permissible to "align" the images by shifting one entirely out of the way of the other. """ function qd_affine(fixed, moving, mxshift, linmins, linmaxs; presmoothed=false, SD=I, thresh=0.5*sum(_abs2.(fixed[.!(isnan.(fixed))])), initial_tfm=IdentityTransformation(), print_interval=100, kwargs...) fixed, moving = float(fixed), float(moving) if presmoothed moving = qinterp(eltype(fixed), moving) end linmins = [linmins...] linmaxs = [linmaxs...] print_interval < typemax(Int) && print("Running coarse step\n") mw = default_lin_minwidths(moving) tfm_coarse, mm_coarse = qd_affine_coarse(fixed, moving, mxshift, linmins, linmaxs; SD = SD, minwidth=mw, initial_tfm=initial_tfm, thresh=thresh, print_interval=print_interval, kwargs...) print_interval < typemax(Int) && print("Running fine step\n") mw = mw./100 linmins, linmaxs = scalebounds(linmins, linmaxs, 0.5) # should these be narrowed further? final_tfm, final_mm = qd_affine_fine(fixed, moving, linmins, linmaxs; SD = SD, minwidth_mat=mw, initial_tfm=tfm_coarse, thresh=thresh, print_interval=print_interval, kwargs...) return final_tfm, final_mm end function qd_affine(fixed, moving, mxshift; dmax = 0.05, ndmax = 0.05, kwargs...) minb, maxb = default_linmap_bounds(fixed; dmax = dmax, ndmax = ndmax) return qd_affine(fixed, moving, mxshift, minb, maxb; kwargs...) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
3602
""" `rotations = grid_rotations(maxradians, rgridsz, SD)` generates a set of rotations (AffineMap) useful for a gridsearch of possible rotations to align a pair of images. `maxradians` is either a single maximum angle (in 2D) or a set of Euler angles (in 3D and higher). `rgridsz` is one or more integers specifying the number of gridpoints to search in each of the rotation axes, corresponding with entries in `maxradians`. `SD` is a matrix specifying the sample spacing. e.g. `grid_rotations((pi/8,pi/8,pi/8), (3,3,3), Matrix{Float64}(I,3,3))` would return an array of 27 rotations with 3 possible angles for each Euler axis: -pi/8, 0, pi/8. Passing `Matrix{Float64}(I,3,3)` for SD indicates that the resulting transforms are meant to be applied to an image with isotropic pixel spacing. """ function grid_rotations(maxradians, rgridsz, SD) rgridsz = [rgridsz...] maxradians = [maxradians...] nd = size(SD,1) if !all(isodd, rgridsz) @warn("rgridsz should be odd; rounding up to the next odd integer") end for i = 1:length(rgridsz) if !isodd(rgridsz[i]) rgridsz[i] = max(round(Int, rgridsz[i]) + 1, 1) end end grid_radius = map(x->div(x,2), rgridsz) if nd > 2 gridcoords = [range(-grid_radius[x]*maxradians[x], stop=grid_radius[x]*maxradians[x], length=rgridsz[x]) for x=1:nd] rotation_angles = Iterators.product(gridcoords...) else rotation_angles = range(-grid_radius[1]*maxradians[1], stop=grid_radius[1]*maxradians[1], length=rgridsz[1]) end axmat = Matrix{Float64}(I,nd,nd) axs = map(x->axmat[:,x], 1:nd) tfeye = tformeye(nd) output = typeof(tfeye)[] for ra in rotation_angles if nd > 2 euler_rots = map(x->tformrotate(x...), zip(axs, ra)) rot = foldr(∘, euler_rots, init=tfeye) elseif nd == 2 rot = tformrotate(ra) else error("Unsupported dimensionality") end push!(output, AffineMap(SD*rot.linear/SD , zeros(nd))) #account for sample spacing end return output end """ `best_tform, best_mm = rotation_gridsearch(fixed, moving, maxshift, maxradians, rgridsz, SD =Matrix{Float64}(I,ndims(fixed),ndims(fixed))))` Tries a grid of rotations to align `moving` to `fixed`. Also calculates the best translation (`maxshift` pixels or less) to align the images after performing the rotation. Returns an AffineMap that captures both the best rotation and shift out of the values searched, along with the mismatch value after applying that transform (`best_mm`). For more on how the arguments `maxradians`, `rgridsz`, and `SD` influence the search, see the documentation for `grid_rotations`. """ function rotation_gridsearch(fixed, moving, maxshift, maxradians, rgridsz, SD = Matrix{Float64}(I,ndims(fixed),ndims(fixed))) rgridsz = [rgridsz...] nd = ndims(moving) @assert nd == ndims(fixed) rots = grid_rotations(maxradians, rgridsz, SD) best_mm = Inf best_rot = tformeye(nd) best_shift = zeros(nd) for rot in rots new_moving = transform(moving, rot) #calc mismatch #mm = mismatch(fixed, new_moving, maxshift; normalization=:pixels) mm = mismatch(fixed, new_moving, maxshift) thresh = 0.1*maximum(x->x.denom, mm) best_i = indmin_mismatch(mm, thresh) cur_best =ratio(mm[best_i], 0.0) if cur_best < best_mm best_mm = cur_best best_rot = rot best_shift = [best_i.I...] end end return tformtranslate(best_shift) ∘ best_rot, best_mm end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
9990
## Transformations # Rotation only """ R2 = rot(θ) Calculate a two-dimensional rotation transformation `R2`. `θ` is the angle of rotation around the `z` axis applied to the `xy` plane. """ rot(θ::Number) = LinearMap(RotMatrix(θ)) """ R3 = rot(qx, qy, qz) Calculate a three-dimensional rotation transformation from the supplied parameters. `qx`, `qy`, and `qz` specify the rotation via the components of the corresponding [unit quaternion](https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation). Briefly, `R3` is a rotation around the axis specified by the unit vector `q/|q|` (where `q` is the 3-component vector), with an angle `θ` given by `sin(θ/2) = |q|`. If `|q| > 1`, `rot` returns `nothing` instead of erroring. """ function rot(qx::Number, qy::Number, qz::Number) # Unit-quaternion parametrization r2 = qx^2 + qy^2 + qz^2 r2 > 1 && return nothing qr = sqrt(1 - r2) R = @SMatrix([1 - 2*(qy^2 + qz^2) 2*(qx*qy - qz*qr) 2*(qx*qz + qy*qr); 2*(qx*qy + qz*qr) 1 - 2*(qx^2 + qz^2) 2*(qy*qz - qx*qr); 2*(qx*qz - qy*qr) 2*(qy*qz + qx*qr) 1 - 2*(qx^2 + qy^2)]) return LinearMap(RotMatrix(R)) end #rotation + translation tfmrigid(dx::Number, dy::Number, θ::Number) = Translation(dx, dy) ∘ rot(θ) tfmrigid(dx::Number, dy::Number, dz::Number, qx::Number, qy::Number, qz::Number) = Translation(dx, dy, dz) ∘ rot(qx, qy, qz) ## Transformations supplied as vectors, for which we pass the array so we can infer the dimensionality @noinline dimcheck(v, lv) = length(v) == lv || throw(DimensionMismatch("expected $lv parameters, got $(length(v))")) function rot(theta, img::AbstractArray{T,2}) where {T} dimcheck(theta, 1) return rot(theta[1]) end function rot(qs, img::AbstractArray{T,3}) where {T} dimcheck(qs, 3) qx, qy, qz = qs return rot(qx, qy, qz) end function tfmrigid(params, img::AbstractArray{T,2}) where {T} dimcheck(params, 3) dx, dy, θ = params return tfmrigid(dx, dy, θ) end function tfmrigid(params, img::AbstractArray{T,3}) where {T} dimcheck(params, 6) dx, dy, dz, qx, qy, qz = params return tfmrigid(dx, dy, dz, qx, qy, qz) end ## Computing mismatch #rotation + shift, fast because it uses fourier method for shift function rigid_mm_fast(theta, mxshift, fixed, moving, thresh, SD; initial_tfm=IdentityTransformation()) # The reason this is `initial_tfm ∘ rot` rather than `rot ∘ initial_tfm` # is explained in `linmap` tfm = arrayscale(initial_tfm ∘ rot(theta, moving), SD) moving, fixed = warp_and_intersect(moving, fixed, tfm) bshft, mm = best_shift(fixed, moving, mxshift, thresh; normalization=:intensity) return mm end #rotation + shift, slow because it warps for every rotation and shift function rigid_mm_slow(params, fixed, moving, thresh, SD; initial_tfm=IdentityTransformation()) tfm = arrayscale(initial_tfm ∘ tfmrigid(params, moving), SD) moving, fixed = warp_and_intersect(moving, fixed, tfm) mm = mismatch0(fixed, moving; normalization=:intensity) return ratio(mm, thresh, Inf) end function qd_rigid_coarse(fixed, moving, mxshift, mxrot, minwidth_rot; SD=I, initial_tfm=IdentityTransformation(), thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), kwargs...) #note: if a trial rotation results in image overlap < thresh for all possible shifts then QuadDIRECT throws an error f(x) = rigid_mm_fast(x, mxshift, fixed, moving, thresh, SD; initial_tfm=initial_tfm) upper = [mxrot...] lower = -upper root_coarse, x0coarse = _analyze(f, lower, upper; minwidth=minwidth_rot, print_interval=100, maxevals=5e4, kwargs..., atol=0, rtol=1e-3) box_coarse = minimum(root_coarse) tfmcoarse0 = initial_tfm ∘ rot(position(box_coarse, x0coarse), moving) best_shft, mm = best_shift(fixed, moving, mxshift, thresh; normalization=:intensity, initial_tfm=arrayscale(tfmcoarse0, SD)) tfmcoarse = tfmcoarse0 ∘ pscale(Translation(best_shft), SD) return tfmcoarse, mm end function qd_rigid_fine(fixed, moving, mxrot, minwidth_rot; SD=I, initial_tfm=IdentityTransformation(), thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), kwargs...) f(x) = rigid_mm_slow(x, fixed, moving, thresh, SD; initial_tfm=initial_tfm) upper_shft = fill(2.0, ndims(fixed)) upper_rot = mxrot upper = vcat(upper_shft, upper_rot) lower = -upper minwidth_shfts = fill(0.005, ndims(fixed)) minwidth = vcat(minwidth_shfts, minwidth_rot) root, x0 = _analyze(f, lower, upper; minwidth=minwidth, print_interval=100, maxevals=5e4, kwargs...) box = minimum(root) tfmfine = initial_tfm ∘ tfmrigid(position(box, x0), moving) return tfmfine, value(box) end """ tform, mm = qd_rigid(fixed, moving, mxshift, mxrot; presmoothed=false, SD=I, minwidth_rot=default_minwidth_rot(fixed, SD), thresh=thresh, initial_tfm=IdentityTransformation(), kwargs...) Optimize a rigid transformation (rotation + shift) to minimize the mismatch between `fixed` and `moving` using the QuadDIRECT algorithm. The algorithm is run twice: the first step finds the optimal rotation, using a fourier method to speed up the search for the best whole-pixel shift. The second step performs the rotation + shift in combination to obtain sub-pixel accuracy. Any `NaN`-valued pixels are not included in the mismatch; you can use this to mask out any regions of `fixed` that you don't want to align against. `mxshift` is the maximum-allowed translation, in units of array indices. It can be passed as a vector or tuple. `mxrot` is the maximum-allowed rotation, in radians for 2d or [quaternion-units](https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation) for 3d. See [`RegisterQD.rot`](@ref) for more information. `minwidth_rot` optionally specifies the lower limit of resolution for the rotation; the default is a rotation that moves corner elements by 0.1 pixel. `kwargs...` can include any keyword argument that can be passed to `QuadDIRECT.analyze`. It's recommended that you pass your own stopping criteria when possible (i.e. `rtol`, `atol`, and/or `fvalue`). If you provide `rtol` and/or `atol` they will apply only to the second (fine) step of the registration; there is currently no way to adjust these criteria for the coarse step. The rotation returned will be centered on the origin-of-coordinates, i.e. (0,0) for a 2D image. Usually it is more natural to consider rotations around the center of the image. If you would like `mxrot` and the returned rotation to act relative to the center of the image, then you must move the origin to the center of the image by calling `centered(img)` from the `ImageTransformations` package. Call `centered` on both the fixed and moving image to generate the `fixed` and `moving` that you provide as arguments. If you later want to apply the returned transform to an image you must remember to call `centered` on that image as well. Alternatively you can re-encode the transformation in terms of a different origin by calling `recenter(tform, newctr)` where `newctr` is the displacement of the new center from the old center. Use `SD` ("spatial displacements") if your axes are not uniformly sampled, for example `SD = diagm(voxelspacing)` where `voxelspacing` is a vector encoding the spacing along all axes of the image. See [`arrayscale`](@ref) for more information about `SD`. `thresh` enforces a certain amount of sum-of-squared-intensity overlap between the two images; with non-zero `thresh`, it is not permissible to "align" the images by shifting one entirely out of the way of the other. The default value for `thresh` is 10% of the sum-of-squared-intensity of `fixed`. If you have a good initial guess at the solution, pass it with the `initial_tfm` kwarg to jump-start the search. Use `presmoothed=true` if you have called [`qsmooth`](@ref) on `fixed` before calling `qd_rigid`. Do not smooth `moving`. Both the output `tfm` and any `initial_tfm` are represented in *physical* coordinates; as long as `initial_tfm` is a rigid transformation, `tfm` will be a pure rotation+translation. If `SD` is not the identity, use `arrayscale` before applying the result to `moving`. """ function qd_rigid(fixed, moving, mxshift::VecLike, mxrot::Union{Number,VecLike}; presmoothed=false, SD=I, minwidth_rot=default_minwidth_rot(CartesianIndices(fixed), SD), thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), initial_tfm=IdentityTransformation(), print_interval=100, kwargs...) #TODO make sure isrotation(initial_tfm.linear) returns true, else throw a warning and an option to terminate? do I still allow the main block to run? if initial_tfm == IdentityTransformation() || isrotation(initial_tfm.linear) else @show "WARNING: initial_tfm is not a rigid transformation" # @warn "initial_tfm is not a rigid transformation" end fixed, moving = float(fixed), float(moving) if presmoothed moving = qinterp(eltype(fixed), moving) end mxrot = [mxrot...] print_interval < typemax(Int) && print("Running coarse step\n") tfm_coarse, mm_coarse = qd_rigid_coarse(fixed, moving, mxshift, mxrot, minwidth_rot; SD=SD, initial_tfm=initial_tfm, thresh=thresh, print_interval=print_interval, kwargs...) print_interval < typemax(Int) && print("Obtained mismatch $mm_coarse from coarse step, running fine step\n") final_tfm, mm_fine = qd_rigid_fine(fixed, moving, mxrot./2, minwidth_rot; SD=SD, initial_tfm=tfm_coarse, thresh=thresh, print_interval=print_interval, kwargs...) return final_tfm, mm_fine end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
4824
#################### Translation Search ########################## function tfmshift(params, img::AbstractArray{T,N}) where {T,N} length(params) == N || throw(DimensionMismatch("expected $N parameters, got $(length(params))")) return Translation(params...) end #slow because it warps for every shift instead of using fourier method function translate_mm_slow(params, fixed, moving, thresh; initial_tfm=IdentityTransformation()) tfm = initial_tfm ∘ tfmshift(params, moving) moving, fixed = warp_and_intersect(moving, fixed, tfm) mm = mismatch0(fixed, moving; normalization=:intensity) return ratio(mm, thresh, Inf) end function qd_translate_fine(fixed, moving; initial_tfm=IdentityTransformation(), minwidth=fill(0.01, ndims(fixed)), thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), kwargs...) f(x) = translate_mm_slow(x, fixed, moving, thresh; initial_tfm=initial_tfm) upper = fill(1.0, ndims(fixed)) lower = -upper root, x0 = _analyze(f, lower, upper; minwidth=minwidth, print_interval=100, kwargs...) box = minimum(root) tfmfine = initial_tfm ∘ tfmshift(position(box, x0), moving) return tfmfine, value(box) end """ `tform, mm = qd_translate(fixed, moving, mxshift; presmoothed=false, thresh=thresh, kwargs...)` optimizes a simple shift (translation) to minimize the mismatch between `fixed` and `moving` using the QuadDIRECT algorithm with the constraint that no shifts larger than ``mxshift` (after an optional `initial_tfm`) will be considered. Both `mxshift` and the returned translation are specified in terms of pixel units, so the algorithm need not be aware of anisotropic sampling. The algorithm involves two steps: the first step uses a fourier method to speed up the search for the best whole-pixel shift. The second step refines the search for sub-pixel accuracy. The default precision of this step is 1% of one pixel (0.01) for each dimension of the image. You can override the default with the `minwidth` argument. `kwargs...` can also include any other keyword argument that can be passed to `QuadDIRECT.analyze`. It's recommended that you pass your own stopping criteria when possible (i.e. `rtol`, `atol`, and/or `fvalue`). Use `presmoothed=true` if you have called [`qsmooth`](@ref) on `fixed` before calling `qd_affine`. Do not smooth `moving`. If you have a good initial guess at the solution, pass it with the `initial_tfm` kwarg to jump-start the search. `thresh` enforces a certain amount of sum-of-squared-intensity overlap between the two images; with non-zero `thresh`, it is not permissible to "align" the images by shifting one entirely out of the way of the other. If the `crop` keyword arg is `true` then `fixed` is cropped by `mxshift` (after the optional `initial_tfm`) on all sides so that there will be complete overlap between `fixed` and `moving` for any evaluated shift. This avoids edge effects that can occur due to normalization when the transformed `moving` doesn't fully overlap with `fixed`. """ function qd_translate(fixed, moving, mxshift; presmoothed=false, thresh=0.1*sum(_abs2.(fixed[.!(isnan.(fixed))])), initial_tfm=IdentityTransformation(), minwidth=fill(0.01, ndims(fixed)), print_interval=100, crop=false, kwargs...) fixed, moving = float(fixed), float(moving) if presmoothed moving = qinterp(eltype(fixed), moving) end print_interval < typemax(Int) && print("Running coarse step\n") if crop #we enforce that moving is always bigger than fixed by amount 2*(maxshift+1) (the +1 is for the fine step) sz = size(fixed) .- (2 .* mxshift) if any(size(moving) .< (2 .* (mxshift.+1))) error("Moving image size must be at least 2 * (mxshift+1) when crop_edges is set to true") end cropped_inds_f = crop_rng.(axes(fixed), mxshift) cropped_inds_m = crop_rng.(axes(moving), mxshift) moving_inner = view(moving, cropped_inds_m...) fixed_inner = view(fixed, cropped_inds_f...) moving_fine = OffsetArray(moving, (-1 .* mxshift)...) else fixed_inner = fixed moving_inner = moving_fine = moving end best_shft, mm = best_shift(fixed_inner, moving_inner, mxshift, thresh; normalization=:intensity, initial_tfm=initial_tfm) tfm_coarse = initial_tfm ∘ Translation(best_shft) print_interval < typemax(Int) && print("Running fine step\n") return qd_translate_fine(fixed_inner, moving_fine; initial_tfm=tfm_coarse, thresh=thresh, minwidth=minwidth, print_interval=print_interval, kwargs...) end crop_rng(rng::AbstractUnitRange{Int}, amt::Int) = (first(rng)+amt):(last(rng)-amt)
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
9696
function warp_and_intersect(moving, fixed, tfm::IdentityTransformation) if axes(moving) == axes(fixed) return moving, fixed end inds = intersect.(axes(moving), axes(fixed)) return view(moving, inds...), view(fixed, inds...) end function warp_and_intersect(moving, fixed, tfm) moving = warp(moving, tfm) inds = intersect.(axes(moving), axes(fixed)) return view(moving, inds...), view(fixed, inds...) end """ I, mm = best_shift(fixed, moving, mxshift, thresh; normalization=:intensity, initial_tfm=IdentityTransformation()) Find the best shift `I` (expressed as a tuple) aligning `moving` to `fixed`, possibly after an initial transformation `initial_tfm` applied to `moving`. `mm` is the sum-of-square errors at shift `I`. `mxshift` represents the maximum allowed shift, in pixels. `thresh` is a threshold on the minimum allowed overlap between `fixed` and the shifted `moving`, expressed in pixels if `normalization=:pixels` and in sum-of-squared-intensity if `normalization=:intensity`. One can compute an overall transformation by composing `initial_tfm` with the returned shift `I`. """ function best_shift(fixed, moving, mxshift, thresh; normalization=:intensity, initial_tfm=IdentityTransformation()) moving, fixed = warp_and_intersect(moving, fixed, initial_tfm) mms = mismatch(fixed, moving, mxshift; normalization=normalization) best_i = indmin_mismatch(mms, thresh) mm = mms[best_i] return best_i.I, ratio(mm, thresh, typemax(eltype(mm))) end """ itfm = arrayscale(ptfm, SD) Convert the physical-space transformation `ptfm` into one, `itfm`, that operates on index-space for arrays. For example, suppose `ptfm` is a pure 3d rotation, but you want to apply it to an array in which the sampling along the three axes is (0.5mm, 0.5mm, 2mm). Then by setting `SD = Diagonal(SVector(1, 1, 4))` (the ratio of scales along each axis), one obtains an `itfm` suitable for warping the array. Any translational component of `ptfm` is interpreted in physical-space units, not index-units. `SD` does not even have to be diagonal, if the array sampling is skewed. The columns of `SD` should correspond to the physical-coordinate displacement achieved by shifting by one array element along each axis of the array. Specifically, `SD[:,j]` should be the physical displacement of one array voxel along dimension `j`. """ arrayscale(ptfm::AbstractAffineMap, SD::AbstractMatrix) = arrayscale(ptfm, LinearMap(SD)) arrayscale(ptfm::AbstractAffineMap, scale::LinearMap) = inv(scale) ∘ ptfm ∘ scale arrayscale(ptfm::AbstractAffineMap, scale::UniformScaling) = ptfm """ pt = pscale(it, SD) Convert an index-scaled translation `it` into a physical-space translation `pt`. See [`arrayscale`](@ref) for more information. """ pscale(t::Translation, SD::AbstractMatrix) = pscale(t, LinearMap(SD)) pscale(t::Translation, scale::LinearMap) = Translation(scale(t.translation)) pscale(t::Translation, scale::UniformScaling) = Translation(scale.Ξ»*t.translation) #returns new minbounds and maxbounds with range sizes change by fac function scalebounds(minb, maxb, fac::Real) orng = maxb.-minb newradius = fac.*orng./2 ctrs = minb.+(orng./2) return ctrs.-newradius, ctrs.+newradius end """ minb, maxb = default_linmap_bounds(img::AbstractArray{T,N}; dmax=0.05, ndmax=0.05) where {T,N} Returns two matrices describing a search space of linear transformation matrices. (Linear transformation matrices can encode rotations, scaling, shear, etc) `minb` and `maxb` contain the minimum and maximum acceptable values of an NxN transformation matrix. The center of the space is the identity matrix. The size of the space can be specified with `dmax` and `ndmax` kwargs. These represent the maximum (absolute) difference from the identity matrix for elements along the diagonal and off the diagnonal, respectively. e.g. `dmax=0.05` implies that diagonal elements can range from 0.95 to 1.05. The space is centered on the identity matrix """ function default_linmap_bounds(img::AbstractArray{T,N}; dmax=0.05, ndmax=0.05) where {T, N} deltas = fill(abs(ndmax), N,N) for i=1:N deltas[i,i] = abs(dmax) end return Matrix(1.0*I,N,N).-deltas, Matrix(1.0*I,N,N).+deltas end """ m = default_lin_minwidths(img::AbstractArray{T,N}; dmin=1e-3, ndmin=1e-3) where {T,N} Returns a NxN matrix describing granularity of a search space of linear transformation matrices. This can be useful for setting the `minwidth` parameter of QuadDIRECT when performing a full affine registration. `dmin` and `ndmin` set the tolerances for diagonal and off-diagonal elements of the linear transformation matrix, respectively. """ function default_lin_minwidths(img::AbstractArray{T,N}; dmin=1e-5, ndmin=1e-5) where {T, N} mat = fill(abs(ndmin), N,N) for i=1:N mat[i,i] = abs(dmin) end return mat[:] end """ ΞΈ = default_minrot(ci::CartesianIndices, SD=I; Ξ”c=0.1) Compute the rotation `ΞΈ` that results in largest change in coordinates of size `Ξ”c` (in pixels) for any index in `ci`. """ function default_minrot(ci::CartesianIndices, SD=I; Ξ”c=0.1) L = -Inf for x in CornerIterator(ci) xβ€² = SD*SVector(Tuple(x)) # position of corner point in physical space L = max(L, norm(xβ€²)) end S2 = SD'*SD if SD == I Ξ» = 1 else F = eigen(S2) Ξ» = minimum(F.values) end β„“ = sqrt(Ξ»)*Ξ”c return 2*asin(β„“/(2*L)) end default_minwidth_rot(ci::CartesianIndices{2}, SD=I; kwargs...) = [default_minrot(ci, SD; kwargs...)] function default_minwidth_rot(ci::CartesianIndices{3}, SD=I; kwargs...) ΞΈ = default_minrot(ci, SD; kwargs...) return [ΞΈ, ΞΈ, ΞΈ] end """ getSD(A::AbstractArray) If your image is not uniformily sampled, use this to get the `SD` matrix, which represents spacing along all axes of an image. # Examples ```julia-repl julia> myimage Normed ImageMeta with: data: 3-dimensional AxisArray{N2f14,3,...} with axes: :x, 0.0 ΞΌm:0.71 ΞΌm:6.39 ΞΌm :l, 0.0 ΞΌm:0.71 ΞΌm:6.39 ΞΌm :z, 0.0 ΞΌm:6.2 ΞΌm:55.8 ΞΌm And data, a 10Γ—10Γ—10 Array{N2f14,3} with eltype Normed{UInt16,14} properties: imagineheader: <suppressed> julia> getSD(myimage) 3Γ—3 SArray{Tuple{3,3},Float64,2,9} with indices SOneTo(3)Γ—SOneTo(3): 0.71 0.0 0.0 0.0 0.71 0.0 0.0 0.0 6.2 ``` """ getSD(A::AbstractArray) = getSD(spacedirections(A)) #takes advantage of how spacedirections automatically strips out the time component function getSD(sd::NTuple{N,Tuple}) where N SD = zeros(N,N) denom = oneunit(sd[1][1]) #dividing by a unit should remove unit inconsistancies for i = 1:N for j = 1:N SD[i,j] = sd[i][j]/denom end end return SMatrix{N,N}(SD) #returns static matrix for faster type inferrence end """ imgq = qsmooth(img) imgq = qsmooth(T, img) Create a smoothed version of `img`, smoothing with the kernel of a quadratic B-spline. Use this on your `fixed` image in preparation for registration, and pass `presmoothed` as an option. (Do not smooth `moving`.) `T` allows you to specify the output eltype (default `Float32`). """ function qsmooth(::Type{T}, img::AbstractArray{T2,N}) where {T,N,T2} kern1 = centered(T[1/8, 3/4, 1/8]) # quadratic B-spline kernel return imfilter(img, kernelfactors(ntuple(i->kern1, Val(N)))) end qsmooth(img::AbstractArray) = qsmooth(Float32, img) function qinterp(::Type{T}, moving) where T widen1(ax) = first(ax)-1:last(ax)+1 # This sets up an interpolant object *without* using Interpolations.prefilter # Prefiltering is a form of "anti-smoothing," meaning that for quadratic interpolation # it defines a coefficient array so that, when you interpolate (aka, smooth), # it reconstructs the original values. In this case, we *want* interpolation to # perform smoothing, because the user has applied the same smoothing to `fixed` # by calling `qsmooth`. # Build the coefficient array. Quadratic interpolation requires one beyond-the-edge # element, which we set to NaN nanT = convert(T, NaN) mmpad = PaddedView(nanT, of_eltype(T, moving), widen1.(axes(moving))) # Create the interpolant, bypassing prefiltering return extrapolate(Interpolations.BSplineInterpolation(T, T.(mmpad), BSpline(Quadratic(Free(OnCell()))), axes(moving)), nanT) end # ΞΈ = Inf # # R = I + [0 -Δθ; Δθ 0] is a rotmtrx for infinitesimal Δθ # # `dRdΞΈ` is the "slope" of the rotation, which allows us to compute # # the # dRdΞΈ = SD \ (@SMatrix([0 -1; 1 0]) * SD) # for c in CornerIterator(ci) # dcdΞΈs = dRdΞΈ*SVector(Tuple(c)) # for dcdΞΈ in dcdΞΈs # ΞΈ = min(ΞΈ, abs(Ξ”c/dcdΞΈ)) # end # end # return (ΞΈ,) # end # function default_minwidth_rot(I::CartesianIndices{3}, SD; d=0.1) # slice2d(I, i1, i2) = CartesianIndices((I.indices[i1], I.indices[i2])) # return (default_minwidth_rot(slice2d(I, 2, 3), SD[2:3, 2:3]; d=d)..., # default_minwidth_rot(slice2d(I, 1, 3), SD[[1,3], [1,3]]; d=d)..., # default_minwidth_rot(slice2d(I, 1, 2), SD[1:2, 1:2]; d=d)...) # end #sets splits based on lower and upper bounds function _analyze(f, lower, upper; kwargs...) splits = ([[lower[i]; lower[i]+(upper[i]-lower[i])/2; upper[i]] for i=1:length(lower)]...,) QuadDIRECT.analyze(f, splits, lower, upper; kwargs...) end # abs2 was removed in https://github.com/JuliaGraphics/ColorVectorSpace.jl/pull/131 # this is the current recommended replacement # TODO: follow https://github.com/JuliaGraphics/ColorVectorSpace.jl/issues/157 and adjust for changes _abs2(c) = mapreducec(v->float(v)^2, +, float(zero(eltype(c))), c)
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1382
module RegisterUtilities export Counter #### Counter #### # # Stolen from Grid.jl. Useful when you want to do more math on the iterator. struct Counter max::Vector{Int} end Counter(sz::Tuple) = Counter(Int[sz...]) function Base.iterate(c::Counter) N = length(c.max) (N == 0 || any(c.max .<= 0)) && return nothing state = ones(Int, N) copy(state), state end function Base.iterate(c::Counter, state) state[1] += 1 i = 1 while state[i] > c.max[i] && i < length(state) state[i] = 1 i += 1 state[i] += 1 end state[end] > c.max[end] && return nothing copy(state), state end # Below functions are from RegisterTestUtilities using ..RegisterCore, LinearAlgebra export quadratic, block_center, tighten function quadratic(m, n, shift, Q) A = zeros(m, n) c = block_center(m, n) cntr = [shift[1] + c[1], shift[2] + c[2]] u = zeros(2) for j = 1:n, i = 1:m u[1], u[2] = i - cntr[1], j - cntr[2] A[i, j] = dot(u, Q * u) end A end quadratic(shift, Q, denom::Matrix) = MismatchArray(quadratic(size(denom)..., shift, Q), denom) function block_center(sz...) ntuple(i -> sz[i] >> 1 + 1, length(sz)) end function tighten(A::AbstractArray) T = typeof(first(A)) for a in A T = promote_type(T, typeof(a)) end At = similar(A, T) copyto!(At, A) end end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
9316
function make_lutbridge() begin vec( [ 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ], ) end end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2344
module StructuringElements export strel, strel_type, strel_size, strel_ndims export SEMask, MorphologySE, SEOffset export is_symmetric, require_symmetric_strel export strel_split export strel_box, SEBox, SEBoxArray export strel_diamond, SEDiamond, SEDiamondArray export strel_chain, strel_product, SEChain, SEChainArray # TODO(johnnychen94): remove ImageCore dependency using ImageCore: coords_spatial using OffsetArrays using OffsetArrays: centered abstract type MorphologySE{N} end abstract type MorphologySEArray{N} <: AbstractArray{Bool,N} end OffsetArrays.centered(A::MorphologySEArray) = A """ SEMask{N}() A (holy) trait type for representing structuring element as connectivity mask. This connectivity mask SE is a bool array where `true` indicates that pixel position is connected to the center point. ```jldoctest; setup=:(using ImageMorphology) julia> se = centered(Bool[0 1 0; 1 1 1; 0 1 0]) # commonly known as C4 connectivity 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 0 1 0 1 1 1 0 1 0 julia> strel_type(se) ImageMorphology.StructuringElements.SEMask{2}() ``` See also [`SEOffset`](@ref StructuringElements.SEOffset) for the displacement offset representation. More details can be found on he documentation page [Structuring Element](@ref concept_se). """ struct SEMask{N} <: MorphologySE{N} end """ SEOffset{N}() A (holy) trait type for representing structuring element as displacement offsets. This displacement offsets SE is an array of `CartesianIndex` where each element stores the displacement offset from the center point. ```jldoctest; setup=:(using ImageMorphology) julia> se = [CartesianIndex(-1, 0), CartesianIndex(0, -1), CartesianIndex(1, 0), CartesianIndex(0, 1)] 4-element Vector{CartesianIndex{2}}: CartesianIndex(-1, 0) CartesianIndex(0, -1) CartesianIndex(1, 0) CartesianIndex(0, 1) julia> strel_type(se) ImageMorphology.StructuringElements.SEOffset{2}() ``` See also [`SEMask`](@ref StructuringElements.SEMask) for the connectivity mask representation. More details can be found on he documentation page [Structuring Element](@ref concept_se). """ struct SEOffset{N} <: MorphologySE{N} end include("strel.jl") # SE constructors include("strel_chain.jl") include("strel_box.jl") include("strel_diamond.jl") include("utils.jl") end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2128
# From https://github.com/JuliaImages/ImageMorphology.jl/blob/master/src/ops/bothat.jl """ bothat(img; dims=coords_spatial(img), r=1) bothat(img, se) Performs morphological bottom-hat transform for given image, i.e., `closing(img, se) - img`. $(_docstring_se) This bottom-hat transform, also known as _black_ top-hat transform, can be used to extract small black elements and details from an image. To extract white details, the _white_ top-hat transform [`tophat`](@ref) can be used. # Examples ```jldoctest; setup = :(using ImageMorphology) julia> img = falses(7, 7); img[3:5, 3:5] .= true; img[4, 6] = true; img[4, 4] = false; img 7Γ—7 BitMatrix: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 julia> Int.(bothat(img)) 7Γ—7 Matrix{$Int}: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 julia> Int.(bothat(img, strel_diamond(img))) # use diamond shape SE 7Γ—7 Matrix{$Int}: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` See also [`bothat!`](@ref) for the in-place version. """ function bothat(img; kwargs...) return bothat!(similar(img, maybe_floattype(eltype(img))), img, similar(img); kwargs...) end bothat(img, se) = bothat!(similar(img, maybe_floattype(eltype(img))), img, se, similar(img)) """ bothat!(out, img, buffer; [dims], [r]) bothat!(out, img, se, buffer) The in-place version of [`bothat`](@ref) with input image `img` and output image `out`. The intermediate dilation result is stored in `buffer`. """ function bothat!(out, img, buffer; dims=coords_spatial(img), r=nothing) return bothat!(out, img, strel_box(img, dims; r), buffer) end function bothat!(out, img, se, buffer) closing!(out, img, se, buffer) @. out = out - img return out end function bothat!(out::AbstractArray{<:Color3}, img, se, buffer) throw(ArgumentError("color image is not supported")) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2024
# From https://github.com/JuliaImages/ImageMorphology.jl/blob/master/src/ops/closing.jl """ closing(img; dims=coords_spatial(img), r=1) closing(img, se) Perform the morphological closing on `img`. The closing operation is defined as dilation followed by an erosion: `erode(dilate(img, se), se)`. $(_docstring_se) # Examples ```jldoctest; setup = :(using ImageMorphology) julia> img = falses(7,7); img[2, 2] = true; img[3:5, 3:5] .= true; img[4, 4] = false; img 7Γ—7 BitMatrix: 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 julia> closing(img) 7Γ—7 BitMatrix: 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 julia> closing(img, strel_diamond(img)) # # use diamond shape SE 7Γ—7 BitMatrix: 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` ## See also - [`opening!`](@ref) is the in-place version of this function. - [`closing`](@ref) is the dual operator of `opening` in the sense that `complement.(opening(img)) == closing(complement.(img))`. """ closing(img; kwargs...) = closing!(similar(img), img, similar(img); kwargs...) closing(img, se) = closing!(similar(img), img, se, similar(img)) """ closing!(out, img, buffer; [dims], [r]) closing!(out, img, se, buffer) The in-place version of [`closing`](@ref) with input image `img` and output image `out`. The intermediate dilation result is stored in `buffer`. """ function closing!(out, img, buffer; dims=coords_spatial(img), r=nothing) return closing!(out, img, strel_box(img, dims; r), buffer) end function closing!(out, img, se, buffer) dilate!(buffer, img, se) erode!(out, buffer, se) return out end function closing!(out::AbstractArray{<:Color3}, img, se, buffer) throw(ArgumentError("color image is not supported")) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2228
# From https://github.com/JuliaImages/ImageMorphology.jl/blob/master/src/ops/dilate.jl using ColorTypes const _docstring_se = """ `se` is the structuring element that defines the neighborhood of the image. See [`strel`](@ref) for more details. If `se` is not specified, then it will use the [`strel_box`](@ref) with an extra keyword `dims` to control the dimensions to filter, and half-size `r` to control the diamond size. """ """ dilate(img; dims=coords_spatial(img), r=1) dilate(img, se) Perform a max-filter over the neighborhood of `img`, specified by structuring element `se`. $(_docstring_se) # Examples ```jldoctest; setup = :(using ImageMorphology) julia> img = falses(5, 5); img[3, [2, 4]] .= true; img 5Γ—5 BitMatrix: 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 julia> dilate(img) 5Γ—5 BitMatrix: 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 julia> dilate(img; dims=1) 5Γ—5 BitMatrix: 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 0 0 0 0 julia> dilate(img, strel_diamond(img)) # use diamond shape SE 5Γ—5 BitMatrix: 0 0 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 0 1 0 0 0 0 0 0 ``` ## See also - [`dilate!`](@ref) is the in-place version of this function - [`erode`](@ref) is the dual operator of `dilate` in the sense that `complement.(dilate(img)) == erode(complement.(img))`. !!! note "symmetricity" If `se` is symmetric with repsect to origin, i.e., `se[b] == se[-b]` for any `b`, then dilation becomes the Minkowski sum: AβŠ•B={a+b|a∈A, b∈B}. """ dilate(img::AbstractArray; kwargs...) = dilate!(similar(img), img; kwargs...) dilate(img::AbstractArray, se::AbstractArray) = dilate!(similar(img), img, se) """ dilate!(out, img; [dims], [r]) dilate!(out, img, se) The in-place version of [`dilate`](@ref) with input image `img` and output image `out`. """ function dilate!(out, img; dims=coords_spatial(img), r=nothing) return dilate!(out, img, strel_box(img, dims; r)) end dilate!(out, img, se::AbstractArray) = extreme_filter!(max, out, img, se) function dilate!(out::AbstractArray{<:Color3}, img, se::AbstractArray) throw(ArgumentError("color image is not supported")) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1885
# From https://github.com/JuliaImages/ImageMorphology.jl/blob/master/src/ops/dilate.jl """ out = erode(img; dims=coords_spatial(img), r=1) out = erode(img, se) Perform a min-filter over the neighborhood of `img`, specified by structuring element `se`. $(_docstring_se) # Examples ```jldoctest; setup = :(using ImageMorphology) julia> img = trues(5, 5); img[3, [2, 4]] .= false; img 5Γ—5 BitMatrix: 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 julia> erode(img) 5Γ—5 BitMatrix: 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 julia> erode(img; dims=1) 5Γ—5 BitMatrix: 1 1 1 1 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 julia> erode(img, strel_diamond(img)) # use diamond shape SE 5Γ—5 BitMatrix: 1 1 1 1 1 1 0 1 0 1 0 0 0 0 0 1 0 1 0 1 1 1 1 1 1 ``` ## See also - [`erode!`](@ref) is the in-place version of this function - [`dilate`](@ref) is the dual operator of `erode` in the sense that `complement.(dilate(img)) == erode(complement.(img))`. !!! note "symmetricity" If `se` is symmetric with repsect to origin, i.e., `se[b] == se[-b]` for any `b`, then erosion becomes the Minkowski difference: AβŠ–B={a-b|a∈A, b∈B}. """ erode(img::AbstractArray; kwargs...) = erode!(similar(img), img; kwargs...) erode(img::AbstractArray, se::AbstractArray) = erode!(similar(img), img, se) """ erode!(out, img; [dims], [r]) erode!(out, img, se) The in-place version of [`erode`](@ref) with input image `img` and output image `out`. """ function erode!(out, img; dims=coords_spatial(img), r=nothing) return erode!(out, img, strel_box(img, dims; r)) end erode!(out, img, se::AbstractArray) = extreme_filter!(min, out, img, se) function erode!(out::AbstractArray{<:Color3}, img, se::AbstractArray) throw(ArgumentError("color image is not supported")) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
21546
const MAX_OR_MIN = Union{typeof(max),typeof(min)} """ extreme_filter(f, A; r=1, [dims]) -> out extreme_filter(f, A, Ξ©) -> out Filter the array `A` using select function `f(x, y)` for each Ξ©-neighborhood. The name "extreme" comes from the fact that typical select function `f` choice is `min` and `max`. For each pixel `p` in `A`, the select function `f` is applied to its Ξ©-neighborhood iteratively in a `f(...(f(f(A[p], A[p+Ξ©[1]]), A[p+Ξ©[2]]), ...)` manner. For instance, in the 1-dimensional case, `out[p] = f(f(A[p], A[p-1]), A[p+1])` for each `p` is the default behavior. The Ξ©-neighborhood is defined by the `dims` or `Ξ©` argument. The `r` and `dims` keywords specifies the box shape neighborhood `Ξ©` using [`strel_box`](@ref). The `Ξ©` is also known as structuring element (SE), it can be either displacement offsets or bool array mask, please refer to [`strel`](@ref) for more details. # Examples ```jldoctest extreme_filter; setup=:(using ImageMorphology) julia> M = [4 6 5 3 4; 8 6 9 4 8; 7 8 4 9 6; 6 2 2 1 7; 1 6 5 2 6] 5Γ—5 Matrix{$Int}: 4 6 5 3 4 8 6 9 4 8 7 8 4 9 6 6 2 2 1 7 1 6 5 2 6 julia> extreme_filter(max, M) # max-filter using 4 direct neighbors along both dimensions 5Γ—5 Matrix{$Int}: 8 9 9 9 8 8 9 9 9 9 8 9 9 9 9 8 8 9 9 9 6 6 6 7 7 julia> extreme_filter(max, M; dims=1) # max-filter along the first dimension (column) 5Γ—5 Matrix{$Int}: 8 6 9 4 8 8 8 9 9 8 8 8 9 9 8 7 8 5 9 7 6 6 5 2 7 ``` `Ξ©` can be either an `AbstractArray{Bool}` mask array with `true` element indicating connectivity, or a `AbstractArray{<:CartesianIndex}` array with each element indicating the displacement offset to its center element. ```jldoctest extreme_filter julia> Ξ©_mask = centered(Bool[1 1 0; 1 1 0; 1 0 0]) # custom neighborhood in mask format 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 1 1 0 1 1 0 1 0 0 julia> out = extreme_filter(max, M, Ξ©_mask) 5Γ—5 Matrix{$Int}: 4 8 6 9 4 8 8 9 9 9 8 8 9 9 9 7 8 8 9 9 6 6 6 5 7 julia> Ξ©_offsets = strel(CartesianIndex, Ξ©_mask) # custom neighborhood as displacement offset 4-element Vector{CartesianIndex{2}}: CartesianIndex(-1, -1) CartesianIndex(0, -1) CartesianIndex(1, -1) CartesianIndex(-1, 0) julia> out == extreme_filter(max, M, Ξ©_offsets) # both versions work equivalently true ``` See also the in-place version [`extreme_filter!`](@ref). Another function in ImageFiltering package `ImageFiltering.mapwindow` provides similar functionality. """ function extreme_filter(f, A; r=nothing, dims=coords_spatial(A)) return extreme_filter(f, A, strel_box(A, dims; r)) end extreme_filter(f, A, Ξ©::AbstractArray) = extreme_filter!(f, similar(A), A, Ξ©) """ extreme_filter!(f, out, A; [r], [dims]) extreme_filter!(f, out, A, Ξ©) The in-place version of [`extreme_filter`](@ref) where `out` is the output array that gets modified. """ function extreme_filter!(f, out, A; r=nothing, dims=coords_spatial(A)) return extreme_filter!(f, out, A, strel_box(A, dims; r)) end function extreme_filter!(f, out, A, Ξ©) axes(out) == axes(A) || throw(DimensionMismatch("axes(out) must match axes(A)")) require_select_function(f, eltype(A)) return _extreme_filter!(strel_type(Ξ©), f, out, A, Ξ©) end _extreme_filter!(::MorphologySE, f, out, A, Ξ©) = _extreme_filter_generic!(f, out, A, Ξ©) _extreme_filter!(::SEDiamond, f, out, A, Ξ©) = _extreme_filter_diamond!(f, out, A, Ξ©) function _extreme_filter!( ::MorphologySE, f::MAX_OR_MIN, out, A::AbstractArray{T}, Ξ© ) where {T<:Union{Gray{Bool},Bool}} # NOTE(johnnychen94): empirical choice based on benchmark results (intel i9-12900k) true_ratio = gray(sum(A) / length(A)) # this usually takes <2% of the time but gives a pretty good hint to do the decision true_ratio == 1 && (out .= true; return out) true_ratio == 0 && (out .= false; return out) use_bool = prod(strel_size(Ξ©)) > 9 || (f === max && true_ratio > 0.8) || (f === min && true_ratio < 0.2) if use_bool return _extreme_filter_bool!(f, out, A, Ξ©) else return _extreme_filter_generic!(f, out, A, Ξ©) end end function _extreme_filter!( ::SEDiamond, f::MAX_OR_MIN, out, A::AbstractArray{T}, Ξ© ) where {T<:Union{Gray{Bool},Bool}} rΞ© = strel_size(Ξ©) .Γ· 2 if ndims(A) == 2 && all(rΞ©[1] .== rΞ©) # super fast implementation and wins in all cases return _extreme_filter_diamond!(f, out, A, Ξ©) end # NOTE(johnnychen94): empirical choice based on benchmark results (intel i9-12900k) true_ratio = gray(sum(A) / length(A)) # this usually takes <2% of the time but gives a pretty good hint to do the decision true_ratio == 1 && (out .= true; return out) true_ratio == 0 && (out .= false; return out) use_bool = (f === max && true_ratio > 0.4) || (f === min && true_ratio < 0.6) if use_bool return _extreme_filter_bool!(f, out, A, Ξ©) else return _extreme_filter_diamond!(f, out, A, Ξ©) end end function _extreme_filter!( ::SEBox, f::MAX_OR_MIN, out, A::AbstractArray{T}, Ξ© ) where {T<:Union{Gray{Bool},Bool}} rΞ© = strel_size(Ξ©) .Γ· 2 if ndims(A) == 2 && all(rΞ©[1] .== rΞ©) # super fast implementation and wins in all cases return _extreme_filter_box!(f, out, A, Ξ©) end return _extreme_filter_bool!(f, out, A, Ξ©) end ### # Implementation details ### function _extreme_filter_generic!(f, out, A, Ξ©) @debug "call the generic `extreme_filter` implementation" fname = _extreme_filter_generic! Ξ© = strel(CartesianIndex, Ξ©) Ξ΄ = CartesianIndex(strel_size(Ξ©) .Γ· 2) R = CartesianIndices(A) R_inner = (first(R) + Ξ΄):(last(R) - Ξ΄) # NOTE(johnnychen94): delibrately duplicate the kernel codes here for inner loop and # boundary loop, because keeping the big function body allows Julia to do further # optimization and thus significantly improves the overall performance. @inbounds for p in R_inner # for interior points, boundary check is unnecessary s = A[p] for o in Ξ© v = A[p + o] s = f(s, v) end out[p] = s end @inbounds for p in EdgeIterator(R, R_inner) # for edge points, skip if the offset exceeds the boundary s = A[p] for o in Ξ© q = p + o checkbounds(Bool, A, q) || continue s = f(s, A[q]) end out[p] = s end return out end # optimized implementation for SEDiamond -- a typical case of separable filter function _extreme_filter_diamond!(f, out, A, Ξ©::SEDiamondArray{N}) where {N} rΞ© = strel_size(Ξ©) .Γ· 2 if N == 2 && f isa MAX_OR_MIN && all(rΞ©[1] .== rΞ©) iter = rΞ©[1] return _extreme_filter_diamond_2D!(f, out, A, iter) else return _extreme_filter_diamond_generic!(f, out, A, Ξ©) end end function _extreme_filter_diamond_generic!(f, out, A, Ξ©::SEDiamondArray) @debug "call the optimized `extreme_filter` implementation for SEDiamond SE" fname = _extreme_filter_diamond! rΞ© = strel_size(Ξ©) .Γ· 2 r = maximum(rΞ©) # To avoid the result affected by loop order, we need two arrays src = (out === A) || (r > 1) ? copy(A) : A out .= src # applying radius=r filter is equivalent to applying radius=1 filter r times for i in 1:r Ξ© = strel_diamond(A, Ξ©.dims) rΞ© = strel_size(Ξ©) .Γ· 2 inds = axes(A) for d in 1:ndims(A) # separately apply to each dimension if size(out, d) == 1 || rΞ©[d] == 0 continue end Rpre = CartesianIndices(inds[1:(d - 1)]) Rpost = CartesianIndices(inds[(d + 1):end]) _extreme_filter_C2!(f, out, src, Rpre, inds[d], Rpost) end if r > 1 && i < r src .= out end end return out end # fast version for C2 connectivity along each dimension @noinline function _extreme_filter_C2!(f, dst, src, Rpre, inds, Rpost) # manually unroll the loop for r=1 case # for r>1 case, it is equivalently to apply r times @inbounds for Ipost in Rpost, Ipre in Rpre # loop inner region for i in (first(inds) + 1):(last(inds) - 1) a1 = src[Ipre, i - 1, Ipost] a2 = dst[Ipre, i, Ipost] a3 = src[Ipre, i + 1, Ipost] dst[Ipre, i, Ipost] = f(f(a1, a2), a3) end # process two edge points i = first(inds) a2 = dst[Ipre, i, Ipost] a3 = src[Ipre, i + 1, Ipost] dst[Ipre, i, Ipost] = f(a2, a3) i = last(inds) a1 = src[Ipre, i - 1, Ipost] a2 = dst[Ipre, i, Ipost] dst[Ipre, i, Ipost] = f(a1, a2) end return dst end # Shift vector of size N up or down by 1 accorded to dir, pad with v const SafeArrayTypes{T,N,NA} = Union{Array{T,N},Base.SubArray{T,N,Array{T,NA}}} function _unsafe_padded_copyto!( dest::SafeArrayTypes{T,1}, src::SafeArrayTypes{T,1}, dir, N, v ) where {T} # ptr level optimized implementation for Real types # short-circuit all check so unsafe if dir unsafe_store!(pointer(dest), v) unsafe_copyto!(pointer(dest, 2), pointer(src, 1), N - 1) else unsafe_copyto!(pointer(dest, 1), pointer(src, 2), N - 1) unsafe_store!(pointer(dest), v, N) end return dest end function _unsafe_padded_copyto!(dest::AbstractVector, src::AbstractVector, dir, N, v) if dir dest[begin] = v copyto!(dest, 2, src, 1, N - 1) else dest[end] = v copyto!(dest, 1, src, 2, N - 1) end return dest end # ptr level optimized implementation for Real types # short-circuit all check # call LoopVectorization directly function _unsafe_shift_arith!( f::MAX_OR_MIN, out::AbstractVector, tmp::AbstractVector, tmp2::AbstractVector, A::AbstractVector, ) #tmp external to reuse external allocation if f === min padd = typemax(eltype(out)) else padd = typemin(eltype(out)) end N = length(out) #in src = [1,2,3,4], padd, N=4 #out tmp = [padd,1,2,3] #out tmp2 = [1,2,3,padd] _unsafe_padded_copyto!(tmp, A, true, N, padd) _unsafe_padded_copyto!(tmp2, A, false, N, padd) @turbo warn_check_args = false for i in eachindex(out, A, tmp, tmp2) out[i] = f(f(A[i], tmp[i]), tmp2[i]) end return out end @static if Sys.WORD_SIZE == 64 # optimized `extreme_filter` implementation for SEDiamond SE and 2D images # Similar approach could be found in # Ε½laus, Danijel & Mongus, Domen. (2018). In-place SIMD Accelerated Mathematical Morphology. 76-79. 10.1145/3206157.3206176. # see https://www.researchgate.net/publication/325480366_In-place_SIMD_Accelerated_Mathematical_Morphology function _extreme_filter_diamond_2D!( f::MAX_OR_MIN, out::AbstractArray{T}, A, iter ) where {T} @debug "call the AVX-enabled `extreme_filter` implementation for 2D SEDiamond" fname = _extreme_filter_diamond_2D! out_actual = out out = OffsetArrays.no_offset_view(out) A = OffsetArrays.no_offset_view(A) src = if (out === A) || (iter > 1) # To avoid the result affected by loop order, we need two arrays T.(A) elseif eltype(A) != T # To avoid incorrect result, we need to ensure the eltypes are the same # https://github.com/JuliaImages/ImageMorphology.jl/issues/104 T.(A) else A end # NOTE(johnnychen94): we don't need to do `out .= src` here because it is write-only; # all values are generated from the read-only `src`. # LoopVectorization currently doesn't understand Gray and N0f8 types, thus we # reinterpret to its raw data type UInt8 src = rawview(channelview(src)) out = rawview(channelview(out)) # creating temporaries ySize, xSize = size(A) tmp = similar(out, eltype(out), ySize) tmp2 = similar(tmp) tmp3 = similar(tmp) # applying radius=r filter is equivalent to applying radius=1 filter r times for i in 1:iter # NOTE(johnnychen94): this implementation is essentially equivalent to the # following loop. Here we buffer the getindex to further improve the performance # by explicitly introducing SIMD buffers. # for y in 2:(size(src, 2) - 1), x in 2:(size(src, 1) - 1) # tmp = f(f(src[x, y], src[x - 1, y]), src[x + 1, y]) # out[x, y] = f(f(tmp, src[x, y - 1]), src[x, y + 1]) # end #compute first edge column #translate to clipped connection, x neighborhood of interest, ? neighborhood we don't care, . center # x ? # . x # x ? viewprevious = view(src, :, 1) # dilate/erode col 1 _unsafe_shift_arith!(f, tmp2, tmp, tmp3, viewprevious) viewnext = view(src, :, 2) viewout = view(out, :, 1) # inf/sup between dilate/erode col 1 0 and col 2 LoopVectorization.vmap!(f, viewout, viewnext, tmp2) #next->current viewcurrent = view(src, :, 2) for c in 3:xSize # viewprevious c-2 # viewcurrent c-1 # viewnext c # ? x ? # x . x # ? x ? viewout = view(out, :, c - 1) viewnext = view(src, :, c) # dilate(x-1)/erode(x-1) _unsafe_shift_arith!(f, tmp2, tmp, tmp3, viewcurrent) @turbo warn_check_args = false for i in eachindex(viewout, viewprevious, tmp2) #sup(x-2,dilate(x-1)),inf(x-2,erode(x-1)) #sup(sup(x-2,dilate(x-1),x) || inf(inf(x-2,erode(x-1),x) viewout[i] = f(f(viewprevious[i], tmp2[i]), viewnext[i]) end #current->previous viewprevious = view(src, :, c - 1) #next->current viewcurrent = view(src, :, c) end #end last column #translate to clipped connection # ? x # x . # ? x # dilate/erode col x viewout = view(out, :, xSize) _unsafe_shift_arith!(f, tmp2, tmp, tmp3, viewcurrent) LoopVectorization.vmap!(f, viewout, tmp2, viewprevious) if iter > 1 && i < iter src .= out end end return out_actual end else # FIXME(johnnychen94): unknown segfault happens to 32bit machine # https://github.com/JuliaImages/ImageMorphology.jl/pull/106 function _extreme_filter_diamond_2D!(f::MAX_OR_MIN, out::AbstractArray, A, iter) return _extreme_filter_diamond_generic!(f, out, A, strel_diamond(A; r=iter)) end end function _extreme_filter_box!(f, out, A, Ξ©::SEBoxArray{N}) where {N} rΞ© = strel_size(Ξ©) .Γ· 2 if N == 2 && f isa MAX_OR_MIN && all(rΞ©[1] .== rΞ©) iter = rΞ©[1] return _extreme_filter_box_2D!(f, out, A, iter) else return _extreme_filter_generic!(f, out, A, Ξ©) end end @static if Sys.WORD_SIZE == 64 # optimized `extreme_filter` implementation for SEBox SE and 2D images # Similar approach could be found in # Ε½laus, Danijel & Mongus, Domen. (2018). In-place SIMD Accelerated Mathematical Morphology. 76-79. 10.1145/3206157.3206176. # see https://www.researchgate.net/publication/325480366_In-place_SIMD_Accelerated_Mathematical_Morphology function _extreme_filter_box_2D!( f::MAX_OR_MIN, out::AbstractArray{T}, A, iter ) where {T} @debug "call the AVX-enabled `extreme_filter` implementation for 2D SEBox" fname = _extreme_filter_box_2D! out_actual = out out = OffsetArrays.no_offset_view(out) A = OffsetArrays.no_offset_view(A) src = if (out === A) || (iter > 1) # To avoid the result affected by loop order, we need two arrays T.(A) elseif eltype(A) != T # To avoid incorrect result, we need to ensure the eltypes are the same # https://github.com/JuliaImages/ImageMorphology.jl/issues/104 T.(A) else A end # NOTE(johnnychen94): we don't need to do `out .= src` here because it is write-only; # all values are generated from the read-only `src`. # LoopVectorization currently doesn't understand Gray and N0f8 types, thus we # reinterpret to its raw data type UInt8 src = rawview(channelview(src)) out = rawview(channelview(out)) #creating temporaries ySize, xSize = size(A) tmp = similar(out, eltype(out), ySize) tmp2 = similar(tmp) tmp3 = similar(tmp) tmp4 = similar(tmp) tmp5 = similar(tmp) # applying radius=r filter is equivalent to applying radius=1 filter r times for i in 1:iter #compute first edge column #translate to clipped connection, x neighborhood of interest, ? neighborhood we don't care, . center # x x # . x # x x viewprevious = view(src, :, 1) # dilate/erode col 1 _unsafe_shift_arith!(f, tmp2, tmp, tmp5, viewprevious) viewnext = view(src, :, 2) viewout = view(out, :, 1) # dilate/erode col 2 _unsafe_shift_arith!(f, tmp3, tmp, tmp5, viewnext) #sup(dilate col 1,dilate col 0) or inf(erode col 1,erode col 0) LoopVectorization.vmap!(f, viewout, tmp3, tmp2) #next->current viewcurrent = view(src, :, 2) for c in 3:xSize # Invariant of the loop # temp2 contains dilation/erosion of previous col x-2 # temp3 contains dilation/erosion of current col x-1 # temp4 contains dilation/erosion of next col ie x # viewprevious c-2 # viewcurrent c-1 # viewnext c # x x x # x . x # x x x viewout = view(out, :, c - 1) viewnext = view(src, :, c) # dilate(x)/erode(x) _unsafe_shift_arith!(f, tmp4, tmp, tmp5, viewnext) @turbo warn_check_args = false for i in eachindex(viewout, tmp4, tmp3, tmp2) #sup(x-2,dilate(x-1)),inf(x-2,erode(x-1)) #sup(dilate(x-2),dilate(x-1),dilate(y)) or inf(erode(x-2),erode(x-1),erode(x)) viewout[i] = f(f(tmp2[i], tmp3[i]), tmp4[i]) end #swap tmp4, tmp3 = tmp3, tmp4 tmp4, tmp2 = tmp2, tmp4 end #end last column #translate to clipped connection # x x # x . # x x # dilate/erode col x viewout = view(out, :, xSize) _unsafe_shift_arith!(f, tmp4, tmp, tmp5, viewcurrent) LoopVectorization.vmap!(f, viewout, tmp2, tmp3) if iter > 1 && i < iter src .= out end end return out_actual end else # FIXME(johnnychen94): unknown segfault happens to 32bit machine # https://github.com/JuliaImages/ImageMorphology.jl/pull/106 function _extreme_filter_box_2D!(f::MAX_OR_MIN, out::AbstractArray, A, iter) return _extreme_filter_generic!(f, out, A, strel_box(A; r=iter)) end end # optimized implementation for Bool inputs with max/min select function # 1) use &&, || instead of max, min # 2) short-circuit the result to avoid unnecessary indexing and computation function _extreme_filter_bool!(f, out, A::AbstractArray{Bool}, Ξ©) @debug "call the optimized max/min `extreme_filter` implementation for boolean array" fname = _extreme_filter_bool! Ξ© = strel(CartesianIndex, Ξ©) Ξ΄ = CartesianIndex(strel_size(Ξ©) .Γ· 2) R = CartesianIndices(A) R_inner = (first(R) + Ξ΄):(last(R) - Ξ΄) select = _fast_select(f) @inbounds for p in R_inner out[p] = select(A, p, Ξ©) end for p in EdgeIterator(R, R_inner) out[p] = select(A, p, Ξ©) end return out end function _extreme_filter_bool!(f, out, A::AbstractArray{Gray{Bool}}, Ξ©) return _extreme_filter_bool!(f, out, reinterpret(Bool, A), Ξ©) end _fast_select(::typeof(max)) = _maximum_fast _fast_select(::typeof(min)) = _minimum_fast Base.@propagate_inbounds function _maximum_fast(A::AbstractArray{Bool}, p, Ξ©) rst = A[p] for o in Ξ© # the complicated control flow ruins the SIMD and thus for small Ξ©, the performance # will be worse q = p + o @boundscheck checkbounds(Bool, A, q) || continue x = A[q] x && return true rst = rst || x end return rst end Base.@propagate_inbounds function _minimum_fast(A::AbstractArray{Bool}, p, Ξ©) rst = A[p] for o in Ξ© # the complicated control flow ruins the SIMD and thus for small Ξ©, the performance # will be worse q = p + o @boundscheck checkbounds(Bool, A, q) || continue x = A[q] x || return false rst = rst && x end return rst end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1841
# From https://github.com/JuliaImages/ImageMorphology.jl/pull/119 """ fill_holes(img; [dims]) fill_holes(img; se) Fill the holes in image 'img'. Could be binary or grascale The `dims` keyword is used to specify the dimension to process by constructing the box shape structuring element [`strel_box(img; dims)`](@ref strel_box). For generic structuring element, the half-size is expected to be either `0` or `1` along each dimension. The output has the same type as input image """ function fill_holes(img; dims=coords_spatial(img)) return fill_holes(img, strel_box(img, dims)) end function fill_holes(img, se) return fill_holes!(similar(img), img, se) end function fill_holes!(out, img; dims=coords_spatial(img)) return fill_holes!(out, img, strel_box(img, dims)) end function fill_holes!(out, img, se) return _fill_holes!(out, img, se) end function _fill_holes!(out, img, se) N = ndims(img) axes(out) == axes(img) || throw(DimensionMismatch("images should have the same axes")) se_size = strel_size(se) if length(se_size) != N msg = "the input structuring element is not for $N dimensional array, instead it is for $(length(se_size)) dimensional array" throw(DimensionMismatch(msg)) end if !all(x -> in(x, (1, 3)), strel_size(se)) msg = "structuring element with half-size larger than 1 is invalid" throw(DimensionMismatch(msg)) end tmp = similar(img) # fill marker image with max fill!(tmp, typemax(eltype(img))) # fill borders with 0 dimensions = size(tmp) outerrange = CartesianIndices(map(i -> 1:i, dimensions)) innerrange = CartesianIndices(map(i -> (1 + 1):(i - 1), dimensions)) for i in EdgeIterator(outerrange, innerrange) tmp[i] = 0 end return mreconstruct!(erode, out, tmp, img, se) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
6710
""" mreconstruct(op, marker, mask; [dims]) mreconstruct(op, marker, mask, se) Morphological reconstruction of `marker` image by operation `op`. The `op` argument is either `erode` or `dilate`, indicating reconstruction by erosion or by dilation. The `mask` argument has the same shape as `marker` and is used to restrict the output value range. The `dims` keyword is used to specify the dimension to process by constructing the box shape structuring element [`strel_box(marker; dims)`](@ref strel_box). For generic structuring element, the half-size is expected to be either `0` or `1` along each dimension. By definition, the reconstruction is done by applying `marker = select.(op(marker; dims), mask)` repeatly until reaching stability. For dilation `op, select = dilate, min` and for erosion `op, select = erode, max`. # Examples ```jldoctest; setup=:(using ImageMorphology) julia> marker = [0 0 0 0 0; 0 9 0 0 0; 0 0 0 0 0; 0 0 0 5 0; 0 0 0 0 0; 0 9 0 0 0] 6Γ—5 Matrix{$Int}: 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 9 0 0 0 julia> mask = [9 0 0 0 0; 0 8 7 1 0; 0 9 0 4 0; 0 0 0 4 0; 0 0 6 5 6; 0 0 9 8 9] 6Γ—5 Matrix{$Int}: 9 0 0 0 0 0 8 7 1 0 0 9 0 4 0 0 0 0 4 0 0 0 6 5 6 0 0 9 8 9 julia> mreconstruct(dilate, marker, mask) # equivalent to underbuild(marker, mask) 6Γ—5 Matrix{$Int}: 8 0 0 0 0 0 8 7 1 0 0 8 0 4 0 0 0 0 4 0 0 0 4 4 4 0 0 4 4 4 ``` # See also The inplace version of this function is [`mreconstruct!`](@ref). There are also aliases [`underbuild`](@ref) for reconstruction by dilation and [`overbuild`](@ref) for reconstruction by erosion. # References - [1] L. Vincent, β€œMorphological grayscale reconstruction in image analysis: applications and efficient algorithms,” IEEE Trans. on Image Process., vol. 2, no. 2, pp. 176–201, Apr. 1993, doi: 10.1109/83.217222. - [2] P. Soille, Morphological Image Analysis. Berlin, Heidelberg: Springer Berlin Heidelberg, 2004. doi: 10.1007/978-3-662-05088-0. """ function mreconstruct(op, marker, mask; dims=coords_spatial(mask)) return mreconstruct(op, marker, mask, strel_box(marker, dims)) end function mreconstruct(op, marker, mask, se) axes(marker) == axes(mask) || throw(DimensionMismatch("`marker` and `mask` should have the same axes")) # This ensures that we support mixed types, e.g. marker as Matrix{Gray{N0f8}} and mask as Matrix{Float64} OT = ImageCore.MosaicViews.promote_wrapped_type(eltype(marker), eltype(mask)) return mreconstruct!(op, similar(mask, OT), marker, mask, se) end """ mreconstruct!(op, out, marker, mask; [dims]) The in-place version of morphological reconstruction [`mreconstruct`](@ref). """ function mreconstruct!(op, out, marker, mask; dims=coords_spatial(mask)) return mreconstruct!(op, out, marker, mask, strel_box(marker, dims)) end function mreconstruct!(op, out, marker, mask, se) return _mreconstruct!(_prepare_reconstruct_ops(op), out, marker, mask, se) end function _prepare_reconstruct_ops(::op) where {op} return error("operation `$(op.instance)` is not supported for `mreconstruct`") end _prepare_reconstruct_ops(::typeof(dilate)) = (max, min) _prepare_reconstruct_ops(::typeof(erode)) = (min, max) @inline _should_enqueue(::typeof(max)) = < @inline _should_enqueue(::typeof(min)) = > # Single-CPU version, references are [1] and section 6.2 of [2] function _mreconstruct!((select_se, select_marker), out, marker, mask, se) N = ndims(marker) axes(out) == axes(marker) == axes(mask) || throw(DimensionMismatch("images should have the same axes")) require_select_function(select_se, eltype(mask), eltype(marker)) require_select_function(select_marker, eltype(mask), eltype(marker)) # For generic structuring element, the half-size should to be either `0` or `1` along # each dimension. See also section 6.2.3 of [2]. se_size = strel_size(se) if length(se_size) != N msg = "the input structuring element is not for $N dimensional array, instead it is for $(length(se_size)) dimensional array" throw(DimensionMismatch(msg)) end if !all(x -> in(x, (1, 3)), strel_size(se)) # center cropping the input se using [-1:1, -1:1, ...] inds_str = join(ntuple(_ -> 3, N), "Γ—") @warn "structuring element with half-size larger than 1 is invalid, only the center $inds_str values are used" inds = ntuple(i -> (-1:1), N) se = centered(strel(Bool, strel(CartesianIndex, se))[inds...]) end se = strel(CartesianIndex, se) # The original algorithm assume that the marker < mask for erosion and marker > mask for # dilation. This assertion is not always true in practice. @. out = select_marker(marker, mask) queue = Queue{CartesianIndex{N}}() se = strel(CartesianIndex, se) upper_se, lower_se = strel_split(se) # NOTE we could pad the array with -Inf to speedup forward/backward scan # forward scan R = CartesianIndices(axes(marker)) for i in R @inbounds curr_val = out[i] for Ξ”i in upper_se # examine neighborhoods ii = i + Ξ”i if checkbounds(Bool, R, ii) #check that we are in the image @inbounds curr_val = select_se(curr_val, out[ii]) end end @inbounds out[i] = select_marker(curr_val, mask[i]) end # backward scan should_enqueue = _should_enqueue(select_se) for i in reverse(R) @inbounds curr_val = out[i] for Ξ”i in lower_se # examine neighborhoods ii = i + Ξ”i if checkbounds(Bool, R, ii) #check that we are in the image @inbounds curr_val = select_se(curr_val, out[ii]) end end @inbounds out[i] = select_marker(curr_val, mask[i]) for Ξ”i in lower_se # examine neighborhoods ii = i + Ξ”i if checkbounds(Bool, R, ii) #check that we are in the image @inbounds if should_enqueue(out[ii], out[i]) && should_enqueue(out[ii], mask[ii]) enqueue!(queue, i) end end end end # Loop until all pixel have been examined while !isempty(queue) curr_idx = dequeue!(queue) for Ξ”i in se # examine neighborhoods ii = curr_idx + Ξ”i if checkbounds(Bool, R, ii) #check that we are in the image @inbounds if should_enqueue(out[ii], out[curr_idx]) && mask[ii] != out[ii] out[ii] = select_marker(out[curr_idx], mask[ii]) enqueue!(queue, ii) end end end end return out end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1931
""" opening(img; dims=coords_spatial(img), r=1) opening(img, se) Perform the morphological opening on `img`. The opening operation is defined as erosion followed by a dilation: `dilate(erode(img, se), se)`. $(_docstring_se) # Examples ```jldoctest; setup = :(using ImageMorphology) julia> img = trues(7,7); img[2, 2] = false; img[3:5, 3:5] .= false; img[4, 4] = true; img 7Γ—7 BitMatrix: 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 julia> opening(img) 7Γ—7 BitMatrix: 0 0 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 julia> opening(img, strel_diamond(img)) # use diamond shape SE 7Γ—7 BitMatrix: 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ``` ## See also - [`opening!`](@ref) is the in-place version of this function. - [`closing`](@ref) is the dual operator of `opening` in the sense that `complement.(opening(img)) == closing(complement.(img))`. """ opening(img; kwargs...) = opening!(similar(img), img, similar(img); kwargs...) opening(img, se) = opening!(similar(img), img, se, similar(img)) """ opening!(out, img, buffer; [dims], [r]) opening!(out, img, se, buffer) The in-place version of [`opening`](@ref) with input image `img` and output image `out`. The intermediate erosion result is stored in `buffer`. """ function opening!(out, img, buffer; dims=coords_spatial(img), r=nothing) return opening!(out, img, strel_box(img, dims; r), buffer) end function opening!(out, img, se, buffer) erode!(buffer, img, se) dilate!(out, buffer, se) return out end function opening!(out::AbstractArray{<:Color3}, img, se, buffer) throw(ArgumentError("color image is not supported")) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
5407
""" strel([T], X::AbstractArray) Convert structuring element (SE) `X` to appropriate presentation format with element type `T`. This is a useful tool to generate SE that most ImageMorphology functions understand. ImageMorphology currently supports two commonly used representations: - `T=CartesianIndex`: offsets to its center point. The output type is `Vector{CartesianIndex{N}}`. - `T=Bool`: connectivity mask where `true` indicates connected to its center point. The output type is `BitArray{N}`. ```jldoctest; setup=:(using ImageMorphology) julia> se_mask = centered(Bool[1 1 0; 1 1 0; 0 0 0]) # connectivity mask 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 1 1 0 1 1 0 0 0 0 julia> se_offsets = strel(CartesianIndex, se_mask) # displacement offsets to its center point 3-element Vector{CartesianIndex{2}}: CartesianIndex(-1, -1) CartesianIndex(0, -1) CartesianIndex(-1, 0) julia> se = strel(Bool, se_offsets) 3Γ—3 OffsetArray(::BitMatrix, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 1 1 0 1 1 0 0 0 0 ``` See also [`strel_diamond`](@ref) and [`strel_box`](@ref) for SE constructors for two special cases. """ function strel end strel(se) = strel(strel_type(se), se) # convenient user interface without exporting MorphologySE function strel(::Type{ET}, se::AbstractArray) where {ET<:CartesianIndex} return strel(SEOffset{strel_ndims(se)}(), se) end strel(::Type{ET}, se::AbstractArray) where {ET<:Bool} = strel(SEMask{strel_ndims(se)}(), se) # conversion between different SE arrays function strel(SET::MorphologySE, se::T) where {T} strel_type(se) == SET || error("unsupported conversion from type $T to $SET") return se end function strel(::SEMask{N}, offsets::AbstractArray{CartesianIndex{N}}) where {N} isempty(offsets) && return centered(trues(ntuple(_ -> 1, N))) mn, mx = extrema(offsets) r = ntuple(N) do i max(abs(mn.I[i]), abs(mx.I[i])) end sz = @. 2r + 1 se = centered(falses(sz)) se[offsets] .= true se[zero(eltype(offsets))] = true # always set center point to true return centered(BitArray(OffsetArrays.no_offset_view(se))) end strel(::SEMask{N}, mask::AbstractArray{Bool,N}) where {N} = mask function strel(::SEOffset{N}, connectivity::AbstractArray{Bool,N}) where {N} all(isodd, size(connectivity)) || error("`connectivity` must be odd-sized") ax = axes(connectivity) is_symmetric = all(r -> first(r) == -last(r), ax) if !is_symmetric && all(first.(axes(connectivity)) .== 1) # To keep consistent with the "kernel" concept in ImageFiltering, we require # the connectivity mask to be centered as well. # This is a perhaps permanent depwarn to throw friendly message to the user # if they're used to use, e.g., `trues(3, 3)` as the input. msg = "connectivity mask is expected to be a centered bool array" hint = "Do you mean `centered(connectivity)`" Base.depwarn("$msg. $hint?", :strel) elseif !is_symmetric throw(ArgumentError("`connectivity` must be symmetric bool array")) end connectivity = centered(connectivity) # always skip center point return [i for i in CartesianIndices(connectivity) if connectivity[i] && !iszero(i)] end """ strel_type(x) Infer the structuring element type for `x`. !!! note "developer note" This function is used to dispatch special SE types, e.g., [`SEBoxArray`](@ref), to optimized implementation of particular morphology filter. In this sense it is required for custom SE array types to define this method. """ strel_type(se::MorphologySE) = se strel_type(::AbstractArray{Bool,N}) where {N} = SEMask{N}() strel_type(::AbstractVector{CartesianIndex{N}}) where {N} = SEOffset{N}() strel_type(::CartesianIndices{N}) where {N} = SEOffset{N}() strel_type(::T) where {T} = error("invalid structuring element data type: $T") """ strel_size(x) Calculate the minimal block size that contains the structuring element. The result will be a tuple of odd integers. ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> se = strel_diamond((5, 5); r=1) 5Γ—5 SEDiamondArray{2, 2, UnitRange{$Int}, 0} with indices -2:2Γ—-2:2: 0 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 1 0 0 0 0 0 0 0 julia> strel_size(se) # is not (5, 5) (3, 3) julia> strel(Bool, strel(CartesianIndex, se)) # because it only checks the minimal enclosing block 3Γ—3 OffsetArray(::BitMatrix, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 0 1 0 1 1 1 0 1 0 julia> se = [CartesianIndex(1, 1), CartesianIndex(-2, -2)]; julia> strel_size(se) # is not (4, 4) (5, 5) julia> strel(Bool, se) # because the connectivity mask has to be odd size 5Γ—5 OffsetArray(::BitMatrix, -2:2, -2:2) with eltype Bool with indices -2:2Γ—-2:2: 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 julia> se = strel_diamond((5, 5), (1, ); r=1) 5Γ—5 SEDiamondArray{2, 1, UnitRange{$Int}, 1} with indices -2:2Γ—-2:2: 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 julia> strel_size(se) (3, 1) ``` """ strel_size(se) = size(strel(Bool, strel(CartesianIndex, se))) """ strel_ndims(x)::Int Infer the dimension of the structuring element `x` """ strel_ndims(se) = strel_ndims(strel_type(se)) strel_ndims(::MorphologySE{N}) where {N} = N
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
4386
""" SEBox{N}(axes; [r]) The N-dimensional structuring element with all elements connected. This is a special case of [`SEMask`](@ref) that ImageMorphology algorithms might provide optimized implementation. It is recommended to use [`strel_box`](@ref) and [`strel_type`](@ref): ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> se = strel_box((3, 3)) # C8 connectivity 3Γ—3 SEBoxArray{2, UnitRange{$Int}} with indices -1:1Γ—-1:1: 1 1 1 1 1 1 1 1 1 julia> strel_type(se) SEBox{2, UnitRange{$Int}}((-1:1, -1:1), (1, 1)) julia> se = centered(collect(se)) # converted to normal centered array 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 1 1 1 1 1 1 1 1 1 julia> strel_type(se) SEMask{2}() ``` """ struct SEBox{N,R} <: MorphologySE{N} axes::NTuple{N,R} r::Dims{N} function SEBox{N,R}(axes::NTuple{N,R}, r::Dims{N}) where {N,R<:AbstractUnitRange{Int}} if !all(r -> first(r) == -last(r), axes) throw(ArgumentError("axes must be symmetric along each dimension")) end return new{N,R}(axes, r) end end function SEBox{N}(ax::NTuple{N,R}; r=map(R -> length(R) Γ· 2, ax)) where {N,R} r = r isa Integer ? ntuple(_ -> r, N) : r return SEBox{N,R}(ax, r) end """ SEBoxArray(se::SEBox) The instantiated array object of [`SEBox`](@ref SEBox). """ struct SEBoxArray{N,R<:AbstractUnitRange{Int}} <: MorphologySEArray{N} axes::NTuple{N,R} r::Dims{N} end SEBoxArray(se::SEBox{N,R}) where {N,R} = SEBoxArray{N,R}(se.axes, se.r) strel_type(A::SEBoxArray{N}) where {N} = SEBox{N}(A.axes; r=A.r) strel_size(se::SEBoxArray) = @. 1 + 2 * se.r @inline Base.axes(A::SEBoxArray) = A.axes @inline Base.size(A::SEBoxArray) = map(length, axes(A)) @inline function Base.getindex(A::SEBoxArray, inds::Int...) @inbounds for i in 1:length(inds) if abs(inds[i]) > A.r[i] return false end end return true end """ strel_box(A; r=1) strel_box(size; r=size .Γ· 2) Construct the N-dimensional structuring element (SE) with all elements in the local window connected. If image `A` is provided, then the SE size will be `(2r+1, 2r+1, ...)` with default half-size `r=1`. If `size` is provided, the default `r` will be `size .Γ· 2`. The default `dims` will be all dimensions, that is, `(1, 2, ..., length(size))`. ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> img = rand(64, 64); julia> strel_box(img) 3Γ—3 SEBoxArray{2, UnitRange{$Int}} with indices -1:1Γ—-1:1: 1 1 1 1 1 1 1 1 1 julia> strel_box(img; r=2) 5Γ—5 SEBoxArray{2, UnitRange{$Int}} with indices -2:2Γ—-2:2: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 julia> strel_box((5,5); r=(1,2)) 5Γ—5 SEBoxArray{2, UnitRange{$Int}} with indices -2:2Γ—-2:2: 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 ``` !!! note "specialization and performance" The box shape `SEBox` is a special type for which many morphology algorithms may provide efficient implementations. For this reason, if one tries to collect an `SEBoxArray` into other array types (e.g. `Array{Bool}` via `collect`), then a significant performance drop is very likely to occur. See also [`strel`](@ref) and [`strel_box`](@ref). """ function strel_box( A::AbstractArray{T,N}, dims=coords_spatial(A); r::Union{Nothing,Dims{N},Int}=nothing ) where {T,N} dims = _to_dims(Val(N), dims) sz, r = if isnothing(r) ntuple(i -> !isempty(dims) && in(i, dims) ? 3 : 1, N), 1 elseif r isa Dims{N} ntuple(i -> !isempty(dims) && in(i, dims) ? 2r[i] + 1 : 1, N), r elseif r isa Integer ntuple(i -> !isempty(dims) && in(i, dims) ? 2r + 1 : 1, N), r end return strel_box(sz, dims) end function strel_box( sz::Dims{N}, dims=ntuple(identity, N); r::Union{Nothing,Dims{N},Int}=nothing ) where {N} dims = _to_dims(Val(N), dims) all(isodd, sz) || throw(ArgumentError("size should be odd integers")) radius = if isnothing(r) ntuple(i -> !isempty(dims) && in(i, dims) ? sz[i] Γ· 2 : 0, N) elseif r isa Dims{N} r elseif r isa Integer ntuple(i -> !isempty(dims) && in(i, dims) ? r : 0, N) end ax = map(r -> (-r):r, sz .Γ· 2) return SEBoxArray(SEBox{N}(ax; r=radius)) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
4850
struct SEChain{N} <: MorphologySE{N} data::Vector{<:AbstractArray{Bool}} end struct SEChainArray{N,AT<:AbstractArray{Bool,N}} <: MorphologySEArray{N} data::Vector{<:AbstractArray{Bool}} _data::AT # pre-calculated chained data as mask function SEChainArray{N}(data::Vector{<:AbstractArray{Bool}}) where {N} # TODO(johnnychen94): defer the calculation of chained data until it is needed since # this is mainly used for visualization purposes _data = _strel_chain(data) return new{N,typeof(_data)}(data, _data) end end function SEChainArray(data::Vector{<:AbstractArray{Bool}}) data = convert(Vector, data) N = maximum(ndims.(data)) return SEChainArray{N}(data) end SEChainArray(data::Tuple) = SEChainArray(collect(data)) strel_type(A::SEChainArray{N}) where {N} = SEChain{N}(A.data) strel_size(A::SEChainArray) = size(A._data) Base.axes(A::SEChainArray) = axes(A._data) Base.size(A::SEChainArray) = size(A._data) Base.@propagate_inbounds function Base.getindex(A::SEChainArray, inds::Int...) return getindex(A._data, inds...) end """ strel_chain(A, B, ...) strel_chain(As) For structuring elements of the same dimensions, chain them together to build a bigger one. The output dimension is the same as the inputs dimensions. See also [`strel_product`](@ref) that cartesian producting each SE. !!! note "structuring element decomposition" For some morphological operations `f` such as dilation and erosion, if `se` can be decomposed into smaller ones `se1, se2, ..., seN`, then `f(img, se)` is equivalent to `f(...f(f(img, se1), se2), ..., seN)`. Because applying `f` to smaller SEs is more efficient than to the original big one, this trick is used widely in image morphology. ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> img = rand(512, 512); julia> se1, se2 = [centered(rand(Bool, 3, 3)) for _ in 1:2]; julia> se = strel_chain(se1, se2); julia> out_se = dilate(img, se); julia> out_pipe = dilate(dilate(img, se1), se2); julia> out_se[2:end-1, 2:end-1] == out_pipe[2:end-1, 2:end-1] # except for the boundary true ``` """ strel_chain(se, se_rest...) = strel_chain([se, se_rest...]) strel_chain(se_list::Vector{<:AbstractArray{T,N}}) where {T,N} = SEChainArray{N}(se_list) strel_chain(se_list::Tuple) = SEChainArray(se_list) strel_chain(se) = se function _strel_chain(data::AbstractVector{<:AbstractArray}) isempty(data) && throw(ArgumentError("data cannot be empty")) data = strel.(CartesianIndex, data) out = first(data) for i in axes(data, 1)[2:end] # TODO: preallocating the output can reduce a few more out = _simple_dilate(out, data[i]) end out = strel(Bool, strel(CartesianIndex, out)) return out end # a simple dilate function that automatically extends the boundary and dimension function _simple_dilate(A::AbstractArray{T,N}, B::AbstractArray{T,N}) where {T,N} r = strel_size(B) .Γ· 2 sz = max.(strel_size(A), strel_size(B)) out_sz = @. sz + 2r out = centered(falses(out_sz)) R = strel(CartesianIndex, A) offsets = strel(CartesianIndex, B) i = zero(eltype(R)) out[i] = true for o in offsets out[i + o] = true end for i in R out[i] = true for o in offsets out[i + o] = true end end # remove unnecessary zero boundaries return strel(CartesianIndex, out) end """ strel_product(A, B, ...) strel_product(se_list) Cartesian product of multiple structuring elements; the output dimension `ndims(out) == sum(ndims, se_list)`. See also [`strel_chain`](@ref) that chains SEs in the same dimension. ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> strel_product(strel_diamond((5, 5)), centered(Bool[1, 1, 1])) 5Γ—5Γ—3 SEChainArray{3, OffsetArrays.OffsetArray{Bool, 3, BitArray{3}}} with indices -2:2Γ—-2:2Γ—-1:1: [:, :, -1] = 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 [:, :, 0] = 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 [:, :, 1] = 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 ``` """ strel_product(se, se_rest...) = strel_product([se, se_rest...]) # TODO(johnnychen94): fix the type instability if it really matters in practice function strel_product(se_list) N = sum(ndims, se_list) new_se_list = Array{Bool,N}[] ni = 0 for se in se_list pre_ones = ntuple(_ -> one(Int), max(0, ni)) post_ones = ntuple(_ -> one(Int), max(0, N - ndims(se) - ni)) new_se = reshape(se, pre_ones..., size(se)..., post_ones...) push!(new_se_list, convert(Array{Bool,N}, new_se)) ni += ndims(se) end return SEChainArray{N}(map(centered, new_se_list)) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
6028
""" SEDiamond{N}(axes, [dims]; [r]) A (holy) trait type for the N-dimensional diamond shape structuring element. This is a special case of [`SEMask`](@ref SEMask) that ImageMorphology algorithms might provide optimized implementation. It is recommended to use [`strel_diamond`](@ref) and [`strel_type`](@ref): ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> se = strel_diamond((3, 3)) # C4 connectivity 3Γ—3 SEDiamondArray{2, 2, UnitRange{$Int}, 0} with indices -1:1Γ—-1:1: 0 1 0 1 1 1 0 1 0 julia> strel_type(se) SEDiamond{2, 2, UnitRange{$Int}}((-1:1, -1:1), (1, 2), 1) julia> se = centered(collect(se)) # converted to normal centered array 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 0 1 0 1 1 1 0 1 0 julia> strel_type(se) SEMask{2}() ``` """ struct SEDiamond{N,K,R<:AbstractUnitRange{Int}} <: MorphologySE{N} axes::NTuple{N,R} dims::Dims{K} r::Int # radius function SEDiamond{N,K,R}( axes::NTuple{N,R}, dims::Dims{K}, r ) where {N,K,R<:AbstractUnitRange{Int}} if !all(r -> first(r) == -last(r), axes) throw(ArgumentError("axes must be symmetric along each dimension")) end _is_unique_tuple(dims) || throw(ArgumentError("dims should be unique")) N >= K || throw(ArgumentError("`axes` length should be at least $K")) if !all(i -> i <= N, dims) throw(ArgumentError("all `dims` values should be less than or equal to $N")) end return new{N,K,R}(axes, dims, r) end end function SEDiamond{N}( ax::NTuple{N,R}, dims=ntuple(identity, N); r=maximum(length.(ax)) Γ· 2 ) where {N,R} return SEDiamond{N,length(dims),R}(ax, dims, r) end # Helper array type to build a consistant array interface for SEs """ SEDiamondArray(se::SEDiamond) The instantiated array object of [`SEDiamond`](@ref). """ struct SEDiamondArray{N,K,R<:AbstractUnitRange{Int},S} <: MorphologySEArray{N} axes::NTuple{N,R} dims::Dims{K} r::Int # radius _rdims::Dims{S} end function SEDiamondArray(se::SEDiamond{N,K,R}) where {N,K,R} _rdims = _cal_rdims(Val(N), se.dims) return SEDiamondArray{N,K,R,length(_rdims)}(se.axes, se.dims, se.r, _rdims) end strel_type(A::SEDiamondArray{N}) where {N} = SEDiamond{N}(A.axes, A.dims; r=A.r) function strel_size(se::SEDiamondArray) return ntuple(i -> in(i, se.dims) ? 1 + 2 * se.r : 1, strel_ndims(se)) end @inline Base.axes(A::SEDiamondArray) = A.axes @inline Base.size(A::SEDiamondArray) = map(length, axes(A)) @inline Base.IndexStyle(::SEDiamondArray) = IndexCartesian() Base.@propagate_inbounds function Base.getindex( A::SEDiamondArray{N,K}, inds::Int... ) where {N,K} # for remaining dimensions, check if it is at the center position ri = _tuple_getindex(inds, A._rdims) all(iszero, ri) || return false # for masked dimensions, compare if the city-block distance to center is within radius mi = _tuple_getindex(inds, A.dims) r = isempty(mi) ? 0 : sum(abs, mi) return ifelse(r > A.r, false, true) end _tuple_getindex(t::Tuple, inds::Dims) = ntuple(i -> t[inds[i]], length(inds)) function _cal_rdims(::Val{N}, dims::NTuple{K}) where {N,K} return Dims{N - K}(filter(i -> !in(i, dims), 1:N)) end _is_unique_tuple(t::Tuple) = any(i -> t[i] in t[1:(i - 1)], 2:length(t)) ? false : true """ strel_diamond(A::AbstractArray, [dims]; r=1) strel_diamond(size, [dims]; [r]) Construct the N-dimensional structuring element (SE) for a diamond shape. If image `A` is provided, then the SE size will be `(2r+1, 2r+1, ...)` with default half-size `r=1`. If `size` is provided, the default `r` will be `maximum(size)Γ·2`. The default `dims` will be all dimensions, that is, `(1, 2, ..., length(size))`. ```jldoctest; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> img = rand(64, 64); julia> strel_diamond(img) # default size for image input is (3, 3) 3Γ—3 SEDiamondArray{2, 2, UnitRange{$Int}, 0} with indices -1:1Γ—-1:1: 0 1 0 1 1 1 0 1 0 julia> strel_diamond(img; r=2) # equivalent to `strel_diamond((5,5))` 5Γ—5 SEDiamondArray{2, 2, UnitRange{$Int}, 0} with indices -2:2Γ—-2:2: 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 julia> strel_diamond(img, (1,)) # mask along dimension 1 3Γ—1 SEDiamondArray{2, 1, UnitRange{$Int}, 1} with indices -1:1Γ—0:0: 1 1 1 julia> strel_diamond((3,3), (1,)) # 3Γ—3 mask along dimension 1 3Γ—3 SEDiamondArray{2, 1, UnitRange{$Int}, 1} with indices -1:1Γ—-1:1: 0 1 0 0 1 0 0 1 0 ``` !!! note "specialization and performance" The diamond shape `SEDiamond` is a special type for which many morphology algorithms may provide much more efficient implementations. For this reason, if one tries to collect an `SEDiamondArray` into other array types (e.g. `Array{Bool}` via `collect`), then a significant performance drop is very likely to occur. See also [`strel`](@ref) and [`strel_box`](@ref). """ function strel_diamond( img::AbstractArray{T,N}, dims=coords_spatial(img); r::Union{Nothing,Int}=nothing ) where {T,N} dims = _to_dims(Val(N), dims) sz, r = if isnothing(r) ntuple(i -> !isempty(dims) && in(i, dims) ? 3 : 1, N), 1 else ntuple(i -> !isempty(dims) && in(i, dims) ? 2r + 1 : 1, N), r end return strel_diamond(sz, dims; r) end function strel_diamond(sz::Dims{N}, dims=ntuple(identity, N); kw...) where {N} dims = _to_dims(Val(N), dims) all(isodd, sz) || throw(ArgumentError("size should be odd integers")) ax = map(r -> (-r):r, sz .Γ· 2) return SEDiamondArray(SEDiamond{N}(ax, dims; kw...)) end # Tuple(1) is not inferable before Julia 1.9 # we want to support Colon input @inline _to_dims(::Val{N}, i::Int) where {N} = (i,) @inline _to_dims(::Val{N}, dims::Dims) where {N} = dims @inline _to_dims(::Val{N}, ::Union{Colon,Tuple{Colon}}) where {N} = ntuple(identity, N) @inline _to_dims(::Val{N}, v) where {N} = Tuple(v) # fallback
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
5172
#= maybe_floattype(T) To keep consistant with Base `diff` that Int array outputs Int array. It is sometimes useful to only promote types for Bool and FixedPoint. In most of the time, `floattype` should be the most reliable way. =# maybe_floattype(::Type{T}) where {T} = T maybe_floattype(::Type{Bool}) = floattype(Bool) # maybe_floattype(::Type{T}) where {T<:FixedPoint} = floattype(T) # maybe_floattype(::Type{CT}) where {CT<:Color} = base_color_type(CT){maybe_floattype(eltype(CT))} #= A helper to eagerly check if particular function makes sense for `extreme_filter` semantics. For instance, `max(::RGB, ::RGB)` is not well-defined and we should early throw errors so that our users don't get encrypted error messages. =# require_select_function(f, ::Type{T}) where {T} = require_select_function(f, T, T) function require_select_function(f, ::Type{T1}, ::Type{T2}) where {T1,T2} if !_is_select_function(f, T1, T2) hint = "does `f(x::T1, y::T2)` work as expected?" throw( ArgumentError( "function `$f` is not a well-defined select function on type `$T1` and `$T2`: $hint", ), ) end end _is_select_function(f, ::Type{T}) where {T} = _is_select_function(f, T, T) function _is_select_function(f, ::Type{T1}, ::Type{T2}) where {T1,T2} return _is_select_function_trial(f, T1, T2) end function _is_select_function(f, ::Type{T1}, ::Type{T2}) where {T1<:Real,T2<:Real} f in (min, max) && return true return _is_select_function_trial(f, T1, T2) end # function _is_select_function(f, ::Type{CT1}, ::Type{CT2}) where {CT1<:AbstractGray,CT2<:AbstractGray} # f in (min, max) && return true # return _is_select_function_trial(f, CT1, CT2) # end # function _is_select_function(f, ::Type{CT1}, ::Type{CT2}) where {CT1<:Colorant,CT2<:Colorant} # # min/max is not well-defined on generic color space # f in (min, max) && return false # return _is_select_function_trial(f, CT1, CT2) # end function _is_select_function_trial(f, ::Type{T1}, ::Type{T2}) where {T1,T2} # for generic case, just run a trial and see if it doesn't error try f(zero(T1), zero(T2)) return true catch return false end end """ upper, lower = strel_split([T], se) Split a symmetric structuring element into its upper and lower half parts based on its center point. For each element `o` in `strel(CartesianIndex, upper)`, its negative `-o` is an element of `strel(CartesianIndex, lower)`. This function is not the inverse of [`strel_chain`](@ref). The splited non-symmetric SE parts will be represented as array of `T`, where `T` is either a `Bool` or `CartesianIndex`. By default, `T = eltype(se)`. ```jldoctest strel_split; setup=:(using ImageMorphology; using ImageMorphology.StructuringElements) julia> se = strel_diamond((3, 3)) 3Γ—3 SEDiamondArray{2, 2, UnitRange{$Int}, 0} with indices -1:1Γ—-1:1: 0 1 0 1 1 1 0 1 0 julia> upper, lower = strel_split(se); julia> upper 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 0 1 0 1 1 0 0 0 0 julia> lower 3Γ—3 OffsetArray(::Matrix{Bool}, -1:1, -1:1) with eltype Bool with indices -1:1Γ—-1:1: 0 0 0 0 1 1 0 1 0 ``` If the `se` is represented as displacement offset array, then the splitted result will also be displacement offset array: ```jldoctest strel_split julia> se = strel(CartesianIndex, se) 4-element Vector{CartesianIndex{2}}: CartesianIndex(0, -1) CartesianIndex(-1, 0) CartesianIndex(1, 0) CartesianIndex(0, 1) julia> upper, lower = strel_split(se); julia> upper 2-element Vector{CartesianIndex{2}}: CartesianIndex(0, -1) CartesianIndex(-1, 0) julia> lower 2-element Vector{CartesianIndex{2}}: CartesianIndex(1, 0) CartesianIndex(0, 1) ``` """ strel_split(se) = strel_split(eltype(se), se) function strel_split(T, se) se = strel(Bool, se) require_symmetric_strel(se) R = LinearIndices(se) c = R[OffsetArrays.center(R)...] upper = copy(se) lower = copy(se) upper[(c + 1):end] .= false lower[begin:(c - 1)] .= false return strel(T, upper), strel(T, lower) end """ is_symmetric(se) Check if a given structuring element array `se` is symmetric with respect to its center pixel. More formally, this checks if `mask[I] == mask[-I]` for any valid `I ∈ CartesianIndices(mask)` in the connectivity mask representation `mask = strel(Bool, se)`. """ function is_symmetric(se::AbstractArray) # first check the axes, and then the values se = OffsetArrays.centered(strel(Bool, se)) all(r -> first(r) == -last(r), axes(se)) || return false R = CartesianIndices(map(r -> 0:maximum(r), axes(se))) return all(R) do o @inbounds se[o] == se[-o] end end is_symmetric(se::SEBoxArray) = true is_symmetric(se::SEDiamondArray) = true #= Some morphological operation only makes sense for symmetric structuring elements. Here we provide a checker in spirit of Base.require_one_based_indexing. =# function require_symmetric_strel(se) return is_symmetric(se) || throw( ArgumentError("structuring element must be symmetric with respect to its center") ) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2461
""" matchcorr( f1::T, f2::T, Ξ”t::F, mxrot::S=10, psi::F=0.95, sz::S=16, comp::F=0.25, mm::F=0.22 ) where {T<:AbstractArray{Bool,2},S<:Int64,F<:Float64} Compute the mismatch `mm` and psi-s-correlation `c` for floes with masks `f1` and `f2`. The criteria for floes to be considered equivalent is as follows: - `c` greater than `mm` - `_mm` is less than `mm` A pair of `NaN` is returned for cases for which one of their mask dimension is too small or their sizes are not comparable. # Arguments - `f1`: mask of floe 1 - `f2`: mask of floe 2 - `Ξ”t`: time difference between floes - `mxrot`: maximum rotation (in degrees) allowed between floesn (default: 10) - `psi`: psi-s-correlation threshold (default: 0.95) - `sz`: size threshold (default: 16) - `comp`: size comparability threshold (default: 0.25) - `mm`: mismatch threshold (default: 0.22) """ function matchcorr( f1::T, f2::T, Ξ”t::F; mxrot::S=10, psi::F=0.95, sz::S=16, comp::F=0.25, mm::F=0.22 ) where {T<:AbstractArray{Bool,2},S<:Int64,F<:Float64} # check if the floes are too small and size are comparable _sz = size.([f1, f2]) if (any([(_sz...)...] .< sz) || getsizecomparability(_sz...) > comp) return (mm=NaN, c=NaN) end _psi = buildψs.([f1, f2]) c = corr(_psi...) if c < psi @warn "correlation too low, c: $c" return (mm=NaN, c=NaN) else return (mm=0.0, c=c) end # check if the time difference is too large or the rotation is too large _mm, rot = mismatch(f1, f2; mxrot=deg2rad(mxrot)) if all([Ξ”t < 300, rot > mxrot]) || _mm > mm @warn "time difference too small for a large rotation or mismatch too large\nmm: $mm, rot: $rot" return (mm=NaN, c=NaN) end if mm < 0.1 mm = 0.0 end return (mm=mm, c=c) end """ getsizecomparability(s1, s2) Check if the size of two floes `s1` and `s2` are comparable. The size is defined as the product of the floe dimensions. # Arguments - `s1`: size of floe 1 - `s2`: size of floe 2 """ function getsizecomparability(s1::T, s2::T) where {T<:Tuple{Int64,Int64}} a1 = *(s1...) a2 = *(s2...) return abs(a1 - a2) / a1 end """ corr(f1,f2) Return the normalized cross-correlation between the psi-s curves `p1` and `p2`. """ function corr(p1::T, p2::T) where {T<:AbstractArray} cc, _ = maximum.(IceFloeTracker.crosscorr(p1, p2; normalize=true)) return cc end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
17190
# need this for adding methods to Base functions import Base.isempty import Base.isequal # Containers and methods for preliminary matches struct MatchingProps s::Vector{Int64} props::DataFrame ratios::DataFrame dist::Vector{Float64} end """ Container for matched pairs of floes. `props1` and `props2` are dataframes with the same column names as the input dataframes. `ratios` is a dataframe with column names `area`, `majoraxis`, `minoraxis`, `convex_area`, `area_mismatch`, and `corr` for similarity ratios. `dist` is a vector of (pixel) distances between paired floes. """ struct MatchedPairs props1::DataFrame props2::DataFrame ratios::DataFrame dist::Vector{Float64} end """ MatchedPairs(df) Return an object of type `MatchedPairs` with an empty dataframe with the same column names as `df`, an empty dataframe with column names `area`, `majoraxis`, `minoraxis`, `convex_area`, `area_mismatch`, and `corr` for similarity ratios, and an empty vector for distances. """ function MatchedPairs(df) emptypropsdf = similar(df, 0) return MatchedPairs(emptypropsdf, copy(emptypropsdf), makeemptyratiosdf(), Float64[]) end """ update!(match_total::MatchedPairs, matched_pairs::MatchedPairs) Update `match_total` with the data from `matched_pairs`. """ function update!(match_total::MatchedPairs, matched_pairs::MatchedPairs) append!(match_total.props1, matched_pairs.props1) append!(match_total.props2, matched_pairs.props2) append!(match_total.ratios, matched_pairs.ratios) append!(match_total.dist, matched_pairs.dist) return nothing end """ addmatch!(matched_pairs, newmatch) Add `newmatch` to `matched_pairs`. """ function addmatch!(matched_pairs::MatchedPairs, newmatch) push!(matched_pairs.props1, newmatch.props1) push!(matched_pairs.props2, newmatch.props2) push!(matched_pairs.ratios, newmatch.ratios) push!(matched_pairs.dist, newmatch.dist) return nothing end function isempty(matched_pairs::MatchedPairs) return isempty(matched_pairs.props1) && isempty(matched_pairs.props2) && isempty(matched_pairs.ratios) end """ appendrows!(df::MatchingProps, props::T, ratios, idx::Int64, dist::Float64) where {T<:DataFrameRow} Append a row to `df.props` and `df.ratios` with the values of `props` and `ratios` respectively. """ function appendrows!( df::MatchingProps, props::T, ratios, idx::Int64, dist::Float64 ) where {T<:DataFrameRow} push!(df.s, idx) push!(df.props, props) push!(df.ratios, ratios) push!(df.dist, dist) return nothing end """ isequal(matchedpairs1::MatchedPairs, matchedpairs2::MatchedPairs) Return `true` if `matchedpairs1` and `matchedpairs2` are equal, `false` otherwise. """ function isequal(matchedpairs1::MatchedPairs, matchedpairs2::MatchedPairs) return all(( isequal(getfield(matchedpairs1, name), getfield(matchedpairs2, name)) for name in namesof(matchedpairs1) )) end # Final pairs container and associated methods """ Container for final matched pairs of floes. `data` is a vector of `MatchedPairs` objects. """ struct Tracked data::Vector{MatchedPairs} end """ sort!(tracked::Tracked) Sort the floes in `tracked` by area in descending order. """ function sort!(tracked::Tracked) for container in tracked.data p = sortperm(container.props1, "area"; rev=true) for nm in namesof(container) getproperty(container, nm)[:, :] = getproperty(container, nm)[p, :] end end return nothing end function Tracked() return Tracked(MatchedPairs[]) end function update!(tracked::Tracked, matched_pairs::MatchedPairs) push!(tracked.data, matched_pairs) return nothing end # Misc functions """ modenan(x::AbstractVector{<:Float64}) Return the mode of `x` or `NaN` if `x` is empty. """ function modenan(x::AbstractVector{<:Int64}) length(x) == 0 && return NaN return mode(x) end """ getcentroid(props_day::DataFrame, r) Get the coordinates of the `r`th floe in `props_day`. """ function getcentroid(props_day::DataFrame, r) return props_day[r, [:row_centroid, :col_centroid]] end """ absdiffmeanratio(x, y) Calculate the absolute difference between `x` and `y` divided by the mean of `x` and `y`. """ function absdiffmeanratio(x::T, y::T)::Float64 where {T<:Real} return abs(x - y) / mean(x, y) end """ mean(x,y) Compute the mean of `x` and `y`. """ function mean(x::T, y::T)::Float64 where {T<:Real} return (x + y) / 2 end """ makeemptydffrom(df::DataFrame) Return an object with an empty dataframe with the same column names as `df` and an empty dataframe with column names `area`, `majoraxis`, `minoraxis`, `convex_area`, `area_mismatch`, and `corr` for similarity ratios. """ function makeemptydffrom(df::DataFrame) return MatchingProps( Vector{Int64}(), similar(df, 0), makeemptyratiosdf(), Vector{Float64}() ) end """ makeemptyratiosdf() Return an empty dataframe with column names `area`, `majoraxis`, `minoraxis`, `convex_area`, `area_mismatch`, and `corr` for similarity ratios. """ function makeemptyratiosdf() return DataFrame(; area=Float64[], majoraxis=Float64[], minoraxis=Float64[], convex_area=Float64[], area_mismatch=Float64[], corr=Float64[], ) end #= Conditions for a match: Condition 1: displacement time delta =# """ trackercond1(p1, p2, delta_time, t1=(dt = (30, 100, 1300), dist=(15, 30, 120))) Return `true` if the floe at `p1` and the floe at `p2` are within a certain distance of each other and the displacement time is within a certain range. Return `false` otherwise. # Arguments - `p1`: coordinates of floe 1 - `p2`: coordinates of floe 2 - `delta_time`: time elapsed from image day 1 to image day 2 - `t`: tuple of thresholds for elapsed time and distance """ function trackercond1(d, delta_time, t1=(dt=(30, 100, 1300), dist=(15, 30, 120))) return (delta_time < t1.dt[1] && d < t1.dist[1]) || (delta_time >= t1.dt[1] && delta_time <= t1.dt[2] && d < t1.dist[2]) || (delta_time >= t1.dt[3] && d < t1.dist[3]) end """ trackercond2(area1, ratios, t2=(area=1200, arearatio=0.28, majaxisratio=0.10, minaxisratio=0.12, convex_area=0.14)) Set of conditions for "big" floes. Return `true` if the area of the floe is greater than `t2.area` and the similarity ratios are less than the corresponding thresholds in `t2`. Return `false` otherwise. """ function trackercond2( area1, ratios, t2=(area=1200, arearatio=0.28, majaxisratio=0.10, minaxisratio=0.12, convex_area=0.14), ) return area1 > t2.area && ratios.area < t2.arearatio && ratios.majoraxis < t2.majaxisratio && ratios.minoraxis < t2.minaxisratio && ratios.convex_area < t2.convexarearatio end """ trackercond3(area1, ratios, t3=(area=1200, arearatio=0.18, majaxisratio=0.07, minaxisratio=0.08, convex_area=0.09)) Set of conditions for "small" floes. Return `true` if the area of the floe is less than `t3.area` and the similarity ratios are less than the corresponding thresholds in `t3`. Return `false` otherwise """ function trackercond3( area1, ratios, t3=( area=1200, arearatio=0.18, majaxisratio=0.07, minaxisratio=0.08, convexarearatio=0.09, ), ) return area1 <= t3.area && ratios.area < t3.arearatio && ratios.majoraxis < t3.majaxisratio && ratios.minoraxis < t3.minaxisratio && ratios.convex_area < t3.convexarearatio end """ callmatchcorr(conditions) Condition to decide whether match_corr should be called. """ function callmatchcorr(conditions) return conditions.cond1 && (conditions.cond2 || conditions.cond3) end """ isfloegoodmatch(conditions, mct, area_mismatch, corr) Return `true` if the floes are a good match as per the set thresholds. Return `false` otherwise. # Arguments - `conditions`: tuple of booleans for evaluating the conditions - `mct`: tuple of thresholds for the match correlation test - `area_mismatch` and `corr`: values returned by `match_corr` """ function isfloegoodmatch(conditions, mct, area_mismatch, corr) return ( (conditions.cond3 && area_mismatch < mct.area3) || (conditions.cond2 && area_mismatch < mct.area2) ) && corr > mct.corr end """ compute_ratios((props_day1, r), (props_day2,s)) Compute the ratios of the floe properties between the `r`th floe in `props_day1` and the `s`th floe in `props_day2`. Return a tuple of the ratios. # Arguments - `props_day1`: floe properties for day 1 - `r`: index of floe in `props_day1` - `props_day2`: floe properties for day 2 - `s`: index of floe in `props_day2` """ function compute_ratios((props_day1, r), (props_day2, s)) arearatio = absdiffmeanratio(props_day1.area[r], props_day2.area[s]) majoraxisratio = absdiffmeanratio( props_day1.major_axis_length[r], props_day2.major_axis_length[s] ) minoraxisratio = absdiffmeanratio( props_day1.minor_axis_length[r], props_day2.minor_axis_length[s] ) convex_area = absdiffmeanratio(props_day1.convex_area[r], props_day2.convex_area[s]) return ( area=arearatio, majoraxis=majoraxisratio, minoraxis=minoraxisratio, convex_area=convex_area, ) end """ compute_ratios_conditions((props_day1, r), (props_day2, s), delta_time, t) Compute the conditions for a match between the `r`th floe in `props_day1` and the `s`th floe in `props_day2`. Return a tuple of the conditions. # Arguments - `props_day1`: floe properties for day 1 - `r`: index of floe in `props_day1` - `props_day2`: floe properties for day 2 - `s`: index of floe in `props_day2` - `delta_time`: time elapsed from image day 1 to image day 2 - `t`: tuple of thresholds for elapsed time and distance. See `pair_floes` for details. """ function compute_ratios_conditions((props_day1, r), (props_day2, s), delta_time, thresh) t1, t2, t3 = thresh p1 = getcentroid(props_day1, r) p2 = getcentroid(props_day2, s) d = dist(p1, p2) area1 = props_day1.area[r] ratios = compute_ratios((props_day1, r), (props_day2, s)) cond1 = trackercond1(d, delta_time, t1) cond2 = trackercond2(area1, ratios, t2) cond3 = trackercond3(area1, ratios, t3) return (ratios=ratios, conditions=(cond1=cond1, cond2=cond2, cond3=cond3), dist=d) end """ dist(p1, p2) Return the distance between the points `p1` and `p2`. """ function dist(p1, p2) return sqrt( (p1.row_centroid - p2.row_centroid)^2 + (p1.col_centroid - p2.col_centroid)^2 ) end """ getidxmostminimumeverything(ratiosdf) Return the index of the row in `ratiosdf` with the most minima across its columns. If there are multiple columns with the same minimum value, return the index of the first column with the minimum value. If `ratiosdf` is empty, return `NaN`. """ function getidxmostminimumeverything(ratiosdf) nrow(ratiosdf) == 0 && return NaN return mode([argmin(col) for col in eachcol(ratiosdf)]) end """ getpropsday1day2(properties, dayidx::Int64) Return the floe properties for day `dayidx` and day `dayidx+1`. """ function getpropsday1day2(properties, dayidx::Int64) return copy(properties[dayidx]), copy(properties[dayidx + 1]) end """ getbestmatchdata(idx, r, props_day1, matching_floes) Collect the data for the best match between the `r`th floe in `props_day1` and the `idx`th floe in `matching_floes`. Return a tuple of the floe properties for day 1 and day 2 and the ratios. """ function getbestmatchdata(idx, r, props_day1, matching_floes) return ( props1=props_day1[r, :], props2=matching_floes.props[idx, :], ratios=matching_floes.ratios[idx, :], dist=matching_floes.dist[idx], ) end """ getidxofrow(rw0, df) Return the indices of the rows in `df` that are equal to `rw0`. """ function getidxofrow(rw0, df) return findall([rw0 == row for row in eachrow(df)]) end # Collision handling """ getcollisionslocs(df) Return a vector of tuples of the row and the index of the row in `df` that has a collision with another row in `df`. """ function getcollisionslocs(df) #::Vector{Tuple{DataFrameRow{DataFrame, DataFrames.Index}, Vector{Int64}}} typeof(df) <: DataFrameRow && return Tuple{DataFrameRow{DataFrame,DataFrames.Index},Vector{Int64}}[] collisions = getcollisions(df) return [(data=rw, idxs=getidxofrow(rw, df)) for rw in eachrow(collisions)] end namesof(obj::MatchedPairs) = fieldnames(typeof(obj)) """ getcollisions(matchedpairs) Get nonunique rows in `matchedpairs`. """ function getcollisions(matchedpairs) collisions = transform(matchedpairs, nonunique) return filter(r -> r.x1 != 0, collisions)[:, 1:(end - 1)] end function deletematched!( (propsday1, propsday2)::Tuple{DataFrame,DataFrame}, matched::MatchedPairs ) deletematched!(propsday1, matched.props1) deletematched!(propsday2, matched.props2) return nothing end """ deleteallbut!(matched_pairs, idxs, keeper) Delete all rows in `matched_pairs` except for the row with index `keeper` in `idxs`. """ function deleteallbut!(matched_pairs, idxs, keeper) for i in sort(idxs; rev=true) if i !== keeper deleteat!(matched_pairs.ratios, i) deleteat!(matched_pairs.props1, i) deleteat!(matched_pairs.props2, i) deleteat!(matched_pairs.dist, i) end end end """ ismember(df1,df2) Return a boolean array indicating whether each row in `df1` is a member of `df2`. """ function ismember(df1, df2) return in.(eachrow(df1), Ref(eachrow(df2))) end function resolvecollisions!(matched_pairs) collisions = getcollisionslocs(matched_pairs.props2) for collision in reverse(collisions) bestentry = getidxmostminimumeverything(matched_pairs.ratios[collision.idxs, :]) keeper = collision.idxs[bestentry] deleteallbut!(matched_pairs, collision.idxs, keeper) end end function deletematched!(propsday::DataFrame, matched::DataFrame) toremove = findall(ismember(propsday, matched)) return deleteat!(propsday, toremove) end isnotnan(x) = !isnan(x) # match_corr related functions """ corr(f1,f2) Return the correlation between the psi-s curves `p1` and `p2`. """ function corr(p1, p2) cc, _ = maximum.(IceFloeTracker.crosscorr(p1, p2; normalize=true)) return cc end """ normalizeangle(revised,t=180) Normalize angle to be between -180 and 180 degrees. """ function normalizeangle(revised, t=180) revised > t ? theta_revised = revised - 360 : theta_revised = revised return (theta_revised=theta_revised, ROT=-theta_revised) end function buildψs(floe) bd = IceFloeTracker.bwtraceboundary(floe) bdres = IceFloeTracker.resample_boundary(bd[1]) return IceFloeTracker.make_psi_s(bdres)[1] end function addψs!(props::Vector{DataFrame}) for prop in props prop.psi = map(buildψs, prop.mask) end return nothing end function addfloemasks!(props, imgs) for (img, prop) in zip(imgs, props) IceFloeTracker.addfloemasks!(prop, img) end return nothing end ## LatLon functions originally from IFTPipeline.jl """ convertcentroid!(propdf, latlondata, colstodrop) Convert the centroid coordinates from row and column to latitude and longitude dropping unwanted columns specified in `colstodrop` for the output data structure. Addionally, add columns `x` and `y` with the pixel coordinates of the centroid. """ function convertcentroid!(propdf, latlondata, colstodrop) latitude, longitude = [ [latlondata[c][x, y] for (x, y) in zip(propdf.row_centroid, propdf.col_centroid)] for c in ["latitude", "longitude"] ] x, y = [ [latlondata[c][z] for z in V] for (c, V) in zip(["Y", "X"], [propdf.row_centroid, propdf.col_centroid]) ] propdf.latitude = latitude propdf.longitude = longitude propdf.x = x propdf.y = y dropcols!(propdf, colstodrop) return nothing end """ converttounits!(propdf, latlondata, colstodrop) Convert the floe properties from pixels to kilometers and square kilometers where appropiate. Also drop the columns specified in `colstodrop`. """ function converttounits!(propdf, latlondata, colstodrop) if nrow(propdf) == 0 dropcols!(propdf, colstodrop) insertcols!(propdf, :latitude=>Float64, :longitude=>Float64, :x=>Float64, :y=>Float64) return nothing end convertcentroid!(propdf, latlondata, colstodrop) x = latlondata["X"] dx = abs(x[2] - x[1]) convertarea(area) = area * dx^2 / 1e6 convertlength(length) = length * dx / 1e3 propdf.area .= convertarea(propdf.area) propdf.convex_area .= convertarea(propdf.convex_area) propdf.minor_axis_length .= convertlength(propdf.minor_axis_length) propdf.major_axis_length .= convertlength(propdf.major_axis_length) propdf.perimeter .= convertlength(propdf.perimeter) return nothing end function dropcols!(df, colstodrop) select!(df, Not(colstodrop)) return nothing end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
10145
""" addlatlon(pairedfloesdf::DataFrame, refimage::AbstractString) Add columns `latitude`, `longitude`, and pixel coordinates `x`, `y` to `pairedfloesdf`. # Arguments - `pairedfloesdf`: dataframe containing floe tracking data. - `refimage`: path to reference image. """ function addlatlon!(pairedfloesdf::DataFrame, refimage::AbstractString) latlondata = getlatlon(refimage) colstodrop = [:row_centroid, :col_centroid, :min_row, :min_col, :max_row, :max_col] converttounits!(pairedfloesdf, latlondata, colstodrop) return nothing end """ add_passtimes!(props, passtimes) Add a column `passtime` to each DataFrame in `props` containing the time of the image in which the floes were captured. # Arguments - `props`: array of DataFrames containing floe properties. - `passtimes`: array of `DateTime` objects containing the time of the image in which the floes were captured. """ function add_passtimes!(props, passtimes) for (i, passtime) in enumerate(passtimes) props[i].passtime .= passtime end nothing end """ sort_floes_by_area!(props) Sort floes in `props` by area in descending order. """ function sort_floes_by_area!(props) for prop in props # sort by area in descending order DataFrames.sort!(prop, :area; rev=true) nothing end end function _pairfloes( segmented_imgs::Vector{BitMatrix}, props::Vector{DataFrame}, passtimes::Vector{DateTime}, condition_thresholds, mc_thresholds ) dt = diff(passtimes) ./ Minute(1) sort_floes_by_area!(props) # Assign a unique ID to each floe in each image for (i, prop) in enumerate(props) props[i].uuid = [randstring(12) for _ in 1:nrow(prop)] end add_passtimes!(props, passtimes) # Initialize container for props of matched pairs of floes, their similarity ratios, and their distances between their centroids tracked = Tracked() # Crop floes from the images using the bounding box data in `props`. addfloemasks!(props, segmented_imgs) addψs!(props) numdays = length(segmented_imgs) - 1 for dayi in 1:numdays props1, props2 = getpropsday1day2(props, dayi) Ξ”t = dt[dayi] # Container for matches in dayi which will be used to populate tracked match_total = MatchedPairs(props1) while true # there are no more floes to match in props1 # This routine mutates both props1 and props2. # Container for props of matched floe pairs and their similarity ratios. Matches will be updated and added to match_total matched_pairs = MatchedPairs(props1) for r in 1:nrow(props1) # TODO: consider using eachrow(props1) to iterate over rows # 1. Collect preliminary matches for floe r in matching_floes matching_floes = makeemptydffrom(props1) for s in 1:nrow(props2) # TODO: consider using eachrow(props2) to iterate over rows ratios, conditions, dist = compute_ratios_conditions( (props1, r), (props2, s), Ξ”t, condition_thresholds ) if callmatchcorr(conditions) (area_mismatch, corr) = matchcorr( props1.mask[r], props2.mask[s], Ξ”t; mc_thresholds.comp... ) if isfloegoodmatch( conditions, mc_thresholds.goodness, area_mismatch, corr ) appendrows!( matching_floes, props2[s, :], (ratios..., area_mismatch, corr), s, dist, ) end end end # of s for loop # 2. Find the best match for floe r best_match_idx = getidxmostminimumeverything(matching_floes.ratios) if isnotnan(best_match_idx) bestmatchdata = getbestmatchdata( best_match_idx, r, props1, matching_floes ) # might be copying data unnecessarily addmatch!(matched_pairs, bestmatchdata) end end # of for r = 1:nrow(props1) # exit while loop if there are no more floes to match isempty(matched_pairs) && break #= Resolve collisions: Are there floes in day k+1 paired with more than one floe in day k? If so, keep the best matching pair and remove all others. =# resolvecollisions!(matched_pairs) deletematched!((props1, props2), matched_pairs) update!(match_total, matched_pairs) end # of while loop update!(tracked, match_total) end sort!(tracked) _pairs = tracked.data # Concatenate horizontally props1, props2, tracked, and add dist as the last column for each item in _pairs _pairs = [hcat(hcat(p.props1, p.props2, makeunique=true), p.ratios[:, ["area_mismatch", "corr"]]) for p in _pairs] # Make a dict with keys in _pairs[i].props2.uuid and values in _pairs[i-1].props1.uuid mappings = [Dict(zip(p.uuid_1, p.uuid)) for p in _pairs] # Convert mappings to functions funcsfrommappings = [x -> get(mapping, x, x) for mapping in mappings] # Compose functions in reverse order to push uuids forward mapuuid = foldr((f, g) -> x -> f(g(x)), funcsfrommappings) # Apply mapuuid to uuid_1 in each set of props in _pairs => get consolidated uuids [prop.uuid_0 = mapuuid.(prop.uuid_1) for prop in _pairs] # Reshape _pairs to a long df propsvert = vcat(_pairs...) DataFrames.sort!(propsvert, [:uuid_0, :passtime]) rightcolnames = vcat([name for name in names(propsvert) if all([!(name in ["uuid_1", "psi_1", "mask_1"]), endswith(name, "_1")])], ["uuid_0"]) leftcolnames = [split(name, "_1")[1] for name in rightcolnames] matchcolnames = ["area_mismatch", "corr", "uuid_0", "passtime", "passtime_1",] leftdf = propsvert[:, leftcolnames] rightdf = propsvert[:, rightcolnames] matchdf = propsvert[:, matchcolnames] rename!(rightdf, Dict(zip(rightcolnames, leftcolnames))) _pairs = vcat(leftdf, rightdf) # sort by uuid_0, passtime and keep unique rows _pairs = DataFrames.sort!(_pairs, [:uuid_0, :passtime]) |> unique _pairs = leftjoin(_pairs, matchdf, on=[:uuid_0, :passtime]) DataFrames.sort!(_pairs, [:uuid_0, :passtime]) # create mapping from uuids to index as ID uuids = unique(_pairs.uuid_0) uuid2index = Dict(uuid => i for (i, uuid) in enumerate(uuids)) _pairs.ID = [uuid2index[uuid] for uuid in _pairs.uuid_0] _pairs = _pairs[:, [name for name in names(_pairs) if name != "uuid_0"]] return _pairs end """ pairfloes( segmented_imgs::Vector{BitMatrix}, props::Vector{DataFrame}, passtimes::Vector{DateTime}, latlonrefimage::AbstractString, condition_thresholds, mc_thresholds, ) Pair floes in `props[k]` to floes in `props[k+1]` for `k=1:length(props)-1`. The main steps of the algorithm are as follows: 1. Crop floes from `segmented_imgs` using bounding box data in `props`. Floes in the edges are removed. 2. For each floe_k_r in `props[k]`, compare to floe_k+1_s in `props[k+1]` by computing similarity ratios, set of `conditions`, and drift distance `dist`. If the conditions are met, compute the area mismatch `mm` and psi-s correlation `c` for this pair of floes. Pair these two floes if `mm` and `c` satisfy the thresholds in `mc_thresholds`. 3. If there are collisions (i.e. floe `s` in `props[k+1]` is paired to more than one floe in `props[k]`), then the floe in `props[k]` with the best match is paired to floe `s` in `props[k+1]`. 4. Drop paired floes from `props[k]` and `props[k+1]` and repeat steps 2 and 3 until there are no more floes to match in `props[k]`. 5. Repeat steps 2-4 for `k=2:length(props)-1`. # Arguments - `segmented_imgs`: array of images with segmented floes - `props`: array of dataframes containing floe properties - `passtimes`: array of `DateTime` objects containing the time of the image in which the floes were captured - `latlonrefimage`: path to geotiff reference image for getting latitude and longitude of floe centroids - `condition_thresholds`: 3-tuple of thresholds (each a named tuple) for deciding whether to match floe `i` from day `k` to floe j from day `k+1` - `mc_thresholds`: thresholds for area mismatch and psi-s shape correlation Returns a dataframe containing the following columns: - `ID`: unique ID for each floe pairing. - `passtime`: time of the image in which the floes were captured. - `area`: area of the floe in sq. kilometers - `convex_area`: area of the convex hull of the floe in sq. kilometers - `major_axis_length`: length of the major axis of the floe in kilometers - `minor_axis_length`: length of the minor axis of the floe in kilometers - `orientation`: angle between the major axis and the x-axis in radians - `perimeter`: perimeter of the floe in kilometers - `latitude`: latitude of the floe centroid - `longitude`: longitude of the floe centroid - `x`: x-coordinate of the floe centroid - `y`: y-coordinate of the floe centroid - `area_mismatch`: area mismatch between the two floes in row_i and row_i+1 after registration - `corr`: psi-s shape correlation between the two floes in row_i and row_i+1 """ function pairfloes( segmented_imgs::Vector{BitMatrix}, props::Vector{DataFrame}, passtimes::Vector{DateTime}, latlonrefimage::AbstractString, condition_thresholds, mc_thresholds, ) _pairs = _pairfloes( segmented_imgs, props, passtimes, condition_thresholds, mc_thresholds, ) addlatlon!(_pairs, latlonrefimage) cols = [:ID, :passtime, :area, :convex_area, :major_axis_length, :minor_axis_length, :orientation, :perimeter, :latitude, :longitude, :x, :y, :area_mismatch, :corr] _pairs = _pairs[:, cols] return _pairs end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1642
# Setting things up ## locate some files for the tests test_data_dir = "./test_inputs" test_output_dir = "./test_outputs" truecolor_test_image_file = "$(test_data_dir)/NE_Greenland_truecolor.2020162.aqua.250m.tiff" falsecolor_test_image_file = "$(test_data_dir)/NE_Greenland_reflectance.2020162.aqua.250m.tiff" falsecolor_b7_test_file = "$(test_data_dir)/ref_image_b7.png" landmask_file = "$(test_data_dir)/landmask.tiff" landmask_no_dilate_file = "$(test_data_dir)/landmask_no_dilate.png" current_landmask_file = "$(test_data_dir)/current_landmask.png" normalized_test_file = "$(test_data_dir)/matlab_normalized.png" clouds_channel_test_file = "$(test_data_dir)/clouds_channel.png" cloudmask_test_file = "$(test_data_dir)/cloudmask.png" ice_water_discrim_test_file = "$(test_data_dir)/matlab_ice_water_discrim.png" sharpened_test_image_file = "$(test_data_dir)/matlab_sharpened.png" segmented_a_ice_mask_file = "$(test_data_dir)/matlab_segmented_A.png" segmented_b_ice_test_file = "$(test_data_dir)/matlab_segmented_b_ice.png" segmented_b_filled_test_file = "$(test_data_dir)/matlab_segmented_b_filled.png" segmented_c_test_file = "$(test_data_dir)/matlab_segmented_c.png" not_ice_mask_test_file = "$(test_data_dir)/matlab_not_ice_mask.png" strel_file_2 = "$(test_data_dir)/se2.csv" # original matlab structuring element - a disk-shaped kernel with radius of 2 px strel_file_4 = "$(test_data_dir)/strel_disk_4.csv" # disk-shaped kernel with radius of 4 px watershed_test_file = "$(test_data_dir)/matlab_watershed_intersect.png" test_region = (1:2707, 1:4458) lm_test_region = (1:800, 1:1500) ice_floe_test_region = (1640:2060, 1840:2315)
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1521
using IceFloeTracker using Images using Test using DelimitedFiles using Dates using DataFrames using Random using ImageTransformations: imrotate using ArgParse: ArgParseSettings, @add_arg_table!, add_arg_group!, parse_args include("test_error_rate.jl") include("config.jl") # Setting things up (see config.jl) ## Get all test files filenames "test-*" in test folder and their corresponding names/label alltests = [f for f in readdir() if startswith(f, "test-")] testnames = [n[6:(end - 3)] for n in alltests] ## Put the filenames to test below to_test = alltests # uncomment this line to run all tests or add individual files below [ # "test-create-landmask.jl", # "test-create-cloudmask.jl", # "test-normalize-image.jl", # "test-persist.jl", # "test-utils-padding.jl", # "test-discrim-ice-water.jl", # "test-find-ice-labels.jl", # "test-segmentation-a.jl", # "test-segmentation-b.jl", # "test-segmentation-watershed.jl", # "test-segmentation-f.jl", # "test-bwtraceboundary.jl", # "test-resample-boundary.jl", # "test-regionprops.jl", # "test-psi-s.jl", # "test-crosscorr.jl" # "test-bwperim.jl", # "test-bwareamaxfilt.jl" # "test-register-mismatch.jl", # "test-utils-imextendedmin.jl", # "test-morphSE.jl", # "test-hbreak.jl", # "test-bridge.jl", # "test-branch.jl" # "test-pipeline.jl" ] # Run the tests @testset verbose = true "IceFloeTracker.jl" begin for test in to_test include(test) end end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
520
@testset "branch points tests" begin dir = joinpath(test_data_dir, "branch") readcsv(f) = readdlm(joinpath(dir, f), ',', Bool) # Get inputs circles = readcsv("circles.csv") circles_skel = readcsv("circles_skel.csv") circles_branch_exp = readcsv("circles_branch_matlab.csv") # Ideal test on skeletonized image @test circles_branch_exp == branch(circles_skel) # Test on non-skeletonized image: Effect of brach = eroding @test IceFloeTracker.erode(circles) == branch(circles) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
349
@testset "bridge tests" begin println("-------------------------------------------------") println("---------------- bridge tests -------------------") bwin = readdlm("./test_inputs/bridge/bridge_in.csv", ',', Bool) bwexpected = readdlm("./test_inputs/bridge/bridge_expected.csv", ',', Bool) @test bridge(bwin) == bwexpected end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2522
@testset "bwareamaxfilt test" begin println("-------------------------------------------------") println("------------ bwareamaxfilt Tests --------------") # Create a bitmatrix with a big floe and two smaller floes -- 3 connected components in total. A = zeros(Bool, 12, 15) A[2:6, 2:6] .= 1 A[4:8, 7:10] .= 1 A[10:12, 13:15] .= 1 A[10:12, 3:6] .= 1 # 12Γ—15 Matrix{Bool}: # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 # Test 1: Check number of total blobs and their respective areas. # First get the labels labels = label_components(A) # 12Γ—15 Matrix{Int64}: # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 0 2 2 2 2 0 0 0 0 0 0 3 3 3 # 0 0 2 2 2 2 0 0 0 0 0 0 3 3 3 # 0 0 2 2 2 2 0 0 0 0 0 0 3 3 3 # a) Test there are three blobs d = IceFloeTracker.get_areas(labels) @test length(d) == 3 # b) Test largest blob is the one with label '1' @test IceFloeTracker.get_max_label(d) == 1 # c) Test the distribution of the labels @test all([d[1] == 45, d[2] == 12, d[3] == 9]) # Test 2: Filter smaller blobs from label matrix @test sum( IceFloeTracker.filt_except_label(labels, IceFloeTracker.get_max_label(d)) .!= 0 ) == 45 # Test 3: Keep largest blob in input matrix a @test sum(IceFloeTracker.bwareamaxfilt(A)) == 45 # Test 4: In-place version of bwareamaxfilt A_copy = copy(A) IceFloeTracker.bwareamaxfilt!(A_copy) @test A_copy == IceFloeTracker.bwareamaxfilt(A) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2460
@testset "bwperim" begin println("-------------------------------------------------") println("---------------- bwperim Tests ------------------") # Create image with 3 connected components. The test consists of digging the biggests holes for each blob in the foreground using bwperim, thereby creating 3 additional connected components, 6 in total. A = zeros(Bool, 13, 16) A[2:6, 2:6] .= 1 A[4:8, 7:10] .= 1 A[10:12, 13:15] .= 1 A[10:12, 3:6] .= 1 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # count the components in A numinicomps = maximum(IceFloeTracker.label_components(A)) # dig the holes and relabel the interiors border_mask = IceFloeTracker.bwperim(A) # get the borders interior = A .& .!border_mask # keep the interior of the holes interior_relabel = IceFloeTracker.label_components(interior) * 2 # relabel the wholes A_relabeled = interior_relabel .+ border_mask # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 # 0 1 2 2 2 1 0 0 0 0 0 0 0 0 0 0 # 0 1 2 2 2 2 1 1 1 1 0 0 0 0 0 0 # 0 1 2 2 2 2 2 2 2 1 0 0 0 0 0 0 # 0 1 1 1 1 1 2 2 2 1 0 0 0 0 0 0 # 0 0 0 0 0 0 1 2 2 1 0 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 1 4 4 1 0 0 0 0 0 0 1 6 1 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 @test numinicomps + 3 == maximum(IceFloeTracker.label_components(A_relabeled, trues(3, 3))) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2574
@testset "bwtraceboundary test" begin println("-------------------------------------------------") println("------------ bwtraceboundary Tests --------------") # Create an image with 3 connected components. The test consists of identifying the three closed sequences of border pixels in the image below. We do so using bwtraceboundary. A = zeros(Int, 13, 16) A[2:6, 2:6] .= 1 A[4:8, 7:10] .= 1 A[10:12, 13:15] .= 1 A[10:12, 3:6] .= 1 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 # 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 # get boundaries closed by default, no point provided boundary = IceFloeTracker.bwtraceboundary(A) # Test 1: Check correct number of boundary pixels are obtained @test all([ length(boundary[1]) == 27, length(boundary[2]) == 11, length(boundary[3]) == 9 ]) # Test 2: Initial points for contours p1 = (2, 2) p2 = (12, 3) p3 = (10, 15) pbad = (0, 0) pint = (4, 4) # get a closed boundary starting at p1 out = IceFloeTracker.bwtraceboundary(A; P0=p1) @test all([length(boundary[1]) == length(out), out[1] == out[end]]) # get a closed boundary starting at p2 out = IceFloeTracker.bwtraceboundary(A; P0=p2) @test all([length(boundary[2]) == length(out), out[1] == out[end]]) # get a closed boundary starting at p3 out = IceFloeTracker.bwtraceboundary(A; P0=p3) @test all([length(boundary[3]) == length(out), out[1] == out[end]]) # test exterior point out = IceFloeTracker.bwtraceboundary(A; P0=pbad) @test boundary == out # test interior point out = IceFloeTracker.bwtraceboundary(A; P0=pint) @test boundary == out # test input is a BitMatrix @test IceFloeTracker.bwtraceboundary(A) == IceFloeTracker.bwtraceboundary(BitArray(A)) # test not closed @test length(IceFloeTracker.bwtraceboundary(A; P0=p1, closed=false)) == length(IceFloeTracker.bwtraceboundary(A; P0=p1)) - 1 end;
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1738
@testset "Create Cloudmask" begin println("-------------------------------------------------") println("------------ Create Cloudmask Test --------------") # define constants, maybe move to test config file matlab_cloudmask_file = "$(test_data_dir)/matlab_cloudmask.tiff" println("--------- Create and apply cloudmask --------") ref_image = float64.(load(falsecolor_test_image_file)[test_region...]) matlab_cloudmask = float64.(load(matlab_cloudmask_file)) @time cloudmask = IceFloeTracker.create_cloudmask(ref_image) @time masked_image = IceFloeTracker.apply_cloudmask(ref_image, cloudmask) # test for percent difference in cloudmask images @test (@test_approx_eq_sigma_eps masked_image matlab_cloudmask [0, 0] 0.005) == nothing # test for create_clouds_channel clouds_channel_expected = load(clouds_channel_test_file) clds_channel = IceFloeTracker.create_clouds_channel(cloudmask, ref_image) @test (@test_approx_eq_sigma_eps (clds_channel) (clouds_channel_expected) [0, 0] 0.005) == nothing # Persist output images cloudmask_filename = "$(test_output_dir)/cloudmask_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist cloudmask cloudmask_filename masked_image_filename = "$(test_output_dir)/cloudmasked_reflectance_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist masked_image masked_image_filename clouds_channel_filename = "$(test_output_dir)/clouds_channel_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist clds_channel clouds_channel_filename end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
3430
@testset "Create Landmask" begin println("------------------------------------------------") println("------------ Create Landmask Test --------------") # define constants, maybe move to test config file matlab_landmask_file = "$(test_data_dir)/matlab_landmask.png" matlab_landmask_no_dilate_file = "$(test_data_dir)/matlab_landmask_no_dilate.png" strel_file = "$(test_data_dir)/se.csv" struct_elem = readdlm(strel_file, ',', Bool) # read in original matlab structuring element - a disk-shaped kernel with radius of 50 px matlab_landmask = float64.(load(matlab_landmask_file)[lm_test_region...]) matlab_landmask_no_dilate = float64.(load(matlab_landmask_no_dilate_file)[lm_test_region...]) # land is white lm_image = float64.(load(landmask_file)[lm_test_region...]) test_image = load(truecolor_test_image_file)[lm_test_region...] @time landmask = IceFloeTracker.create_landmask(lm_image, struct_elem) # Test method with default se @test landmask == IceFloeTracker.create_landmask(lm_image) # Generate testing files @time landmask_no_dilate = landmask.non_dilated @time masked_image = IceFloeTracker.apply_landmask(test_image, landmask.dilated) @time masked_image_no_dilate = IceFloeTracker.apply_landmask( test_image, .!landmask_no_dilate ) # test for percent difference in landmask images @test test_similarity(.!landmask.dilated, convert(BitMatrix, matlab_landmask), 0.005) @test test_similarity( .!landmask.non_dilated, convert(BitMatrix, matlab_landmask_no_dilate), 0.005 ) # flipping the landmask to match the matlab landmask # test for in-place allocation reduction @time normal_lm = IceFloeTracker.apply_landmask(test_image, landmask.dilated) @time IceFloeTracker.apply_landmask!(test_image, landmask.dilated) x = @allocated IceFloeTracker.apply_landmask(test_image, landmask.dilated) @info("normal allocated: $x") y = @allocated IceFloeTracker.apply_landmask!(test_image, landmask.dilated) @info("in-place allocated: $y") @test x > y # test that the test image has been updated in-place and equals the new image with landmask applied @test(test_image == normal_lm) # persist imgs matlab_landmask_filename = "$(test_output_dir)/matlab_landmask_test_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist matlab_landmask matlab_landmask_filename landmask_filename = "$(test_output_dir)/landmask_test_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist landmask.dilated landmask_filename landmask_no_dilate_filename = "$(test_output_dir)/landmask_test_no_dilate_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist landmask.non_dilated landmask_no_dilate_filename masked_image_filename = "$(test_output_dir)/landmasked_truecolor_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist masked_image masked_image_filename masked_image_no_dilate_filename = "$(test_output_dir)/landmasked_truecolor_test_no_dilate_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist masked_image_no_dilate masked_image_no_dilate_filename end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1493
@testset "crosscorr tests" begin println("-------------------------------------------------") println("----------- cross correlation tests -------------") # Compare against matlab xcorr with normalization (standard use case in IceFloeTracker) n = 0:15 x = 0.84 .^ n y = circshift(x, 5) # [cnormalized,lags] = xcorr(x,y,'coef'); (matlab call) # Output of matlab call above c_matlab = [ 0.0516860456455592, 0.104947285063174, 0.161406917930332, 0.222785618772511, 0.290953976567756, 0.367989503172686, 0.456239947969545, 0.558394848323571, 0.677567496436029, 0.817389820630348, 0.982123072691496, 0.846599102605261, 0.736876248026996, 0.649610574340982, 0.582142556253932, 0.532416025595572, 0.444053743842906, 0.369224528569261, 0.305647870356775, 0.251386194859924, 0.204785812920709, 0.164426522422887, 0.129078325941762, 0.097663945108386, 0.0692259892687896, 0.0428977778640515, 0.0178769273085035, 0.0136884958891382, 0.00991723767782281, 0.00644821909097442, 0.00317571765737478, ] # Compute normalized cross correlation scores and lags with padding r, lags = IceFloeTracker.crosscorr(x, y; normalize=true) # Test @test all(round.(c_matlab, digits=5) .== round.(r, digits=5)) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1461
@testset "Discriminate Ice-Water" begin println("------------------------------------------------") println("------------ Create Ice-Water Discrimination Test --------------") input_image = float64.(load(truecolor_test_image_file)[test_region...]) falsecolor_image = float64.(load(falsecolor_test_image_file)[test_region...]) landmask = convert(BitMatrix, load(current_landmask_file)) landmask_no_dilate = convert(BitMatrix, float64.(load(landmask_no_dilate_file))) cloudmask = IceFloeTracker.create_cloudmask(falsecolor_image) matlab_ice_water_discrim = float64.(load("$(test_data_dir)/matlab_ice_water_discrim.png")) image_sharpened = IceFloeTracker.imsharpen(input_image, landmask_no_dilate) image_sharpened_gray = IceFloeTracker.imsharpen_gray(image_sharpened, landmask) normalized_image = IceFloeTracker.normalize_image( image_sharpened, image_sharpened_gray, landmask ) ice_water_discrim = IceFloeTracker.discriminate_ice_water( falsecolor_image, normalized_image, landmask, cloudmask ) @test (@test_approx_eq_sigma_eps ice_water_discrim matlab_ice_water_discrim [0, 0] 0.065) == nothing # persist generated image ice_water_discrim_filename = "$(test_output_dir)/ice_water_discrim_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist ice_water_discrim ice_water_discrim_filename end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
937
@testset "Find_Ice_Labels" begin println("------------------------------------------------") println("------------ Create Ice Labels Test --------------") falsecolor_image = float64.(load(falsecolor_test_image_file)[test_region...]) landmask = convert(BitMatrix, load(current_landmask_file)) ice_labels_matlab = DelimitedFiles.readdlm( "$(test_data_dir)/ice_labels_matlab.csv", ',' ) ice_labels_matlab = vec(ice_labels_matlab) @time ice_labels_julia = IceFloeTracker.find_ice_labels(falsecolor_image, landmask) DelimitedFiles.writedlm("ice_labels_julia.csv", ice_labels_julia, ',') @test ice_labels_matlab == ice_labels_julia @time ice_labels_ice_floe_region = IceFloeTracker.find_ice_labels( falsecolor_image[ice_floe_test_region...], landmask[ice_floe_test_region...] ) DelimitedFiles.writedlm("ice_labels_floe_region.csv", ice_labels_ice_floe_region, ',') end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
417
@testset "hbreak tests" begin h1, h2 = keys(IceFloeTracker.make_hbreak_dict()) A = zeros(Bool, 20, 20) # Make 4 H-connected groups on each corner of A A[1:3, 1:3] = h1 A[1:3, (end - 2):end] = h2 A[(end - 2):end, 1:3] = h1 A[(end - 2):end, (end - 2):end] = h2 A[10:12, 10:12] = h1 # and another in the middle for good measure @test sum(A) == sum(IceFloeTracker.hbreak(A)) + 5 end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2349
@testset "tracker/matchcorr" begin path = joinpath(test_data_dir, "tracker") @testset "matchcorr" begin floes = deserialize.([ joinpath(path, f) for f in ["f1.dat", "f2.dat", "f3.dat", "f4.dat"] ]) mm, c = matchcorr(floes[1], floes[2], 400.0) @test isapprox(mm, 0.0; atol=0.05) && isapprox(c, 0.99; atol=0.05) @test all(isnan.(collect(matchcorr(floes[3], floes[4], 400.0)))) end @testset "tracker" begin # Set thresholds t1 = (dt=(30.0, 100.0, 1300.0), dist=(200, 250, 300)) t2 = ( area=1200, arearatio=0.28, majaxisratio=0.10, minaxisratio=0.12, convexarearatio=0.14, ) t3 = ( area=10_000, arearatio=0.18, majaxisratio=0.1, minaxisratio=0.15, convexarearatio=0.2, ) condition_thresholds = (t1, t2, t3) mc_thresholds = ( goodness=(area3=0.18, area2=0.236, corr=0.68), comp=(mxrot=10, sz=16) ) dt = [15.0, 20.0] # Load data data = deserialize(joinpath(path, "tracker_test_data.dat")) passtimes = deserialize(joinpath(path, "passtimes.dat")) latlonimgpth = "test_inputs/NE_Greenland_truecolor.2020162.aqua.250m.tiff" # Filtering out small floes. Algorithm performs poorly on small, amorphous floes as they seem to look similar (too `blobby`) to each other for (i, prop) in enumerate(data.props) data.props[i] = prop[prop[:, :area].>=350, :] end _pairs = IceFloeTracker.pairfloes( data.imgs, data.props, passtimes, latlonimgpth, condition_thresholds, mc_thresholds ) @test maximum(_pairs.ID) == 6 expectedcols = ["ID", "passtime", "area", "convex_area", "major_axis_length", "minor_axis_length", "orientation", "perimeter", "area_mismatch", "corr", "latitude", "longitude", "x", "y"] @test all([name in expectedcols for name in names(_pairs)]) @test issorted(_pairs, :ID) @test all([issorted(grp, :passtime) for grp in groupby(_pairs, :ID)]) end end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
610
println("------------------------------------------------ ----------------- Misc. Tests ------------------") # Define a test to check the version number of the package matches the version number in the Project.toml file. Use the get_version_from_toml function to get the version number from the Project.toml file. The version number is then compared to the version number of the package. If the version numbers match, the test passes. If the version numbers do not match, the test fails. @testset "Version number" begin @test IceFloeTracker.get_version_from_toml(dirname((@__DIR__))) == IFTVERSION end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1895
@testset "MorphSE test" begin println("------------------------------------------------") println("---------------- MorphSE Tests -----------------") # Dilate -- Start with a pixel in the middle and dilate in one go to fill up the full image n = rand(11:2:21) # choose random odd number mid = (n - 1) Γ· 2 + 1 # get median a = zeros(Int, n, n) a[mid, mid] = 1 # make 1 the pixel in the center se = IceFloeTracker.MorphSE.strel_box((n, n)) @test IceFloeTracker.MorphSE.dilate(a, se) == ones(Int, n, n) # Bothat, opening, erode, filling holes, reconstruction using output from Matlab A = zeros(Bool, 41, 41) A[(21 - 10):(21 + 10), (21 - 10):(21 + 10)] .= 1 I = falses(8, 8) I[1:8, 3:6] .= 1 I[[CartesianIndex(4, 4), CartesianIndex(5, 5)]] .= 0 I se = centered(IceFloeTracker.se_disk4()) #read in expected files from MATLAB path = joinpath(test_data_dir, "morphSE") erode_withse_exp = readdlm(joinpath(path, "erode_withse1_exp.csv"), ',', Bool) bothat_withse_exp = readdlm(joinpath(path, "bothat_withse1_exp.csv"), ',', Bool) open_withse_exp = readdlm(joinpath(path, "open_withse1_exp.csv"), ',', Bool) reconstruct_exp = readdlm(joinpath(path, "reconstruct_exp.csv"), ',', Int64) matrix_A = readdlm(joinpath(path, "mat_a.csv"), ',', Int64) matrix_B = readdlm(joinpath(path, "mat_b.csv"), ',', Int64) filled_holes_exp = readdlm(joinpath(path, "filled_holes.csv"), ',', Int64) #run tests @test open_withse_exp == IceFloeTracker.MorphSE.opening(A, se) @test erode_withse_exp == IceFloeTracker.MorphSE.erode(A, se) @test bothat_withse_exp == IceFloeTracker.MorphSE.bothat(A, se) @test reconstruct_exp == IceFloeTracker.MorphSE.mreconstruct( IceFloeTracker.MorphSE.dilate, matrix_B, matrix_A ) @test filled_holes_exp == IceFloeTracker.MorphSE.fill_holes(I) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
3765
@testset "Normalize Image" begin println("-------------------------------------------------") println("---------- Create Normalization Test ------------") struct_elem2 = strel_diamond((5, 5)) #original matlab structuring element - a disk-shaped kernel with radius of 2 px matlab_normalized_img_file = "$(test_data_dir)/matlab_normalized.png" matlab_sharpened_file = "$(test_data_dir)/matlab_sharpened.png" matlab_diffused_file = "$(test_data_dir)/matlab_diffused.png" matlab_equalized_file = "$(test_data_dir)/matlab_equalized.png" landmask_bitmatrix = convert(BitMatrix, float64.(load(current_landmask_file))) landmask_no_dilate = convert(BitMatrix, float64.(load(landmask_no_dilate_file))) input_image = float64.(load(truecolor_test_image_file)[test_region...]) matlab_norm_image = float64.(load(matlab_normalized_img_file)[test_region...]) matlab_sharpened = float64.(load(matlab_sharpened_file)) matlab_diffused = float64.(load(matlab_diffused_file)[test_region...]) matlab_equalized = float64.(load(matlab_equalized_file)) println("-------------- Process Image - Diffusion ----------------") input_landmasked = IceFloeTracker.apply_landmask(input_image, landmask_no_dilate) @time image_diffused = IceFloeTracker.diffusion(input_landmasked, 0.1, 75, 3) @test (@test_approx_eq_sigma_eps image_diffused matlab_diffused [0, 0] 0.0054) == nothing @test (@test_approx_eq_sigma_eps input_landmasked image_diffused [0, 0] 0.004) == nothing @test (@test_approx_eq_sigma_eps input_landmasked matlab_diffused [0, 0] 0.007) == nothing diffused_image_filename = "$(test_output_dir)/diffused_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist image_diffused diffused_image_filename println("-------------- Process Image - Equalization ----------------") ## Equalization masked_view = (channelview(matlab_diffused)) eq = [ IceFloeTracker._adjust_histogram(masked_view[i, :, :], 255, 10, 10, 0.86) for i in 1:3 ] image_equalized = colorview(RGB, eq...) @test (@test_approx_eq_sigma_eps image_equalized matlab_equalized [0, 0] 0.051) == nothing equalized_image_filename = "$(test_output_dir)/equalized_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist image_equalized equalized_image_filename println("-------------- Process Image - Sharpening ----------------") ## Sharpening @time sharpenedimg = IceFloeTracker.imsharpen(input_image, landmask_no_dilate) @time image_sharpened_gray = IceFloeTracker.imsharpen_gray( sharpenedimg, landmask_bitmatrix ) @test (@test_approx_eq_sigma_eps image_sharpened_gray matlab_sharpened [0, 0] 0.046) == nothing sharpened_image_filename = "$(test_output_dir)/sharpened_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist image_sharpened_gray sharpened_image_filename println("-------------- Process Image - Normalization ----------------") ## Normalization @time normalized_image = IceFloeTracker.normalize_image( sharpenedimg, image_sharpened_gray, landmask_bitmatrix, struct_elem2 ) #test for percent difference in normalized images @test (@test_approx_eq_sigma_eps normalized_image matlab_norm_image [0, 0] 0.045) == nothing normalized_image_filename = "$(test_output_dir)/normalized_test_image_" * Dates.format(Dates.now(), "yyyy-mm-dd-HHMMSS") * ".png" IceFloeTracker.@persist normalized_image normalized_image_filename end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1792
@testset "persist.jl" begin println("-------------------------------------------------") println("---------- Persist Image Tests ------------") outimage_path = "outimage1.tiff" img = ones(3, 3) # Test filename in variable @persist img outimage_path @test isfile(outimage_path) # Test filename as string literal @persist img "outimage2.tiff" @test isfile("outimage2.tiff") # Test no-filename call. Default filename startswith 'persisted_img-' # First clear all files that start with this prefix, if any prefix = "persisted_img-" [rm(f) for f in readdir() if startswith(f, prefix)] @persist img @test length([f for f in readdir() if startswith(f, prefix)]) == 1 # clean up - part 1! rm(outimage_path) rm("outimage2.tiff") [rm(f) for f in readdir() if startswith(f, prefix)] # Part 2 # Test call expressions @persist identity(img) outimage_path @persist identity(img) "outimage2.tiff" @persist identity(img) # no file name given @test isfile(outimage_path) @test isfile("outimage2.tiff") @test length([f for f in readdir() if startswith(f, prefix)]) == 1 # Part 3 # Test filename as Expr, such as "$(dir)$(fname).$(ext)" fname = "persistedimg" ext = "png" @persist img "$(fname).$(ext)" @test isfile("$(fname).$(ext)") # Part 4 # Test timestamp [rm(f) for f in readdir() if startswith(f, "foo")] # clear "foo*" files # Persist twice the same img with different ts @persist img "foo.png" true foos = [f for f in readdir() if startswith(f, "foo")] @test length(foos) == 1 @test length(foos[1]) == 25 # ts adds 19 chars # Clean up [rm(f) for f in readdir() if endswith(f, "png") || endswith(f, "tiff")] end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1677
@testset "ψ-s curve test" begin # draw cardioid https://en.wikipedia.org/wiki/Cardioid t = range(0, 2pi, 201) x = @. cos(t) * (1 - cos(t)) y = @. (1 - cos(t)) * sin(t) ψ, s = IceFloeTracker.make_psi_s(x, y) # Test 0: Continuity for smooth curves (except initial/final point for cardioid) @test all((ψ[2:end] - ψ[1:(end - 1)]) .< 0.05) # Test 1: initial/final phase [0, 3Ο€] @test all([ψ[1] < 0.05, abs(ψ[end] - 3pi) < 0.05]) # Test 2: Option unwrap=false; cardioid will have one discontinuity ΞΈ, s = IceFloeTracker.make_psi_s(x, y; rangeout=true, unwrap=false) @test sum((abs.(ΞΈ[2:end] - ΞΈ[1:(end - 1)])) .> 0.05) == 1 # Test 3: Option rangeout=false, unwrap=false. There will be negative phase values. p_wrapped, _ = IceFloeTracker.make_psi_s(x, y; rangeout=false, unwrap=false) @test !all(p_wrapped .>= 0) # Test 4: Return arclength; compare against theoretical total arclength = 8 _, s = IceFloeTracker.make_psi_s(x, y; rangeout=true) @test abs(s[end] - 8) < 0.005 # Test 5: Auxiliary functions A = [x y] # norm of a Vector @test all([ IceFloeTracker.norm(x) == sum(x .^ 2)^0.5, IceFloeTracker.norm(y) == sum(y .^ 2)^0.5 ]) # norm of a row/col @test all([ IceFloeTracker.norm(A[1, :]) == sum(A[1, :] .^ 2)^0.5, IceFloeTracker.norm(A[:, 1]) == sum(A[:, 1] .^ 2)^0.5, ]) # test grad methods for vectors and matrices @test IceFloeTracker.grad(x, y) == IceFloeTracker.grad(A) # Test 6: Alternate method of make_psi_s with 2-column matrix as input @test IceFloeTracker.make_psi_s(x, y) == IceFloeTracker.make_psi_s([x y]) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1838
@testset "regionprops.jl" begin println("-------------------------------------------------") println("-------------- regionprops Tests ----------------") Random.seed!(123) bw_img = Bool.(rand([0, 1], 5, 10)) bw_img[end, 7] = 1 label_img = IceFloeTracker.label_components(bw_img, trues(3, 3)) properties = ( "centroid", "area", "major_axis_length", "minor_axis_length", "convex_area", "bbox", "perimeter", "orientation", ) extra_props = nothing table = IceFloeTracker.regionprops_table(label_img, bw_img; properties=properties) total_labels = maximum(label_img) # Tests for regionprops_table @test typeof(table) <: DataFrame && # check correct data type 6 == sum([p in names(table) for p in properties]) && # check correct set of properties size(table) == (total_labels, length(properties) + 4) # check correct table size # Check no value in bbox cols is 0 (zero indexing from skimage) @test all(Matrix(table[:, ["min_row", "min_col", "max_row", "max_col"]] .> 0)) # Check no value in centroid cols is 0 (zero indexing from skimage) @test all(Matrix(table[:, ["row_centroid", "col_centroid"]] .> 0)) # check default properties @test table == IceFloeTracker.regionprops_table(label_img) # Tests for regionprops regions = IceFloeTracker.regionprops(label_img, bw_img) # Check some data matches in table randnum = rand(1:total_labels) @test table.area[randnum] == regions[randnum].area # Check floe masks generation and correct cropping IceFloeTracker.addfloemasks!(table, bw_img) @test all( [ length(unique(label_components(table.mask[i], trues(3, 3)))) for i in 1:nrow(table) ] .== [2, 2, 1], ) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
499
@testset "register_mismatch tests" begin # Read in floe from file floe = readdlm("./test_inputs/floetorotate.csv", ',', Bool) # Define rotation angle rot_angle = 15 # degrees # Rotate floe rotated_floe = imrotate(floe, deg2rad(rot_angle)) # Estimate rigid transformation and mismatch mm, rot = IceFloeTracker.mismatch(floe, rotated_floe) # Test 1: mismatch accuracy @test mm < 0.005 # Test 2: angle estimate @test abs(rot - rot_angle) < 0.05 end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1835
@testset "resample_boundary test" begin println("-------------------------------------------------") println("------------ resample_boundary Tests --------------") # Create an image with 3 connected components. The test consists of identifying the three closed sequences of border pixels in the image below. We do so using bwtraceboundary. A = zeros(Int, 9, 11) A[2:6, 2:6] .= 1 A[4:8, 7:10] .= 1 # 0 0 0 0 0 0 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 # 0 1 1 1 1 1 0 0 0 0 0 # 0 1 1 1 1 1 1 1 1 1 0 # 0 1 1 1 1 1 1 1 1 1 0 # 0 1 1 1 1 1 1 1 1 1 0 # 0 0 0 0 0 0 1 1 1 1 0 # 0 0 0 0 0 0 1 1 1 1 0 # 0 0 0 0 0 0 0 0 0 0 0 # get boundary of biggest blob in image boundary = IceFloeTracker.bwtraceboundary(A; P0=(2, 2)) # get resampled set of boundary points resampled_boundary = IceFloeTracker.resample_boundary(boundary) # Test 0: Check data type of resampled_boundary is Matrix{Float64} @test typeof(resampled_boundary) <: Matrix{Float64} # Test 1: Check correct number of resampled pixels where obtained @test size(resampled_boundary)[1] == length(boundary) Γ· 2 # Test 2: Check perimeters are comparable (less than 10% after regularization by half the points) # make dist function norm(u) = (u[1]^2 + u[2]^2)^0.5 per1 = sum([norm(u) for u in (boundary[2:end] - boundary[1:(end - 1)])]) difs2 = [ norm(u) for u in eachrow(resampled_boundary[2:end, :] - resampled_boundary[1:(end - 1), :]) ] per2 = sum(difs2) d = abs(per1 - per2) / per1 @test d < 0.1 # Test 3: Check distances between a pair of adjacent points is about the same (small standard deviation) IceFloeTracker.std(difs2) < 1.0 end;
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
2194
@testset "Segmentation-A" begin println("------------------------------------------------") println("------------ Create Segmentation-A Test --------------") ice_water_discriminated_image = float64.(load("$(test_data_dir)/matlab_ice_water_discrim.png")) cloudmask = convert(BitMatrix, load(cloudmask_test_file)) landmask = convert(BitMatrix, load(current_landmask_file)) ice_labels = DelimitedFiles.readdlm("$(test_data_dir)/ice_labels_julia.csv", ',') ice_labels = Int64.(vec(ice_labels)) matlab_segmented_A = float64.(load("$(test_data_dir)/matlab_segmented_A.png")) matlab_segmented_A_bitmatrix = convert(BitMatrix, matlab_segmented_A) matlab_segmented_ice = convert( BitMatrix, float64.(load("$(test_data_dir)/matlab_segmented_ice.png")) ) matlab_segmented_ice_cloudmasked = load("$(test_data_dir)/matlab_segmented_ice_cloudmasked.png") .> 0.5 println("---------- Segment Image - Direct Method ------------") @time segmented_ice_cloudmasked = IceFloeTracker.segmented_ice_cloudmasking( ice_water_discriminated_image, cloudmask, ice_labels ) IceFloeTracker.@persist segmented_ice_cloudmasked "./test_outputs/segmented_a_ice_cloudmasked.png" true @time segmented_A = IceFloeTracker.segmentation_A(segmented_ice_cloudmasked) IceFloeTracker.@persist segmented_A "./test_outputs/segmented_a.png" true @time segmented_ice = IceFloeTracker.kmeans_segmentation( ice_water_discriminated_image, ice_labels ) IceFloeTracker.@persist segmented_ice "./test_outputs/segmented_a_ice.png" true @test typeof(segmented_A) == typeof(matlab_segmented_A_bitmatrix) @test test_similarity(matlab_segmented_A_bitmatrix, segmented_A, 0.039) @test typeof(segmented_ice_cloudmasked) == typeof(matlab_segmented_ice_cloudmasked) @test test_similarity( convert( BitMatrix, IceFloeTracker.apply_landmask(segmented_ice_cloudmasked, landmask) ), matlab_segmented_ice_cloudmasked, 0.051, ) @test typeof(segmented_ice) == typeof(matlab_segmented_ice) @test test_similarity(matlab_segmented_ice, segmented_ice, 0.001) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1559
@testset "Segmentation-B" begin println("------------------------------------------------") println("------------ Create Segmentation-B Test --------------") sharpened_image = float64.(load(sharpened_test_image_file)) segmented_a_ice_mask = convert(BitMatrix, load(segmented_a_ice_mask_file)) cloudmask = convert(BitMatrix, load(cloudmask_test_file)) matlab_ice_intersect = convert( BitMatrix, load("$(test_data_dir)/matlab_segmented_c.png") ) matlab_not_ice_mask = float64.(load("$(test_data_dir)/matlab_I.png")) #matlab_not_ice_bit = matlab_not_ice_mask .> 0.499 @time segB = IceFloeTracker.segmentation_B( sharpened_image, cloudmask, segmented_a_ice_mask ) IceFloeTracker.@persist segB.not_ice "./test_outputs/segB_not_ice_mask.png" true IceFloeTracker.@persist segB.ice_intersect "./test_outputs/segB_ice_mask.png" true IceFloeTracker.@persist matlab_not_ice_mask "./test_outputs/matlab_not_ice_mask.png" true IceFloeTracker.@persist matlab_ice_intersect "./test_outputs/matlab_ice_intersect.png" true @test typeof(segB.not_ice) == typeof(matlab_not_ice_mask) @test (@test_approx_eq_sigma_eps segB.not_ice matlab_not_ice_mask [0, 0] 0.001) == nothing @test typeof(segB.not_ice_bit) == typeof(matlab_not_ice_mask .> 0.499) @test test_similarity((matlab_not_ice_mask .> 0.499), segB.not_ice_bit, 0.001) @test typeof(segB.ice_intersect) == typeof(matlab_ice_intersect) @test test_similarity(matlab_ice_intersect, segB.ice_intersect, 0.005) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1459
@testset "Segmentation-F" begin println("------------------------------------------------") println("--------- Create Segmentation-F Test -----------") ## Load inputs for comparison segmentation_B_not_ice_mask = float64.(load("$(test_data_dir)/matlab_I.png")) segmentation_B_ice_intersect = convert(BitMatrix, load(segmented_c_test_file)) matlab_BW7 = load("$(test_data_dir)/matlab_BW7.png") .> 0.499 ## Load function arg files cloudmask = convert(BitMatrix, load(cloudmask_test_file)) landmask = convert(BitMatrix, load(current_landmask_file)) watershed_intersect = load(watershed_test_file) .> 0.499 ice_labels = Int64.( vec(DelimitedFiles.readdlm("$(test_data_dir)/ice_labels_floe_region.csv", ',')) ) ## Run function with Matlab inputs @time isolated_floes = IceFloeTracker.segmentation_F( segmentation_B_not_ice_mask[ice_floe_test_region...], segmentation_B_ice_intersect[ice_floe_test_region...], watershed_intersect[ice_floe_test_region...], ice_labels, cloudmask[ice_floe_test_region...], landmask[ice_floe_test_region...], ) IceFloeTracker.@persist isolated_floes "./test_outputs/isolated_floes.png" true IceFloeTracker.@persist matlab_BW7[ice_floe_test_region...] "./test_outputs/matlab_isolated_floes.png" true @test test_similarity(matlab_BW7[ice_floe_test_region...], isolated_floes, 0.013) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1958
@testset "Segmentation-Watershed" begin println("------------------------------------------------") println("------------ Create Segmentation-Watershed Test --------------") matlab_not_ice = load("$(test_data_dir)/matlab_not_ice_mask.png") matlab_not_ice_bit = matlab_not_ice .> 0.499 matlab_ice_intersect = convert( BitMatrix, load("$(test_data_dir)/matlab_segmented_c.png") ) matlab_watershed_D = convert(BitMatrix, load("$(test_data_dir)/matlab_watershed_D.png")) matlab_watershed_E = convert(BitMatrix, load("$(test_data_dir)/matlab_watershed_E.png")) matlab_watershed_intersect = convert( BitMatrix, load("$(test_data_dir)/matlab_watershed_intersect.png") ) ## Run function with Matlab inputs @time watershed_B_ice_intersect = IceFloeTracker.watershed_ice_floes( matlab_ice_intersect ) @time watershed_B_not_ice = IceFloeTracker.watershed_ice_floes(matlab_not_ice_bit) @time watershed_intersect = IceFloeTracker.watershed_product( watershed_B_ice_intersect, watershed_B_not_ice ) IceFloeTracker.@persist watershed_B_ice_intersect "./test_outputs/watershed_ice_intersect.png" true IceFloeTracker.@persist watershed_B_not_ice "./test_outputs/watershed_not_ice.png" true IceFloeTracker.@persist watershed_intersect "./test_outputs/watershed_intersect.png" true IceFloeTracker.@persist matlab_not_ice_bit "./test_outputs/matlab_not_ice_bit.png" true ## Tests with Matlab inputs @test typeof(watershed_B_not_ice) == typeof(matlab_watershed_E) @test typeof(watershed_B_ice_intersect) == typeof(matlab_watershed_D) @test typeof(watershed_intersect) == typeof(matlab_watershed_intersect) @test test_similarity(matlab_watershed_D, watershed_B_ice_intersect, 0.12) @test test_similarity(matlab_watershed_E, watershed_B_not_ice, 0.15) @test test_similarity(matlab_watershed_intersect, watershed_intersect, 0.033) end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1332
@testset "imextendedmin and bwdist" begin println("-------------------------------------------------") println("------- imextendedmin bwdist Tests --------------") test_matrix = "$(test_data_dir)/test_extendedmin.csv" test_image = DelimitedFiles.readdlm(test_matrix, ',', Bool) # Test matrix # 10Γ—10 BitMatrix: # 1 1 1 1 1 1 1 1 1 0 # 1 1 1 1 1 1 1 0 1 0 # 1 1 1 0 1 1 1 1 1 1 # 1 1 0 0 1 1 1 1 1 1 # 1 1 1 1 1 1 1 1 1 1 # 1 1 1 1 1 1 1 1 1 1 # 1 1 1 1 1 0 1 1 1 1 # 1 1 1 1 1 1 1 1 0 1 # 1 0 1 1 1 1 1 1 1 1 # 1 0 1 1 1 1 1 1 1 1 matlab_extendedmin_output_file = "$(test_data_dir)/test_extendedmin_output.csv" matlab_extendedmin_output = DelimitedFiles.readdlm( matlab_extendedmin_output_file, ',', Bool ) # Test workflow for watershed segmentation distances = -IceFloeTracker.bwdist(.!test_image) extendedmin_bitmatrix = IceFloeTracker.imextendedmin(distances) # Matlab output # 10Γ—10 BitMatrix: # 1 1 1 1 1 1 0 0 0 0 # 1 1 0 0 0 1 0 0 0 0 # 1 0 0 0 0 1 0 0 0 0 # 1 0 0 0 0 1 1 1 1 1 # 1 0 0 0 0 1 1 1 1 1 # 1 1 1 1 0 0 0 1 1 1 # 1 1 1 1 0 0 0 0 0 0 # 0 0 0 1 0 0 0 0 0 0 # 0 0 0 1 1 1 1 0 0 0 # 0 0 0 1 1 1 1 1 1 1 @test extendedmin_bitmatrix == matlab_extendedmin_output end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
1211
@testset "utils.jl pad utilities" begin println("-------------------------------------------------") println("--------------- Pad Image Tests -----------------") fill_value = 0 simpleimg = collect(reshape(1:4, 2, 2)) w, h = size(simpleimg) # 2Γ—2 Matrix{Int64}: # 1 3 # 2 4 lo = (1, 2) hi = (3, 4) fil_type = Fill(fill_value, lo, hi) rep_type = Pad(:replicate, lo, hi) fil_paddedimg = IceFloeTracker.add_padding(simpleimg, fil_type) rep_paddedimg = IceFloeTracker.add_padding(simpleimg, rep_type) # test replicate padding at corners @test rep_paddedimg[1, 1] == 1 && rep_paddedimg[1, end] == 3 && rep_paddedimg[end, 1] == 2 && rep_paddedimg[end, end] == 4 # test filled image at the corners @test fil_paddedimg[1, 1] == fil_paddedimg[1, end] == fil_paddedimg[end, 1] == fil_paddedimg[end, end] == 0 # test sizing @test size(fil_paddedimg) == (h + lo[1] + hi[1], w + lo[2] + hi[2]) # test padding removal @test IceFloeTracker.remove_padding(fil_paddedimg, fil_type) == simpleimg @test IceFloeTracker.remove_padding(rep_paddedimg, rep_type) == simpleimg end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
code
356
function test_similarity(imgA::BitMatrix, imgB::BitMatrix, error_rate=0.005) error = sum(imgA .!== imgB) / prod(size(imgA)) res = error_rate > error if res @info "Test passed with $error mismatch with threshold $error_rate" else @warn "Test failed with $error mismatch with threshold $error_rate" end return res end
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
docs
2927
# IceFloeTracker [![Build Status](https://github.com/WilhelmusLab/IceFloeTracker.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/WilhelmusLab/IceFloeTracker.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/WilhelmusLab/IceFloeTracker.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/WilhelmusLab/IceFloeTracker.jl) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://wilhelmuslab.github.io/IceFloeTracker.jl/) Track Ice Floes using Moderate Resolution Imaging Spectroradiometer (MODIS) data. ## Documentation See the package's documentation (in development) at https://wilhelmuslab.github.io/IceFloeTracker.jl/ ## Prerequisites A `julia` installation; ensure it is available on the `PATH`. ## Clone repo and run tests Clone the repository. ```zsh $ git clone https://github.com/WilhelmusLab/IceFloeTracker.jl ``` Now start a Julia session. ```zsh $ julia ``` ``` julia> ] ``` ... to enter package mode. ``` (@v1.9) pkg> activate IceFloeTracker.jl/ Activating project at `~/IceFloeTracker.jl` ``` Instantiate the environment and run the tests: ``` (IceFloeTracker) pkg> instantiate (IceFloeTracker) pkg> test ``` ## Notebooks There are Jupyter notebooks illustrating the main image processing and tracking functions, in the `/notebooks` folder. ## Interface for Pipeline Workflows See related tools in the [IFTPipeline repository](https://github.com/WilhelmusLab/ice-floe-tracker-pipeline#ice-floe-tracker-pipeline), including a Julia Command-line Interface and templates that leverage the [Cylc](https://cylc.github.io) pipeline orchestrator. ## Development Git hooks are used to run common developer tasks on commits (e.g. code formatting, tests, etc.). If you are running git version 2.9 or later run the following from the root of the project to enable git hooks. ``` git config core.hooksPath ./hooks ``` To help with passing git hooks, run the formatting script before staging files: ``` ./scripts/format.jl git add . git commit -m "some informative message" git push ``` ### Versioning the registered package 1. Update the major or minor version numbers in the corresponding field at the top of `Project.toml` 2. Add `@JuliaRegistrator register` in a comment in the commit you wish to use for the release - this bot will open a PR on the [Julia registry](https://github.com/JuliaRegistries/General/tree/master/I/IceFloeTracker) for the package 3. Wait for feedback from the bot to make sure the new version is accepted and merged to the Julia registry 4. Create a new version tag - The bot will generate git commands that you can run in a terminal to add a tag 5. Create the new release on the [repo console](https://github.com/WilhelmusLab/IceFloeTracker.jl/releases) - Click on `Draft a new release` - Choose the new tag you created - Click on `Generate release notes` or add a custom description
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
docs
199
# IceFloeTracker Documentation for IceFloeTracker.jl package. ```@contents ``` ## Functions ```@autodocs Modules = [IceFloeTracker] Order = [:function, :macro, :type] ``` ## Index ```@index ```
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
0.5.0
945ba13f54390ab0147b8a7dd41185264b85505a
docs
702
## Recommened Settings 1. Install Julia 2. Install VS Code 3. Add the following extensions for VS Code: Julia, Jupyter 4. (Optional) Ensure Julia is set up to work with threading enabled for shared memory multiprocessing. a. Press Cmd+Shift+P (mac) or Ctrl+Shift+P (windows) to display the command palette and search for `settings.json` and choose the option that appears ![Alt text](imgs/settings.png) b. In the `settings.json` file, find the ` "julia.NumThreads"` option (near the bottom). Change its value to `"auto"` and save the file ![Alt text](imgs/set-threads-auto.png) 5. Open the `./notebooks/preprocessing-workflow/preprocessing-workflow.ipynb` file within VS Code
IceFloeTracker
https://github.com/WilhelmusLab/IceFloeTracker.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
37
using Conda Conda.add("astroquery")
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
576
using Documenter using Pkg push!(LOAD_PATH, joinpath(@__DIR__, "../src/")) Pkg.develop(path=abspath(joinpath(@__DIR__, "../"))) using Supernovae DocMeta.setdocmeta!(Supernovae, :DocTestSetup, :(using Supernovae); recursive=true) makedocs( sitename="Supernovae Documentation", modules = [Supernovae], pages = [ "Supernovae" => "index.md", "Usage" => "usage.md", "API" => "api.md" ], format = Documenter.HTML( assets = ["assets/favicon.ico"], ) ) deploydocs( repo = "github.com/OmegaLambda1998/Supernovae.jl.git" )
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
7286
# Filter Module module FilterModule # Internal Packages # External Packages using Unitful using UnitfulAstro using PyCall using Trapz # Exports export Filter export planck export synthetic_flux const h = 6.626e-34 * u"J / Hz" # Planck Constant const k = 1.381e-23 * u"J / K" # Boltzmann Constant const c = 299792458 * u"m / s" # Speed of light in a vacuum """ svo(facility::String, instrument::String, passband::String) Attempt to get filter transmission curve from [SVO](http://svo2.cab.inta-csic.es/theory/fps/). Uses the python package `astroquery` via PyCall. # Arguments - `facility::String`: SVO name for the filter's facility - `instrument::String`: SVO name for the filter's instrument - `passband::String`: SVO name for the filter's passband """ function svo(facility::String, instrument::String, passband::String) py""" from astroquery.svo_fps import SvoFps def svo(svo_name): try: return SvoFps.get_transmission_data(svo_name) except: return None """ svo_name = "$facility/$instrument.$passband" return py"svo"(svo_name) end """ struct Filter Photometric filter transmission curve. # Fields - `facility::String`: Name of the filter's facility (NewHorizons, Keper, Tess, etc...) - `instrument::String`: Name of the filter's instrument (Bessell, CTIO, Landolt, etc...) - `passband::String`: Name of the filter's passband (g, r, i, z, etc...) - `wavelength::Vector{Γ…}`: Transmission curve wavelength - `transmission::Vector{Float64}`: Transmission curve transmission """ struct Filter facility::String # Facility name (NewHorizons, Keper, Tess, etc...) instrument::String # Instrument name (Bessell, CTIO, Landolt, etc...) passband::String # Filter name (g, r, i, z, etc...) wavelength::Vector{typeof(1.0u"β„«")} # Default unit of Angstrom transmission::Vector{Float64} # Unitless end """ Filter(facility::String, instrument::String, passband::String, svo::PyCall.PyObject) Make [`Filter`](@ref) object from [`svo`](@ref) transmission curve. # Arguments - `facility::String`: Name of the filter's facility - `instrument::String`: Name of the filter's instrument - `passband::String`: Name of the filter's passband - `svo::Pycall.PyObject`: SVO transmission curve """ function Filter(facility::String, instrument::String, passband::String, svo::PyCall.PyObject) wavelength = svo.__getitem__("Wavelength") transmission = svo.__getitem__("Transmission") return Filter(facility, instrument, passband, wavelength .* u"Γ…", transmission) end """ Filter(facility::String, instrument::String, passband::String, filter_file::AbstractString) Make [`Filter`](@ref) object from `filter_file` transmission curve. # Arguments - `facility::String`: Name of the filter's facility - `instrument::String`: Name of the filter's instrument - `passband::String`: Name of the filter's passband - `filter_file::AbstractString`: Path to transmission curve file. Assumed to be a comma delimited wavelength,transmission file. """ function Filter(facility::String, instrument::String, passband::String, filter_file::AbstractString) lines = open(filter_file) do io ls = [line for line in readlines(io) if line != ""] return ls end wavelength = [] transmission = [] for line in lines w, t = split(line, ',') w = parse(Float64, w) * u"Γ…" t = parse(Float64, t) push!(wavelength, w) push!(transmission, t) end return Filter(facility, instrument, passband, wavelength, transmission) end """ Filter(facility::String, instrument::String, passband::String, config::Dict{String, Any}) Make [`Filter`](@ref) object from `config` options. `config` must include "FILTER_PATH" => path/to/transmission_curve. If this file exists, the transmission curve will be loaded via [`Filter(facility::String, instrument::String, passband::String, filter_file::AbstractString)`](@ref), otherwise attempt to create Filter via [`Filter(facility::String, instrument::String, passband::String, svo::PyCall.PyObject)`](@ref) and the SVO FPS database. # Arguments - `facility::String`: Name of the filter's facility - `instrument::String`: Name of the filter's instrument - `passband::String`: Name of the filter's passband - `config::Dict{String, Any}`: Options for creating a Filter. """ function Filter(facility::String, instrument::String, passband::String, config::Dict{String,Any}) filter_directory = config["FILTER_PATH"] filter_file = "$(facility)__$(instrument)__$(passband)" if !isfile(joinpath(filter_directory, filter_file)) @debug "Could not find $(filter_file) in $(filter_directory)" @debug "Attempting to find filter on SVO FPS" filter_svo = svo(facility, instrument, passband) if !isnothing(filter_svo) filter = Filter(facility, instrument, passband, filter_svo) save_filter(filter, filter_directory) return filter else error("Could not find $(filter_file) anywhere, no filter found with facility: $facility, instrument: $instrument, and passband: $passband") end else return Filter(facility, instrument, passband, joinpath(filter_directory, filter_file)) end end """ save_filter(filter::Filter, filter_dir::AbstractString) Save `filter` to directory `filter_dir`. # Arguments - `filter::Filter`: The [`Filter`](@ref) to save. - `filter_dir::AbstractString`: The directory to save `filter` to. """ function save_filter(filter::Filter, filter_dir::AbstractString) filter_path = joinpath(filter_dir, "$(filter.facility)__$(filter.instrument)__$(filter.passband)") @debug "Saving filter to $filter_path" filter_str = "" for i in 1:length(filter.wavelength) filter_str *= "$(ustrip(filter.wavelength[i])),$(filter.transmission[i])\n" end open(filter_path, "w") do io write(io, filter_str) end end """ planck(T::Unitful.Unitful.Temperature, Ξ»::Unitful.Length) Planck's law: Calculates the specral radiance of a blackbody at temperature T, emitting at wavelength Ξ» # Arguments - `T::Unitful.Temperature`: Temperature of blackbody - `Ξ»::Unitful.Length`: Wavelength of blackbody """ function planck(T::Unitful.Temperature, Ξ»::Unitful.Length) if T <= 0u"K" throw(DomainError(T, "Temperature must be strictly greater than 0 K")) end if Ξ» <= 0u"Γ…" throw(DomainError(Ξ», "Wavelength must be strictly greater than 0 Γ…")) end exponent = h * c / (Ξ» * k * T) B = (2Ο€ * h * c * c / (Ξ»^5)) / (exp(exponent) - 1) # Spectral Radiance return B end """ synthetic_flux(filter::Filter, T::Unitful.Temperature) Calculates the flux of a blackbody at temperature `T`, as observed with the `filter` # Arguments - `filter::Filter`: The [`Filter`](@ref) through which the blackbody is observed - `T::Unitful.Temperature`: The temperature of the blackbody """ function synthetic_flux(filter::Filter, T::Unitful.Temperature) numer = @. planck(T, filter.wavelength) * filter.transmission * filter.wavelength numer = trapz(numer, filter.wavelength) denom = @. filter.transmission / filter.wavelength denom = c .* trapz(denom, filter.wavelength) return abs(numer / denom) end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
22438
# Photometry Module module PhotometryModule # Internal Packages using ..FilterModule # External Packages using Unitful, UnitfulAstro const UNITS = [Unitful, UnitfulAstro] # Exports export Observation export Lightcurve export flux_to_mag, mag_to_flux export absmag_to_mag, mag_to_absmag const c = 299792458.0u"m / s" const Magnitude = Union{Quantity{T, dimension(1.0u"AB_mag"), U}, Level{L, S, Quantity{T, dimension(1.0u"AB_mag"), U}} where {L, S}} where {T, U} const Flux = Union{Quantity{T, dimension(1.0u"μJy"), U}, Level{L, S, Quantity{T, dimension(1.0u"μJy"), U}} where {L, S}} where {T, U} """ mutable struct Observation A single observation of a supernova, including time, flux, magnitude and filter information. # Fields - `name::String`: The name of the supernova - `time::typeof(1.0u"d")`: The time of the observation in MJD - `flux::typeof(1.0u"Jy")`: The flux of the observation in Jansky - `flux_err::typeof(1.0u"Jy")`: The flux error of the observation in Jansky - `mag::typeof(1.0u"AB_mag")`: The magnitude of the observations in AB Magnitude - `mag_err::typeof(1.0u"AB_mag")`: The magnitude error of the observations in AB Magnitude - `absmag::typeof(1.0u"AB_mag")`: The absolute magnitude of the observations in AB Magnitude - `absmag_err::typeof(1.0u"AB_mag")`: The absolute magnitude error of the observations in AB Magnitude - `filter::Filter`: The [`Filter`](@ref) used to observe the supernova - `is_upperlimit::Bool`: Whether the observation is an upperlimit """ mutable struct Observation name::String time::typeof(1.0u"d") flux::typeof(1.0u"Jy") flux_err::typeof(1.0u"Jy") mag::typeof(1.0u"AB_mag") mag_err::typeof(1.0u"AB_mag") absmag::typeof(1.0u"AB_mag") absmag_err::typeof(1.0u"AB_mag") filter::Filter is_upperlimit::Bool end """ mutable struct Lightcurve A lightcurve is simply a collection of observations # Fields - `observations::Vector{Observation}`: A `Vector` of [`Observation`](@ref) representing a supernova lightcurve. """ Base.@kwdef mutable struct Lightcurve observations::Vector{Observation} = Vector{Observation}() end """ parse_file(lines::Vector{String}; delimiter::String=", ", comment::String="#") Parse a file, splitting on `delimiter` and removing `comment`s. # Arguments - `lines::Vector{String}`: A vector containing each line of the file to parse - `;delimiter::String=", "`: What `delimiter` to split on - `;comment::String="#"`: What comments to remove. Will remove everything from this comment onwards, allowing for inline comments """ function parse_file(lines::Vector{String}; delimiter::String=", ", comment::String="#") parsed_file = Vector{Vector{String}}() for line in lines # Remove comments # Assumes once a comment starts, it takes up the rest of the line first = findfirst(comment, line) if !isnothing(first) comment_index = first[1] - 1 line = line[1:comment_index] end line = string.([l for l in split(line, delimiter) if l != ""]) if length(line) > 0 push!(parsed_file, line) end end return parsed_file end """ get_column_index(header::Vector{String}, header_keys::Dict{String,Any}) Determine the index of each column withing `header` associated with `header_keys` # Arguments - `header::Vector{String}`: The header, split by column names - `header_keys::Dict{String, Any}`: Determine the index of these parameters. The `key::String` is the type of object stored in the column, for instance `"TIME"`, `"FLUX"`, `"MAG_ERR"`, and so on. The `values::Any` can be an `Int64` or a `String` where the former indicates the column index (which is simply returned) and the latter represents the name of the `key` object inside `header`. For instance `key = "FLUX"` might map to a column in the `header` title `"Flux"`, `"F"`, `"emmission"`, or `"uJy"`. """ function get_column_index(header::Vector{String}, header_keys::Dict{String,Any}) columns = Dict{String,Tuple{Any,Any}}() for key in keys(header_keys) opts = header_keys[key] column_id = opts["COL"] unit = get(opts, "UNIT", nothing) unit_column_id = get(opts, "UNIT_COL", nothing) column_index = get_column_id(header, column_id) if !isnothing(unit) if unit == "DEFAULT" column_unit = get_default_unit(header, column_id, column_index) else column_unit = uparse(unit, unit_context=UNITS) end elseif !isnothing(unit_column_id) column_unit = get_column_id(header, unit_column_id) else column_unit = nothing end columns[key] = (column_index, column_unit) end return columns end """ get_column_id(::Vector{String}, column_id::Int64) Convenience function which simply returns the `column_id` passed in. # Arguments - `column_id::Int64`: Return this column id """ function get_column_id(::Vector{String}, column_id::Int64) return column_id end """ get_column_id(header::Vector{String}, column_id::String) Find the column in `header` which contains the given `column_id` and return its index. # Arguments - `header::Vector{String}`: The header, split by column - `column_id::String`: The column title to search for in `header` """ function get_column_id(header::Vector{String}, column_id::String) first = findfirst(f -> occursin(column_id, f), header) if !isnothing(first) return first end error("Can not find column $(column_id) in header: $header") end """ get_default_unit(header::Vector{String}, column_id::String, column_index::Int64) If no unit is provided for a parameter, it is assumed that the unit is listed in the header via `"paramater_name[unit]"`. Under this system you might have `"time[d]"`, `"flux[μJy]"`, or `"mag[AB_mag]"`. # Arguments - `header::Vector{String}`: The header, split by column - `column_id::String`: The name of the parameter in the column title - `column_index::Int64`: The index of the column in `header` """ function get_default_unit(header::Vector{String}, column_id::String, column_index::Int64) column_head = header[column_index] unit = foldl(replace, [column_id => "", "[" => "", "]" => ""]; init=column_head) return uparse(unit, unit_context=UNITS) end """ Lightcurve(observations::Vector{Dict{String,Any}}, zeropoint::Magnitude, redshift::Float64, config::Dict{String,Any}; max_flux_err::Flux=Inf * 1.0u"μJy", peak_time::Union{Bool,Float64}=false) Create a Lightcurve from a Vector of observations, modelled as a Vector of Dicts. Each observation must contains the keys `NAME`, and `PATH` which specify the name of the supernovae, and a path to the photometry respectively. `PATH` can either be absolute, or relative to `DATA_PATH` as specified in `[ GLOBAL ]` and is expected to be a delimited file of rows and columns, with a header row describing the content of each column, and a row for each individual photometric observation of the lightcurve. Each observation in `PATH` must contain a time, flux, and flux error column. You can also optionally pescribe a seperate facility, instrument, passband, and upperlimit column. If any of these column exist, they will be read per row. If not, you must specify a global value. The keys `DELIMITER::String=", "`, and `COMMENT::String="#"` allow you to specify the delimiter and comment characters used by `PATH`. The rest of the keys in an observation are for reading or overwriting the photometry in `PATH`. You can overwrite the facility (`FACILITY`::String), instrument (`INSTRUMENT`::String), passband (`PASSBAND`::String), and whether the photometry is an upperlimit (`UPPERLIMIT`::Union{Bool, String}). Specifying any overwrites will apply that overwrite to every row of `PATH`. You can also specify a flux offset (`FLUX_OFFSET`) assumed to be of the same unit as the flux measurements in `PATH`. By default, the upplimit column / overwrite is assumed to be a string: `upperlimit∈["T", "TRUE", "F", "FALSE"]`, if you instead want a different string identifier, you can specify `UPPERLIMIT_TRUE::Union{String, Vector{String}}`, and `UPPERLIMIT_FALSE::Union{String, Vector{String}}`. Each column of `PATH`, including the required time (`TIME`), flux (`FLUX`), and flux error (`FLUX_ERR`), and the optional facility (`FACILITY`), instrument (`INSTRUMENT`), passband (`PASSBAND`), and upperlimit (`UPPERLIMIT`) columns, can have both an identifier of the column, and the unit of the values be specified (units must be recognisable by [`Unitful`](https://painterqubits.github.io/Unitful.jl/stable/). There are three ways to do this. All of these methods are described by specifying identifiers through `HEADER.OBJECT_NAME.COL` and either `HEADER.OBJECT_NAME.UNIT` or `HEADER.OBJECT_NAME.UNIT_COL`. For example to given an identifier for time, you'd include `HEADER.TIME.COL` and `HEADER.TIME.UNIT`. The first method is to simply assume the headers have the syntax `name [unit]`, with time, flux, and flux error having the names `time`, `flux`, and `flux_err` respectively. This is the default when no identifiers are given, but can also be used for the unit identifier by specifying `HEADER.OBJECT_NAME.UNIT = "DEFAULT"`. The next method involves specifying the name of the column containing data of the object in question. This is simply `HEADER.OBJECT_NAME.COL = "col_name"`. For the unit you can either specify a global unit for the object via `HEADER.OBJECT_NAME.UNIT = "unit"`, or you can specify a unit column by name via `HEADER.OBJECT_NAME.UNIT_COL = "unit_col_name"`. The final method is to specify the index of the column containing data of the object in questions. This is done via `HEADER.OBJECT_NAME.COL = col_index`. Once again you can either specify a global unit or the index of the column containing unit information via `HEADER.OBJECT_NAME.UNIT_COL = unit_col_index`. Your choice of identifer can be different for each object and unit, for instance you could specify the name of the time column, and the index of the time unit column. As for the rest of the inputs, it is required to specify a zeropoint (in some magnitude unit), the redshift, and provide a global config. You can specify a maximum error on the flux via `max_flux_err`, which will treat every observation with a flux error greater than this as an outlier which will not be included. Finally you can specify a peak time which all other time parameters will be relative to (i.e, the peak time will be 0 and all other times become time - peak_time). This can either be `true`, in which case the peak time will be set to the time of maximum flux, or a float with units equal to the units of the time column. If you don't want relative times, set `peak_time` to `false`, which is the default. # Arguments - `observations::Vector{Dict{String,Any}}`: A `Vector` of `Dicts` containing information and overwrites for the file containing photometry of the supernova. - `zeropoint::Magnitude`: The zeropoint of the supernova - `redshift::Float64`: The redshift of the supernova - `config::Dict{String,Any}`: The global config, containing information about paths - `max_flux_err::Flux=Inf * 1.0u"μJy"`: An optional constrain on the maximum flux error. Any observation with flux error greater than this is considered an outlier and removed from the lightcurve. - `peak_time::Union{Bool, Float64}=false`: If not `false`, times will be relative to `peak_time` (i.e, will transform from `time` to `time - peak_time`). If `true` times a relative to the time of peak flux, otherwise times are relative to `peak_time`, which is assumed to be of the same unit as the times. """ function Lightcurve(observations::Vector{Dict{String,Any}}, zeropoint::Magnitude, redshift::Float64, config::Dict{String,Any}; max_flux_err::Flux=Inf * 1.0u"μJy", peak_time::Union{Bool,Float64}=false) lightcurve = Lightcurve() for observation in observations # File path obs_name = observation["NAME"] @info "Loading observations for $obs_name" obs_path = observation["PATH"] if !isabspath(obs_path) obs_path = joinpath(config["DATA_PATH"], obs_path) end obs_path = abspath(obs_path) # Optional overwrites facility = get(observation, "FACILITY", nothing) instrument = get(observation, "INSTRUMENT", nothing) passband = get(observation, "PASSBAND", nothing) upperlimit = get(observation, "UPPERLIMIT", nothing) flux_offset = get(observation, "FLUX_OFFSET", 0) # Upperlimit identifiers upperlimit_true = collect(get(observation, "UPPERLIMIT_TRUE", ["T", "TRUE"])) upperlimit_false = collect(get(observation, "UPPERLIMIT_FALSE", ["F", "FALSE"])) # File details delimiter = get(observation, "DELIMITER", ", ") comment = get(observation, "COMMENT", "#") default_header_keys = Dict{String,Any}( "TIME" => Dict{String,Any}("COL" => "time", "UNIT" => "DEFAULT"), "FLUX" => Dict{String,Any}("COL" => "flux", "UNIT" => "DEFAULT"), "FLUX_ERR" => Dict{String,Any}("COL" => "flux_err", "UNIT" => "DEFAULT") ) header_keys = get(observation, "HEADER", default_header_keys) obs_file = open(obs_path, "r") do io return parse_file(readlines(io); delimiter=delimiter, comment=comment) end header = obs_file[1] data = obs_file[2:end] columns::Dict{String,Tuple{Any,Any}} = get_column_index(header, header_keys) if "TIME" in keys(columns) time_col = columns["TIME"][1] time_unit_col = columns["TIME"][2] time_unit(row) = begin if isa(time_unit_col, Int64) return uparse(row[time_unit_col], unit_context=UNITS) else return time_unit_col end end time = [parse(Float64, d[time_col]) * time_unit(d) for d in data] else error("Missing time column. Please specify a time column.") end if "FLUX" in keys(columns) flux_col = columns["FLUX"][1] flux_unit_col = columns["FLUX"][2] flux_unit(row) = begin if isa(flux_unit_col, Int64) return uparse(row[flux_unit_col], unit_context=UNITS) else return flux_unit_col end end flux = [(parse(Float64, d[flux_col]) + flux_offset) * flux_unit(d) for d in data] else error("Missing flux column. Please specify a flux column.") end if "FLUX_ERR" in keys(columns) flux_err_col = columns["FLUX_ERR"][1] flux_err_unit_col = columns["FLUX_ERR"][2] flux_err_unit(row) = begin if isa(flux_err_unit_col, Int64) return uparse(row[flux_err_unit_col], unit_context=UNITS) else return flux_err_unit_col end end flux_err = [parse(Float64, d[flux_err_col]) * flux_err_unit(d) for d in data] else error("Missing flux_err column. Please specify a flux_err column.") end mag = flux_to_mag.(flux, zeropoint) mag_err = flux_err_to_mag_err.(flux, flux_err) absmag = mag_to_absmag.(mag, redshift) absmag_err = mag_err if isnothing(facility) if "FACILITY" in keys(columns) facility_col = columns["FACILITY"][1] facility = [d[facility_col] for d in data] else error("Missing Facility details. Please either specify a facility column, or provide a facility") end else facility = [facility for _ in data] end if isnothing(instrument) if "INSTRUMENT" in keys(columns) instrument_col = columns["INSTRUMENT"][1] instrument = [d[instrument_col] for d in data] else error("Missing instrument details. Please either specify a instrument column, or provide a instrument") end else instrument = [instrument for _ in data] end if isnothing(passband) if "PASSBAND" in keys(columns) passband_col = columns["PASSBAND"][1] passband = [d[passband_col] for d in data] else error("Missing passband details. Please either specify a passband column, or provide a passband") end else passband = [passband for _ in data] end get_equiv = Dict("time" => time, "flux" => flux, "flux_err" => flux_err) if isnothing(upperlimit) if "UPPERLIMIT" in keys(columns) upperlimit_col = columns["UPPERLIMIT"][1] upperlimit = Vector{Bool}() for d in data if d[upperlimit_col] in upperlimit_true push!(upperlimit, true) elseif d[upperlimit_col] in upperlimit_false push!(upperlimit, false) else error("Unknown upperlimit specifier $d, truth options include: $upperlimit_true, false options include: $upperlimit_false") end end else error("Missing upperlimit details. Please either specify a upperlimit column, or provide a upperlimit") end else if typeof(upperlimit) == Bool upperlimit = [upperlimit for _ in data] elseif typeof(upperlimit) == String if upperlimit in keys(get_equiv) upperlimit_equivalent = get_equiv[upperlimit] upperlimit = [u < 0 * unit(u) for u in upperlimit_equivalent] else error("Can not determine upperlimit from $(upperlimit), only 'time', 'flux', and 'flux_err' can be used.") end end end filter = [Filter(facility[i], instrument[i], passband[i], config) for i in 1:length(data)] obs = [Observation(obs_name, time[i], flux[i], flux_err[i], mag[i], mag_err[i], absmag[i], absmag_err[i], filter[i], upperlimit[i]) for i in 1:length(data) if flux_err[i] < max_flux_err] lightcurve.observations = vcat(lightcurve.observations, obs) end # If peak_time is a value, set all time relative to that value if peak_time isa Float64 peak_time *= unit(time[1]) for obs in lightcurve.observations obs.time -= peak_time end # Otherwise if peak_time is true, set all time relative to maximum flux time elseif peak_time max_ind = argmax(get(lightcurve, "flux")) time = get(lightcurve, "time") max_time = time[max_ind] for obs in lightcurve.observations obs.time -= max_time end end return lightcurve end function Base.get(lightcurve::Lightcurve, key::String, default::Any=nothing) if Symbol(key) in fieldnames(Observation) return [getfield(obs, Symbol(key)) for obs in lightcurve.observations] end return default end """ flux_to_mag(flux::Unitful.Quantity{Float64}, zeropoint::Level) Convert `flux` to magnitudes. Calculates `zeropoint - 2.5log10(flux)`. Returns `AB_mag` units # Arguments - `flux::Unitful.Quantity{Float64}`: The flux to convert, in units compatible with Jansky. If the flux is negative it will be set to 0.0 to avoid `log10` errors - `zeropoint::Level`: The assumed zeropoint, used to convert the flux to magnitudes. """ function flux_to_mag(flux::Flux, zeropoint::Magnitude) if flux <= 0.0 * unit(flux) flux *= 0.0 end return (ustrip(zeropoint |> u"AB_mag") - 2.5 * log10(ustrip(flux |> u"Jy"))) * u"AB_mag" end """ flux_err_to_mag_err(flux::Unitful.Quantity{Float64}, flux_err::Unitful.Quantity{Float64}) Converts `flux_err` to magnitude error. Calculates `(2.5 / log(10)) * (flux_err / flux)`. # Arguments - `flux::Unitful.Quantity{Float64}`: The flux associated with the error to be converted - `flux_err::Unitful.Quantity{Float64}`: The flux error to be converted """ function flux_err_to_mag_err(flux::Flux, flux_err::Flux) return (2.5 / log(10)) * (flux_err / flux) * u"AB_mag" end """ mag_to_flux(mag::Level, zeropoint::Level) Convert `flux` to magnitudes. Calculates `10^(0.4(zeropoint - mag))`. Return `Jy` units. # Arguments - `flux::Unitful.Quantity{Float64}`: The flux to convert, in units compatible with Jansky. If the flux is negative it will be set to 0.0 to avoid `log10` errors - `zeropoint::Level`: The assumed zeropoint, used to convert the flux to magnitudes. """ function mag_to_flux(mag::Magnitude, zeropoint::Magnitude) return (10.0^(0.4 * (ustrip(zeropoint |> u"AB_mag") - ustrip(mag |> u"AB_mag")))) * u"Jy" end """ mag_to_absmag(mag::Level, redshift::Float64; H0::Unitful.Quantity{Float64}=70.0u"km/s/Mpc") Converts `mag` to absolute magnitude. Calculates `mag - 5 log10(c * redshift / (H0 * 10pc))` # Arguments - `mag::Level`: The magnitude to convert - `redshift::Float64`: The redshift, used to calculate the distance to the object - `;H0::Unitful.Quantity{Float64}=70.0u"km/s/Mpc`: The assumed value of H0, used to calculate the distance to the object """ function mag_to_absmag(mag::Magnitude, redshift::Float64; H0::Unitful.Frequency=70.0u"km/s/Mpc") d = c * redshift / H0 μ = 5.0 * log10(d / 10.0u"pc") absmag = (ustrip(mag |> u"AB_mag") - μ) * u"AB_mag" return absmag end """ absmag_to_mag(absmag::Level, redshift::Float64; H0::Unitful.Quantity{Float64}=70.0u"km/s/Mpc") Converts `absmag` to magnitudes. Calculates `absmag + 5 log10(c * redshift / (H0 * 10pc))` # Arguments - `mag::Level`: The magnitude to convert - `redshift::Float64`: The redshift, used to calculate the distance to the object - `;H0::Unitful.Quantity{Float64}=70.0u"km/s/Mpc`: The assumed value of H0, used to calculate the distance to the object """ function absmag_to_mag(absmag::Magnitude, redshift::Float64; H0::Unitful.Frequency=70.0u"km/s/Mpc") d = c * redshift / H0 μ = 5.0 * log10(d / 10.0u"pc") mag = (ustrip(absmag |> u"AB_mag") + μ) * u"AB_mag" return mag end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
9146
# Plot Module module PlotModule # Internal Packages using ..SupernovaModule using ..FilterModule # External Packages using Random Random.seed!(0) using CairoMakie CairoMakie.activate!(type="svg") using Unitful, UnitfulAstro const UNITS = [Unitful, UnitfulAstro] # Exports export plot_lightcurve, plot_lightcurve! const marker_labels = shuffle([:rect, :star5, :diamond, :hexagon, :cross, :xcross, :utriangle, :dtriangle, :ltriangle, :rtriangle, :pentagon, :star4, :star8, :vline, :hline, :x, :+, :circle]) const colour_labels = shuffle(["salmon", "coral", "tomato", "firebrick", "crimson", "red", "orange", "green", "forestgreen", "seagreen", "olive", "lime", "charteuse", "teal", "turquoise", "cyan", "navyblue", "midnightblue", "indigo", "royalblue", "slateblue", "steelblue", "blue", "purple", "orchid", "magenta", "maroon", "hotpink", "deeppink", "saddlebrown", "brown", "peru", "tan"]) # Plotting functions """ plot_lightcurve!(fig::Figure, ax::Axis, supernova::Supernova, plot_config::Dict{String, Any}) Add lightcurve plot to axis. plot_config contains plotting options. DATA_TYPE = ["flux", "magnitude", "abs_magnitude"]: The type of data to plot UNITS::Dict: Units for time, and flux, magnitude, or abs_magnitude NAMES::Vector: List of [`SupernovaModule.Observation`](@ref).name's to include in the plot. If `nothing`, all observations are included RENAME::Dict: Convert [`FilterModule.Filter`](@ref).passband to new name FILTERS::Vector: List of [`FilterModule.Filter`](@ref).passband's to include MARKERSIZE::Int: Size of the markers MARKER::Dict: Marker to use for each [`SupernovaModule.Observation`](@ref).name. If a passband is missing, a default marker is used COLOUR::Dict: Marker to use for each [`FilterModule.Filter`](@ref).passband. If a passband is missing, a default marker is used LEGEND::Bool: Whether to include a legend # Arguments - `fig::Figure`: Figure to plot to - `ax::Axis`: Axis to plot to - `supernova::Supernova`: Supernova to plot - `plot_config::Dict{String, Any}`: Details of the plot """ function plot_lightcurve!(fig::Figure, ax::Axis, supernova::Supernova, plot_config::Dict{String, Any}) time = Dict{Tuple{String, String}, Vector{Float64}}() data_type = get(plot_config, "DATATYPE", "flux") @debug "Plotting data type set to $data_type" data = Dict{Tuple{String, String}, Vector{Float64}}() data_err = Dict{Tuple{String, String}, Vector{Float64}}() marker_plots = Dict{String,MarkerElement}() markers = Dict{String,Symbol}() colour_plots = Dict{String,MarkerElement}() colours = Dict{String,String}() units = get(plot_config, "UNIT", Dict{String,Any}()) time_unit = uparse(get(units, "TIME", "d"), unit_context=UNITS) if data_type == "flux" data_unit = uparse(get(units, "DATA", "Β΅Jy"), unit_context=UNITS) elseif data_type == "magnitude" data_unit = uparse(get(units, "DATA", "AB_mag"), unit_context=UNITS) elseif data_type == "abs_magnitude" data_unit = uparse(get(units, "DATA", "AB_mag"), unit_context=UNITS) else error("Unknown data type: $data_type. Possible options are [flux, magnitude, abs_magnitude]") end @debug "Plotting data unit set to $data_unit" names = get(plot_config, "NAME", nothing) rename = get(plot_config, "RENAME", Dict{String, Any}()) filters = get(plot_config, "FILTERS", nothing) markersize = get(plot_config, "MARKERSIZE", 11) offsets = get(plot_config, "OFFSET", Dict{String, Any}()) @debug "Generating all plot vectors" for obs in supernova.lightcurve.observations if !isnothing(names) if !(obs.name in names) continue end end if !isnothing(filters) if !(obs.filter.passband in filters) continue end end passband = get(rename, uppercase(obs.filter.passband), obs.filter.passband) obs_name = get(rename, uppercase(obs.name), obs.name) passband_offset = get(offsets, uppercase(obs.filter.passband), 0) obs_name_offset = get(offsets, uppercase(obs.name), 0) if !(obs.name in keys(markers)) marker = Meta.parse(get(get(plot_config, "MARKER", Dict{String, Any}()), uppercase(obs.name), "nothing")) if marker == :nothing marker = marker_labels[length(marker_plots)+1] end elem = MarkerElement(color=:black, marker=marker, markersize=markersize) marker_plots[obs_name] = elem markers[obs.name] = marker end if !(obs.filter.passband in keys(colours)) colour = get(get(plot_config, "COLOUR", Dict{String, Any}()), uppercase(obs.filter.passband), nothing) if isnothing(colour) colour = colour_labels[length(colour_plots)+1] end elem = MarkerElement(marker=:hline, color=colour, markersize=0.5 * markersize) colour_plots[passband] = elem colours[obs.filter.passband] = colour end push!(get!(time, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(time_unit, obs.time))) if data_type == "flux" push!(get!(data, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(data_unit, obs.flux)) + passband_offset + obs_name_offset) push!(get!(data_err, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(data_unit, obs.flux_err))) elseif data_type == "magnitude" push!(get!(data, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(data_unit, obs.mag)) + passband_offset + obs_name_offset) push!(get!(data_err, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(data_unit, obs.mag_err))) elseif data_type == "abs_magnitude" push!(get!(data, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(data_unit, obs.absmag)) + passband_offset + obs_name_offset) push!(get!(data_err, (obs.name, obs.filter.passband), Float64[]), ustrip(uconvert(data_unit, obs.absmag_err))) else error("Unknown data type: $data_type. Possible options are [flux, magnitude, abs_magnitude]") end end legend_plots = MarkerElement[] legend_names = String[] for k in sort(collect(keys(marker_plots))) push!(legend_names, k) push!(legend_plots, marker_plots[k]) end for k in sort(collect(keys(colour_plots))) push!(legend_names, k) push!(legend_plots, colour_plots[k]) end @debug "Plotting" for (i, key) in enumerate(collect(keys(time))) marker = Meta.parse(get(get(plot_config, "MARKER", Dict{String, Any}()), key[1], "nothing")) if marker == :nothing marker = markers[key[1]] end colour = get(get(plot_config, "COLOUR", Dict{String, Any}()), key[2], nothing) if isnothing(colour) colour = colours[key[2]] end sc = scatter!(ax, time[key], data[key], color=colour, marker=marker) sc.markersize = markersize errorbars!(ax, time[key], data[key], data_err[key], color=colour) end if get(plot_config, "LEGEND", true) Legend(fig[1, 2], legend_plots, legend_names) end return colours, markers, legend_plots, legend_names end """ plot_lightcurve(supernova::Supernova, plot_config::Dict{String,Any}, config::Dict{String,Any}) Set up Figure and Axis, then plot lightcurve using [`plot_lightcurve!`](@ref) # Arguments - `supernova::Supernova`: The supernova to plot - `plot_config::Dict{String, Any}`: Plot options passed to plot_lightcurve! - `config::Dict{String, Any}`: Global options including where to save the plot """ function plot_lightcurve(supernova::Supernova, plot_config::Dict{String,Any}, config::Dict{String,Any}) fig = Figure() units = get(plot_config, "UNIT", Dict{String,Any}()) time_unit = uparse(get(units, "TIME", "d"), unit_context=UNITS) data_type = get(plot_config, "DATATYPE", "flux") if data_type == "flux" data_unit = uparse(get(units, "DATA", "Β΅Jy"), unit_context=UNITS) ax = Axis(fig[1, 1], xlabel="Time [$time_unit]", ylabel="Flux [$data_unit]", title=supernova.name) elseif data_type == "magnitude" data_unit = uparse(get(units, "DATA", "AB_mag"), unit_context=UNITS) ax = Axis(fig[1, 1], xlabel="Time [$time_unit]", ylabel="Magnitude [$data_unit]", title=supernova.name) ax.yreversed = true elseif data_type == "abs_magnitude" data_unit = uparse(get(units, "DATA", "AB_mag"), unit_context=UNITS) ax = Axis(fig[1, 1], xlabel="Time [$time_unit]", ylabel="Absolute Magnitude [$data_unit]", title=supernova.name) ax.yreversed = true else error("Unknown data type: $data_type. Possible options are [flux, magnitude, abs_magnitude]") end plot_lightcurve!(fig, ax, supernova, plot_config) path = get(plot_config, "PATH", "$(supernova.name)_lightcurve.svg") if !isabspath(path) path = joinpath(config["OUTPUT_PATH"], path) end path = abspath(path) save(path, fig) return fig, ax end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
1415
module RunModule # External Packages # Internal Packages include(joinpath(@__DIR__, "FilterModule.jl")) using .FilterModule include(joinpath(@__DIR__, "PhotometryModule.jl")) using .PhotometryModule include(joinpath(@__DIR__, "SupernovaModule.jl")) using .SupernovaModule include(joinpath(@__DIR__, "PlotModule.jl")) # `used` later only if needed # Exports export run_Supernovae export Supernova export Observation export synthetic_flux export flux_to_mag, mag_to_flux export absmag_to_mag, mag_to_absmag export plot_lightcurve """ run_Supernovae(toml::Dict{String, Any}) Main entrance function for the package # Arguments - `toml::Dict{String, Any}`: Input toml file containing all options for the package """ function run_Supernovae(toml::Dict{String,Any}) config = toml["GLOBAL"] supernova = Supernova(toml["DATA"], config) if "PLOT" in keys(toml) @info "Plotting" plot_config = toml["PLOT"] # Only include PlotModule if needed to save on precompilation time if we don't need to use Makie @debug "Loading Plotting Module" @eval using .PlotModule if "LIGHTCURVE" in keys(plot_config) @info "Plotting Lightcurve" for lightcurve_config in plot_config["LIGHTCURVE"] Base.@invokelatest plot_lightcurve(supernova, lightcurve_config, config) end end end return supernova end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
3124
# Supernova Module module SupernovaModule # Internal Packages using ..PhotometryModule # External Packages using Unitful using UnitfulAstro const UNITS = [Unitful, UnitfulAstro] # Exports export Supernova """ mutable struct Supernova A Supernova # Fields - `name::String`: Supernova name - `zeropoint::typeof(1.0u"AB_mag")`: Zeropoint of the supernova - `redshift::Float64`: Redshift of the supernova - `lightcurve::[`Lightcurve`](@ref)`: The lightcurve of the supernova """ mutable struct Supernova name::String zeropoint::typeof(1.0u"AB_mag") redshift::Float64 lightcurve::Lightcurve end """ Supernova(data::Dict{String,Any}, config::Dict{String,Any}) Load in a supernova from `data`, which has a number of keys containing supernova data and options. - `NAME::String`: Name of the supernova - `ZEROPOINT::Float64`: Supernova zeropoint - `ZEROPOINT_UNIT::String`: Unitful unit of zeropoint, default to AB_mag - `REDSHIFT::Float64`: Supernova redshift - `MAX_FLUX_ERR::Float64`: Maximum allowed flux error, default to inf - `MAX_FLUX_ERR_UNIT::String`: Unitful unit of maximum flux error - `PEAK_TIME::Union{Bool, Float64}`: If bool, whether to set time relative to peak flux, if Float64, set time relative to PEAK_TIME - `OBSERVATIONS::Vector{Dict{String,Any}}`: Data to be turned into a [`Lightcurve`](@ref) """ function Supernova(data::Dict{String,Any}, config::Dict{String,Any}) # Supernova Details name = data["NAME"] @info "Loading Supernova: $name" zeropoint = data["ZEROPOINT"] zeropoint_unit = get(data, "ZEROPOINT_UNIT", "AB_mag") zeropoint = zeropoint * uparse(zeropoint_unit, unit_context=UNITS) @debug "Supernova has zeropoint: $zeropoint" redshift = data["REDSHIFT"] @debug "Supernova has redshift: $redshift" # Maximum error in flux max_flux_err = get(data, "MAX_FLUX_ERR", Inf) max_flux_err_units = get(data, "MAX_FLUX_ERR_UNIT", "ΞΌJy") max_flux_err = max_flux_err * uparse(max_flux_err_units, unit_context=UNITS) @debug "Maximum flux error set to: $max_flux_err" # Whether times are absolute or relative to the peak # Alternative choose a time for other times to be relative to peak_time = get(data, "PEAK_TIME", false) # Load in observations observations = get(data, "OBSERVATIONS", Vector{Dict{String,Any}}()) @info "Found $(length(observations)) observations" lightcurve = Lightcurve(observations, zeropoint, redshift, config; max_flux_err=max_flux_err, peak_time=peak_time) @info "Finished loading Supernova" return Supernova(name, zeropoint, redshift, lightcurve) end function Base.get(supernova::Supernova, key::AbstractString, default::Any=nothing) return get(supernova.lightcurve, key, default) end function Base.filter(f::Function, supernova::Supernova) filt = filter(f, supernova.lightcurve.observations) return Supernova(supernova.name, supernova.zeropoint, supernova.redshift, Lightcurve(filt)) end function Base.filter!(f::Function, supernova::Supernova) supernova.lightcurve = Lightcurve(filter(f, supernova.lightcurve.observations)) end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
2095
module Supernovae # External packages using TOML using BetterInputFiles using ArgParse using StatProfilerHTML using OrderedCollections # Internal Packages include("RunModule.jl") using .RunModule # Exports export main export run_Supernovae export Supernova export Observation export synthetic_flux export flux_to_mag, mag_to_flux export absmag_to_mag, mag_to_absmag export plot_lightcurve """ get_args() Helper function to get the ARGS passed to julia. """ function get_args() s = ArgParseSettings() @add_arg_table! s begin "--verbose", "-v" help = "Increase level of logging verbosity" action = :store_true "--profile", "-p" help = "Run profiler" action = :store_true "input" help = "Path to .toml file" required = true end return parse_args(s) end """ main() Read the args, prepare the input TOML and run the actual package functionality. Runs [`main(toml_path, verbose, profile)`](@ref). """ function main() args = get_args() toml_path = args["input"] verbose = args["verbose"] profile = args["profile"] main(toml_path, verbose, profile) end """ main(toml_path::AbstractString, verbose::Bool, profile::Bool) Loads `toml_path`, and sets up logging with verbosity based on `verbose`. Runs [`run_Supernovae`](@ref) and if `profile` is `true`, also profiles the code. # Arguments - `toml_path::AbstractString`: Path to toml input file. - `verbose::Bool`: Set verbosity of logging - `profile::Bool`: If true, profile [`run_Supernovae`](@ref) """ function main(toml_path::AbstractString, verbose::Bool, profile::Bool) paths = OrderedDict( "data_path" => ("base_path", "Data"), "filter_path" => ("base_path", "Filters") ) toml = setup_input(toml_path, verbose; paths=paths) if profile @warn "Running everything once to precompile before profiling" run_Supernovae(toml) @profilehtml run_Supernovae(toml) else run_Supernovae(toml) end end if abspath(PROGRAM_FILE) == @__FILE__ main() end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
code
15838
using Supernovae using Supernovae.RunModule using Supernovae.RunModule.FilterModule using Supernovae.RunModule.PhotometryModule using Supernovae.RunModule.SupernovaModule using Supernovae.RunModule.PlotModule using Test using Unitful, UnitfulAstro @testset "Supernovae.jl" begin @testset "FilterModule" begin facility = "JWST" instrument = "NIRCam" passband = "F200W" filter_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) filter_path = joinpath(filter_config["FILTER_PATH"], "$(facility)__$(instrument)__$(passband)") # Get the filter from svo filter_1 = Filter(facility, instrument, passband, filter_config) # Load the same filter from disk filter_2 = Filter(facility, instrument, passband, filter_config) # Make sure it crashes correctly @test_throws ErrorException broken_filter = Filter("A", "B", "C", filter_config) # Test that filter_1 and filter_2 are identical for field in fieldnames(Filter) @test getfield(filter_1, field) == getfield(filter_2, field) end rm(filter_path) neg_t = -10u"K" zero_t = 0.0u"K" neg_Ξ» = -10.0u"nm" zero_Ξ» = 0u"nm" # Ensure physically impossible inputs are caught @test_throws DomainError planck(neg_t, 1000.0u"nm") @test_throws DomainError planck(zero_t, 1000.0u"nm") @test_throws DomainError planck(1000.0u"K", neg_Ξ») @test_throws DomainError planck(1000.0u"K", zero_Ξ») @test_throws DomainError synthetic_flux(filter_1, neg_t) @test_throws DomainError synthetic_flux(filter_1, zero_t) # Ensure units are handled correctly a_planck = planck(1000u"K", 5000u"nm") b_planck = planck(1000.0u"K", 50000.0u"β„«") @test a_planck |> unit(b_planck) β‰ˆ b_planck @test synthetic_flux(filter_1, 1000u"K") == synthetic_flux(filter_2, 1000.0u"K") end @testset "PhotometryModule" begin # Load lightcurves using various methods default_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "default", "PATH" => joinpath(@__DIR__, "observations/Default.txt"), "FACILITY" => "JWST", "INSTRUMENT" => "NIRCam", "PASSBAND" => "F200W", "UPPERLIMIT" => false ) ]) default_zeropoint = -21.0u"AB_mag" default_redshift = 1.0 default_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) default_lightcurve = Lightcurve(default_observations, default_zeropoint, default_redshift, default_config) default_time = [o.time for o in default_lightcurve.observations] default_flux = [o.flux for o in default_lightcurve.observations] default_flux_err = [o.flux_err for o in default_lightcurve.observations] default_mag = [o.mag for o in default_lightcurve.observations] default_absmag = [o.absmag for o in default_lightcurve.observations] default_filter = [o.filter for o in default_lightcurve.observations] default_upperlimit = [o.is_upperlimit for o in default_lightcurve.observations] extracols_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "extracols", "PATH" => joinpath(@__DIR__, "observations/ExtraCols.txt"), "UPPERLIMIT_TRUE" => ["True"], "UPPERLIMIT_FALSE" => ["False"], "HEADER" => Dict{String, Any}( "TIME" => Dict{String, Any}( "COL" => "time", "UNIT" => "DEFAULT" ), "FLUX" => Dict{String, Any}( "COL" => "flux", "UNIT" => "DEFAULT" ), "FLUX_ERR" => Dict{String, Any}( "COL" => "flux_err", "UNIT" => "DEFAULT" ), "FACILITY" => Dict{String, Any}( "COL" => "facility" ), "INSTRUMENT" => Dict{String, Any}( "COL" => "instrument" ), "PASSBAND" => Dict{String, Any}( "COL" => "passband" ), "UPPERLIMIT" => Dict{String, Any}( "COL" => "upperlimit" ) ) ) ]) extracols_zeropoint = -21.0u"AB_mag" extracols_redshift = 1.0 extracols_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) extracols_lightcurve = Lightcurve(extracols_observations, extracols_zeropoint, extracols_redshift, extracols_config) extracols_time = [o.time for o in extracols_lightcurve.observations] extracols_flux = [o.flux for o in extracols_lightcurve.observations] extracols_flux_err = [o.flux_err for o in extracols_lightcurve.observations] extracols_filter = [o.filter for o in extracols_lightcurve.observations] extracols_upperlimit = [o.is_upperlimit for o in extracols_lightcurve.observations] named_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "named", "PATH" => joinpath(@__DIR__, "observations/Named.txt"), "FACILITY" => "JWST", "INSTRUMENT" => "NIRCam", "PASSBAND" => "F200W", "UPPERLIMIT" => "flux", "HEADER" => Dict{String, Any}( "TIME" => Dict{String, Any}( "COL" => "time", "UNIT" => "d" ), "FLUX" => Dict{String, Any}( "COL" => "flux", "UNIT_COL" => "flux_unit" ), "FLUX_ERR" => Dict{String, Any}( "COL" => "flux_err", "UNIT_COL" => 5 ) ) ) ]) named_zeropoint = -21.0u"AB_mag" named_redshift = 1.0 named_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) named_lightcurve = Lightcurve(named_observations, named_zeropoint, named_redshift, named_config) named_time = [o.time for o in named_lightcurve.observations] named_flux = [o.flux for o in named_lightcurve.observations] named_flux_err = [o.flux_err for o in named_lightcurve.observations] named_filter = [o.filter for o in named_lightcurve.observations] named_upperlimit = [o.is_upperlimit for o in named_lightcurve.observations] index_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "index", "PATH" => joinpath(@__DIR__, "observations/Index.txt"), "FACILITY" => "JWST", "INSTRUMENT" => "NIRCam", "PASSBAND" => "F200W", "UPPERLIMIT" => false, "COMMENT" => "-", # Treat comment as header "HEADER" => Dict{String, Any}( "TIME" => Dict{String, Any}( "COL" => 1, "UNIT_COL" => 2 ), "FLUX" => Dict{String, Any}( "COL" => 3, "UNIT_COL" => 4 ), "FLUX_ERR" => Dict{String, Any}( "COL" => 5, "UNIT_COL" => 6 ) ) ) ]) index_zeropoint = -21.0u"AB_mag" index_redshift = 1.0 index_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) index_lightcurve = Lightcurve(index_observations, index_zeropoint, index_redshift, index_config) index_time = [o.time for o in index_lightcurve.observations] index_flux = [o.flux for o in index_lightcurve.observations] index_flux_err = [o.flux_err for o in index_lightcurve.observations] index_filter = [o.filter for o in index_lightcurve.observations] index_upperlimit = [o.is_upperlimit for o in index_lightcurve.observations] # Test that the lightcurves are identical @test default_time == extracols_time == named_time == index_time @test default_flux == extracols_flux == named_flux == index_flux @test default_flux_err == extracols_flux_err == named_flux_err == index_flux_err for field in fieldnames(Filter) @test getfield.(default_filter, field) == getfield.(extracols_filter, field) == getfield.(named_filter, field) == getfield.(index_filter, field) end @test default_upperlimit == extracols_upperlimit == named_upperlimit == index_upperlimit # Test that functions make sense @test !(false in (absmag_to_mag.(default_absmag, default_redshift) .β‰ˆ default_mag)) @test !(false in (mag_to_flux.(default_mag, default_zeropoint) β‰ˆ default_flux)) # Error testing broken_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "broken", "PATH" => joinpath(@__DIR__, "observations/Default.txt"), "HEADER" => Dict{String, Any}() ) ]) @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["HEADER"]["TIME"] = Dict{String, Any}( "COL" => "missing", "UNIT" => "DEFAULT" ) @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["HEADER"]["TIME"]["COL"] = "time" @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["HEADER"]["FLUX"] = Dict{String, Any}( "COL" => "flux", "UNIT" => "DEFAULT" ) @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["HEADER"]["FLUX_ERR"] = Dict{String, Any}( "COL" => "flux_err", "UNIT" => "DEFAULT" ) @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["FACILITY"] = "JWST" @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["INSTRUMENT"] = "NIRCam" @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["PASSBAND"] = "F200W" @test_throws ErrorException broken_lightcurve = Lightcurve(broken_observations, default_zeropoint, default_redshift, default_config) broken_observations[1]["UPPERLIMIT"] = false # Test peak time options peak_time_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "peak_time", "PATH" => joinpath(@__DIR__, "observations/Default.txt"), "FACILITY" => "JWST", "INSTRUMENT" => "NIRCam", "PASSBAND" => "F200W", "UPPERLIMIT" => false ) ]) peak_time_zeropoint = -21.0u"AB_mag" peak_time_redshift = 1.0 peak_time_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) lc_1= Lightcurve(peak_time_observations, peak_time_zeropoint, peak_time_redshift, peak_time_config, peak_time=true) lc_2= Lightcurve(peak_time_observations, peak_time_zeropoint, peak_time_redshift, peak_time_config, peak_time=3.0) lc_1_time = [o.time for o in lc_1.observations] lc_2_time = [o.time for o in lc_2.observations] @test lc_1_time == lc_2_time # Test getting @test get(default_lightcurve, "time") == default_time @test isnothing(get(default_lightcurve, "key", nothing)) end @testset "SupernovaModule" begin default_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "default", "PATH" => joinpath(@__DIR__, "observations/Default.txt"), "FACILITY" => "JWST", "INSTRUMENT" => "NIRCam", "PASSBAND" => "F200W", "UPPERLIMIT" => false ) ]) default_zeropoint = -21.0 default_redshift = 1.0 default_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters") ) default_data = Dict{String, Any}( "NAME" => "default", "ZEROPOINT" => default_zeropoint, "REDSHIFT" => default_redshift, "OBSERVATIONS" => default_observations ) default_supernova = Supernova(default_data, default_config) @test length(default_supernova.lightcurve.observations) == 2 @test get(default_supernova.lightcurve, "time") == get(default_supernova, "time") filt_supernova = filter(x -> x.time < 2u"d", default_supernova) @test length(filt_supernova.lightcurve.observations) == 1 filter!(x -> x.time < 2u"d", default_supernova) @test length(default_supernova.lightcurve.observations) == 1 end @testset "PlotModule" begin # These `tests` just make sure the plotting function runs without crashing default_observations = Vector{Dict{String, Any}}([ Dict{String, Any}( "NAME" => "default", "PATH" => joinpath(@__DIR__, "observations/Default.txt"), "FACILITY" => "JWST", "INSTRUMENT" => "NIRCam", "PASSBAND" => "F200W", "UPPERLIMIT" => false ) ]) default_zeropoint = -21.0 default_redshift = 1.0 default_config = Dict{String, Any}( "FILTER_PATH" => joinpath(@__DIR__, "filters"), "OUTPUT_PATH" => joinpath(@__DIR__, "output") ) default_data = Dict{String, Any}( "NAME" => "default", "ZEROPOINT" => default_zeropoint, "REDSHIFT" => default_redshift, "OBSERVATIONS" => default_observations ) default_supernova = Supernova(default_data, default_config) plot_config = Dict{String, Any}() plot_lightcurve(default_supernova, plot_config, default_config) @test isfile(joinpath(default_config["OUTPUT_PATH"], "default_lightcurve.svg")) plot_config["DATATYPE"] = "magnitude" plot_lightcurve(default_supernova, plot_config, default_config) @test isfile(joinpath(default_config["OUTPUT_PATH"], "default_lightcurve.svg")) plot_config["DATATYPE"] = "abs_magnitude" plot_lightcurve(default_supernova, plot_config, default_config) @test isfile(joinpath(default_config["OUTPUT_PATH"], "default_lightcurve.svg")) plot_config["DATATYPE"] = "error" @test_throws ErrorException plot_lightcurve(default_supernova, plot_config, default_config) end end
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
docs
4407
[![Tests](https://github.com/OmegaLambda1998/Supernovae.jl/actions/workflows/test_and_codecov.yml/badge.svg)](https://github.com/OmegaLambda1998/Supernovae.jl/actions/workflows/test_and_codecov.yml) [![Documentation](https://github.com/OmegaLambda1998/Supernovae.jl/actions/workflows/documentation.yml/badge.svg)](https://omegalambda.au/Supernovae.jl/) [![Coverage Status](https://coveralls.io/repos/github/OmegaLambda1998/Supernovae.jl/badge.svg?branch=main)](https://coveralls.io/github/OmegaLambda1998/Supernovae.jl?branch=main) # Supernovae.jl Provides methods for reading in and plotting supernova lightcurves from text files. Extremely flexible reading methods allow for almost any reasonable lightcurve data file syntax to be read. ## Prerequisites To automatically download passbands from the [SVO Filter Profile Service](svo2.cab.inta-csic.es/theory/fps/), you must install the python package [astroquery](https://astroquery.readthedocs.io/en/latest/index.html). This is installed as part of the build process, installing into a `Conda.jl` conda environment. ## Install ```bash $ git clone [email protected]:OmegaLambda1998/Supernovae.jl.git $ cd Supernovae.jl $ make ``` This will instantiate and build `Supernovae.jl`, installing all required Julia packages, and setting up a Conda environment for the required Python packages. Finally it will run the tests to make sure everything is working. If you want to skip testing run `make install` instead. You can also run `./scripts/Supernovae -v ./Examples/Inputs/2021zby/2021zby_data.toml` to load and plot the lightcurve of 2021zby. This will create a `.svg` plot in `./Examples/Outputs/2021zby/`. ## Usage ```bash $ ./scripts/Supernovae -v path/to/input.toml ``` Details on how to build the input files which control `Supernovae.jl` can be found in [Usage](./usage.md). ## Example data file The following example input file can be found in the Examples directory. `base_path` is the directory containing your input file. ```toml [ global ] filter_path = "../Filters" # Defaults to base_path / Filters output_path = "../../Outputs/2021zby" # Defaults to base_path / Output # Data [ data ] # First include information about the supernova name = "2021zby" # Required zeropoint = 8.9 # Required redshift = 0.02559 # Required max_flux_err = 2.5e2 # Optional, set's the maximum allowed value for the uncertainty in the flux, assumes same units as flux peak_time = true # Default false. Can either be true, in which case all times will become relative to the peak data point. Alternatively, give a value, and all times will be relative to that value peak_time_unit = "d" # Optional, default to d [[ data.observations ]] # Now load in different observations of the supernova. This can either be one file with all observations, or you can load in multiple files name = "atlas" # Required, Human readable name to distinguish observations path = "atlas_1007.dat" # Required, Accepts either relative (to Supernova) or absolute path delimiter = " " # Optional, defaults to comma facility = "Misc" instrument = "Atlas" # Optional, will overwrite anything in the file upperlimit = "flux_err" # Since this file contains a header that isn't in the expected format, you can optionally specify what each header corresponds to. # If you do this you MUST specify the time, flux, and flux error. # You can also specify the filter, instrument, or upperlimit columns if they're in the file. If not, specify them above header.time.col = "MJD" header.time.unit = "d" header.flux.col = "uJy" header.flux.unit = "Β΅Jy" header.flux_err.col = "duJy" header.flux_err.unit = "Β΅Jy" header.passband.col = "F" [[ data.observations ]] name = "tess 6hr" path = "tess_2_6hrlc.txt" delimiter = " " comment = "#" # Optional, defines what is a comment (will be removed). Defaults to # facility = "tess" instrument = "tess" passband = "Red" filter_name = "Tess" upperlimit = false flux_offset = 0.296 # Defaults to 0, assumes same units as flux [[ plot.lightcurve ]] filters = ["Red", "orange"] markersize = 21 marker."tess 6hr" = "utriangle" rename."tess 6hr" = "Tess (6hr)" marker.atlas = "circle" rename.atlas = "Atlas" colour.Red = "red" rename.Red = "Tess: Red" rename.orange = "Atlas: Orange (+150 ΞΌJy)" colour.orange = "orange" offset.orange = 150 legend = true ``` Further details can be found in the [documentation](https://www.omegalambda.au/Supernovae.jl/dev/).
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
docs
1525
# API ## Contents ```@contents Pages = ["api.md"] Depth = 5 ``` ## Supernovae Functions ```@meta CurrentModule = Supernovae ``` ### Public Objects ```@autodocs Modules = [Supernovae] Private = false ``` ### Private Objects ```@autodocs Modules = [Supernovae] Public = false ``` ## RunModule Functions ```@meta CurrentModule = Supernovae.RunModule ``` ### Public Objects ```@autodocs Modules = [RunModule] Private = false ``` ### Private Objects ```@autodocs Modules = [RunModule] Public = false ``` ## FilterModule Functions ```@meta CurrentModule = Supernovae.RunModule.FilterModule ``` ### Public Objects ```@autodocs Modules = [FilterModule] Private = false ``` ### Private Objects ```@autodocs Modules = [FilterModule] Public = false ``` ## PhotometryModule Functions ```@meta CurrentModule = Supernovae.RunModule.PhotometryModule ``` ### Public Objects ```@autodocs Modules = [PhotometryModule] Private = false ``` ### Private Objects ```@autodocs Modules = [PhotometryModule] Public = false ``` ## SupernovaModule Functions ```@meta CurrentModule = Supernovae.RunModule.SupernovaModule ``` ### Public Objects ```@autodocs Modules = [SupernovaModule] Private = false ``` ### Private Objects ```@autodocs Modules = [SupernovaModule] Public = false ``` ## PlotModule Objects ```@meta CurrentModule = Supernovae.RunModule.PlotModule ``` ### Public Objects ```@autodocs Modules = [PlotModule] Private = false ``` ### Private Objects ```@autodocs Modules = [PlotModule] Public = false ```
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
docs
4378
[![Tests](https://github.com/OmegaLambda1998/Supernovae.jl/actions/workflows/test_and_codecov.yml/badge.svg)](https://github.com/OmegaLambda1998/Supernovae.jl/actions/workflows/test_and_codecov.yml) [![Documentation](https://github.com/OmegaLambda1998/Supernovae.jl/actions/workflows/documentation.yml/badge.svg)](https://omegalambda.au/Supernovae.jl/) [![Coverage Status](https://coveralls.io/repos/github/OmegaLambda1998/Supernovae.jl/badge.svg?branch=main)](https://coveralls.io/github/OmegaLambda1998/Supernovae.jl?branch=main) # [Supernovae.jl](https://github.com/OmegaLambda1998/Supernovae.jl) Documentation Provides methods for reading in and plotting supernova lightcurves from text files. Extremely flexible reading methods allow for almost any reasonable lightcurve data file syntax to be read. ## Prerequisites To automatically download passbands from the [SVO Filter Profile Service](http://svo2.cab.inta-csic.es/theory/fps/), you must install the python package [astroquery](https://astroquery.readthedocs.io/en/latest/index.html). This is installed as part of the build process, installing into a `Conda.jl` conda environment. ## Install ```bash $ git clone [email protected]:OmegaLambda1998/Supernovae.jl.git $ cd Supernovae.jl $ make ``` This will instantiate and build `Supernovae.jl`, installing all required Julia packages, and setting up a Conda environment for the required Python packages. Finally it will run the tests to make sure everything is working. If you want to skip testing run `make install` instead. You can also run `./scripts/Supernovae -v ./Examples/Inputs/2021zby/2021zby_data.toml` to load and plot the lightcurve of 2021zby. This will create a `.svg` plot in `./Examples/Outputs/2021zby/`. ## Usage ```bash $ ./scripts/Supernovae -v path/to/input.toml ``` Details on how to build the input files which control `Supernovae.jl` can be found in [Usage](./usage.md). ## Example data file The following example input file can be found in the Examples directory. `base_path` is the directory containing your input file. ```toml [ global ] filter_path = "../Filters" # Defaults to base_path / Filters output_path = "../../Outputs/2021zby" # Defaults to base_path / Output # Data [ data ] # First include information about the supernova name = "2021zby" # Required zeropoint = 8.9 # Required redshift = 0.02559 # Required max_flux_err = 2.5e2 # Optional, set's the maximum allowed value for the uncertainty in the flux, assumes same units as flux peak_time = true # Default false. Can either be true, in which case all times will become relative to the peak data point. Alternatively, give a value, and all times will be relative to that value peak_time_unit = "d" # Optional, default to d [[ data.observations ]] # Now load in different observations of the supernova. This can either be one file with all observations, or you can load in multiple files name = "atlas" # Required, Human readable name to distinguish observations path = "atlas_1007.dat" # Required, Accepts either relative (to Supernova) or absolute path delimiter = " " # Optional, defaults to comma facility = "Misc" instrument = "Atlas" # Optional, will overwrite anything in the file upperlimit = "flux_err" # Since this file contains a header that isn't in the expected format, you can optionally specify what each header corresponds to. # If you do this you MUST specify the time, flux, and flux error. # You can also specify the filter, instrument, or upperlimit columns if they're in the file. If not, specify them above header.time.col = "MJD" header.time.unit = "d" header.flux.col = "uJy" header.flux.unit = "Β΅Jy" header.flux_err.col = "duJy" header.flux_err.unit = "Β΅Jy" header.passband.col = "F" [[ data.observations ]] name = "tess 6hr" path = "tess_2_6hrlc.txt" delimiter = " " comment = "#" # Optional, defines what is a comment (will be removed). Defaults to # facility = "tess" instrument = "tess" passband = "Red" filter_name = "Tess" upperlimit = false flux_offset = 0.296 # Defaults to 0, assumes same units as flux [[ plot.lightcurve ]] filters = ["Red", "orange"] markersize = 21 marker."tess 6hr" = "utriangle" rename."tess 6hr" = "Tess (6hr)" marker.atlas = "circle" rename.atlas = "Atlas" colour.Red = "red" rename.Red = "Tess: Red" rename.orange = "Atlas: Orange (+150 ΞΌJy)" colour.orange = "orange" offset.orange = 150 legend = true ```
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
1.0.0
deabfde09b46a5730813f23a6656588c6ab14bed
docs
9076
# Usage Details To load a supernova with `Supernovae.jl` you must create an input file containing details on how to read the lightcurve files of the supernova. This file is read in using [BetterInputFiles.jl](https://www.omegalambda.au/BetterInputFiles.jl/dev/), which provides a number of advantages, including: - Choice of `.yaml`, `.toml`, or `.json` files. All examples will be `.toml` but you can choose whichever is preferable for your workflow. - Case-insensitive keys - Ability to include other files via `<include path/to/file.toml>`. This will essentially copy paste the contents of `file.toml` into your input file. - Ability to interpolate environmental variables via `<$ENV_VAR>`. - Ability to interpolate other keys in your input via `<%key>`. As long as `<%key>` exists in the same subtree, the value of key will be interpolated, allowing for easy duplication. - Default values via `[DEFAULT]`. Default sub-keys are available everywhere. This is particularly useful when combined with interpolation. See the BetterInputFiles [documentation](https://www.omegalambda.au/BetterInputFiles.jl/dev/) for more details and examples about how this all works. ## Supernovae.jl Input Files There are three keys which can be included in a supernova's input file, `[ global ]`, `[ data ]`, and `[ plot ]`. ### `[ global ]` `[ global ]` controls file-paths and is optional. File paths can be absolute, or relative to `base_path` which, by default, is the parent directory of the input file. The file paths that can be defined are: ```toml [ global ] base_path = "./" # All other paths will be relative to this path output_path = "base_path/Output" # Where all output will be placed filter_path = "base_path/Filters" # Where filter transmission curves will be saved and loaded data_path = "base_path/Data" # any relative paths to data files will be relative to data_path ``` ### `[ data ]` `[ data ]` includes all the options for loading in your supernova and is required. `data` keys include: ```toml [ data ] name::String # The name of the supernova zeropoint::Float64 # The zeropoint of the supernova zeropoint_unit::String="AB_mag" # The unit of the zeropoint. redshift::Float64 # The redshift of the supernova max_flux_err::Float64=Inf # The maximum allowed flux error. Any datapoint with flux error greater than this will be removed. Assumes the same units as flux. peak_time::Union{Bool, Float64}=false # If true, set time relatative to the time of maximum flux. Alternatively, provide a value for time to be set relative to. Assumes the same units as time ``` In addition to these options, you must specify `[[ data.observations ]]`, which contain details on the data files you with to associate with this supernova. The main assumption is that columns are different parameters and rows are different datapoints. Since `[[ data.observations ]]` is a list object, you can include as many files as you want, and they will all get collated into the one supernova object. `observations` keys include: ```toml [[ data.observations ]] name::String # Human readable name of the observations. Typically this is the survey responsible for the observations path::String # Path to data file containing photometry information. Can be absolute or relative (to data_path). delimiter::String=", " # Delimiter of the data file. comment::String="#" # Comment character of the data file. facility::Union{String,Nothing}=nothing # Override the facility responsible for the data. Use this if this information is not available in the data file. instrument::Union{String,Nothing}=nothing # Override the instrument responsible for the data. Use this if this information is not available in the data file. passband::Union{String,Nothing}=nothing # Override the passband of the data. Use this if this information is not available in the data file. upperlimit::Union{Bool,String,Nothing}=nothing # Override whether the data is an upperlimit. The String options include ["time", "flux", "flux_err"]. If a String, upperlimit is true if that parameter is negative. Use this if this information is not available in the data file. flux_offset::Float64=0 # Apply an offset to the flux. Assumes flux_offset is the same unit as flux. upperlimit_true::Vector{String}=["T", "TRUE"] # Provides the (case-insensitive) string which corresponds to an upperlimit being true. Used when reading the upperlimit from a column of the data file. upperlimit_false::Vector{String}=["F", "FALSE"] # Provides the (case-insensitive) string which corresponds to an upperlimit being false. Used when reading the upperlimit from a column of the data file. ``` The rest of the `observations` keys are related to loading in data from the data file. Your data file must include per-observation time, flux, and flux error information. Additionally, per-observation facility, instrument, passband, and upperlimit information can be included. In general there are three different ways to load a parameter from the data file. #### Default Method The default assumption is that the data file has a header line with syntax: ``` time [d], flux [ΞΌJy], flux_err [ΞΌJy] ``` If this is the case, then you need not provide any more details and `Supernovae.jl` will be able to extract these. #### Column Name If your header doesn't exactly match the default header, then you can specify which column corresponds to which parameter via the header name of that parameter: ```toml [[ data.observations ]] header.time.col = "MJD" # The name of the time column header.time.unit = "d" # The unit of the time column header.flux.col = "brightness" # The name of the time column header.flux.unit = "ΞΌJy" # The unit of the time column header.flux_err.col = "d_brightness" # The name of the time column header.flux_err.unit = "ΞΌJy" # The unit of the time column header.facility.col = "survey" # The name of the facility column header.instrument.col = "telescope" # The name of the instrument column header.passband.col = "filter" # The name of the passband column header.upperlimit.col = "is_real" # The name of the upperlimit column ``` In addition to specifying the unit of a parameter, you can also specify `header.parameter.unit_col` to give the column name containing the unit of that parameter. #### Column Index Instead of `header.parameter.col` being the name of the column, you can provide the index of the column. This can be mixed and matched with the column name method to allow you to load in a large number of different syntaxes. #### Filter details Your choice of `facility`, `instrument`, and `passband` is very important. `Supernovae.jl` will search `filter_path` for a transmission curve file with name `facility__instrument__passband`. If you have the passband for all your observations, make sure to put them in `filter_path`! If you don't, check if they're available on the [SVO Filter Profile Service](http://svo2.cab.inta-csic.es/theory/fps/). If so, make sure `facility`, `instrument`, and `passband` match the SVO FPS syntax as `Supernovae.jl` will attempt to download the transmission curve and save it to `filter_path`. Transission curve files should be comma seperated files containing the wavelength (in angstroms), and the transmission at that wavelength. Check the Examples directory to see what to expect. ### `[ plot ]` The `plot` key is optional, with `Supernovae.jl` only producing plots if this key exists. At the moment only lightcurve plots are implemented, but in the future there will be filter, and spectra plots. #### `[[ plot.lightcurve ]]` The lightcurve plot has a number of keys used to customise your plot. You can make any number of lightcurve plots by defining multiple `[[ plot.lightcurve ]]` keys. ```toml [ plot.lightcurve ]] path::String="$(supernova.name)_lightcurve.svg" # Where to save the plot, relative to output_path datatype::String="flux" # What type of data to plot. Options include "flux", "magnitude", and "abs_magnitude". unit.time::String="d" # Time unit unit.data::String=["ΞΌJy", "AB_mag"] # Depending on the type of data, this will default to either ΞΌJy or AB_mag. name::Union{Vector{String},Nothing}=nothing # What observations to include, based on their human readable name. If nothing, all observations are included. filters::Union{Vector{String},Nothing}=nothing # What passbands to include. If nothing, all passbands are included. rename.[passband, obs_name]::String=new_name # Optionally rename passband or obs_name to new_name. Useful if you don't want to use the SVO name, or want to add additional detail. offset.[passband, obs_name]::Float64=0 # Optionally include an offset to the given passband or obs_name. If an observation has both passband and obs_name, it will be offset twice! markersize::Int64=11 # Set the marker size. marker.obs_name::String="nothing" # Set the marker type for observations with name obs_name. If "nothing", default marker is used. colour.passband::Union{String,Nothing}=nothing # Set the colour for passband. If nothing, default colours are used. legend::Bool=true # Whether to include a legend in the plot. ```
Supernovae
https://github.com/OmegaLambda1998/Supernovae.jl.git
[ "MIT" ]
0.2.5
c0aa4b519104fecca9bc146c9843393f7cbd3c99
code
3989
module AbstractNumbers using SpecialFunctions # Yeah yeah, how ironic abstract type AbstractNumber{T} <: Number end abstract type AbstractReal{T} <: Real end const AbstractNumberOrReal = Union{AbstractNumber{T},AbstractReal{T}} where T # convert(Number, my_type) & is the only interface one needs to overload @inline basetype(T::Type{<:AbstractNumberOrReal}) = error("AbstractNumbers.basetype not implemented for $T") @inline basetype(x::T) where T <: AbstractNumberOrReal = basetype(T) @inline number(x::AbstractNumberOrReal) = error("AbstractNumbers.number not implemented for $(typeof(x))") @inline function Base.convert(::Type{AN}, x::AbstractNumberOrReal{T2}) where {AN <: AbstractNumberOrReal{T}, T2} where T AN(T(number(x))) end @inline function Base.convert(::Type{AN}, x::Number) where AN <: AbstractNumberOrReal{T} where T AN(x) end @inline function Base.convert(::Type{T}, x::AbstractNumberOrReal) where T <: Number if isabstracttype(T) return x else return convert(T, number(x)) end end """ like(num::Union{AbstractNumber,AbstractReal}, x::T) Creates a number from `x` like the first argument. It discards the eltype of `num` and uses the type of `x` instead. usage: ``` like(MyAbstractNumber(1f0), 22) === MyAbstractNumber{Int}(22) ``` """ @inline like(num::AN, x::T) where {AN <: AbstractNumberOrReal, T} = like(AN, x) @inline like(::Type{AN}, x::T) where {AN <: AbstractNumberOrReal, T} = basetype(AN){T}(x) # Not sure if this is the most performant and correct way, but this enables # that == and friends return a bool. Returning an AbstractNumberOrReal{Bool} seems a bit odd @inline like(::Type{AN}, x::Tuple) where AN <: AbstractNumberOrReal = like.(AN, x) @inline Base.typemax(::Type{Num}) where Num <: AbstractNumberOrReal{T} where T = like(Num, typemax(T)) @inline Base.typemin(::Type{Num}) where Num <: AbstractNumberOrReal{T} where T = like(Num, typemin(T)) @inline Base.typemax(::T) where T <: AbstractNumberOrReal = typemax(T) @inline Base.typemin(::T) where T <: AbstractNumberOrReal = typemax(T) @inline Base.eltype(x::T) where T <: AbstractNumberOrReal = T @inline Base.eltype(::Type{T}) where T <: AbstractNumberOrReal = T include("overloads.jl") rem(x::AbstractNumber, y::AbstractNumber, r::RoundingMode) = like(x, rem(number(x), number(y), r)) rem(x::AbstractReal, y::AbstractReal, r::RoundingMode) = like(x, rem(number(x), number(y), r)) # Overload ambiguities for (M, f, A, B) in [ (Base, :^, Irrational{:β„―}, AbstractNumber), (Base, :^, Irrational{:β„―}, AbstractReal), (Base, :log, Irrational{:β„―}, AbstractNumber), (Base, :log, Irrational{:β„―}, AbstractReal), (Base, :flipsign, Signed, AbstractReal), (Base, :flipsign, Float32, AbstractReal), (Base, :flipsign, Float64, AbstractReal), (Base, :copysign, Float32, AbstractReal), (Base, :copysign, Float64, AbstractReal), (Base, :copysign, Rational, AbstractReal), (Base, :copysign, Signed, AbstractReal), (SpecialFunctions, :polygamma, Integer, AbstractNumber), (SpecialFunctions, :polygamma, Integer, AbstractReal), ] @eval $M.$f(a::$A, b::$B) = like(a, $f(a, number(b))) end for (M, f, A, B) in [ (SpecialFunctions, :besselkx, AbstractReal, AbstractFloat), (SpecialFunctions, :besselyx, AbstractReal, AbstractFloat), (SpecialFunctions, :besselj, AbstractReal, AbstractFloat), (SpecialFunctions, :besselk, AbstractReal, AbstractFloat), (SpecialFunctions, :besseli, AbstractReal, AbstractFloat), (SpecialFunctions, :bessely, AbstractReal, AbstractFloat), (SpecialFunctions, :besselix, AbstractReal, AbstractFloat), (SpecialFunctions, :besseljx, AbstractReal, AbstractFloat), (Base, :^, AbstractNumber, Integer), (Base, :^, AbstractNumber, Rational), (Base, :^, AbstractReal, Rational), (Base, :^, AbstractReal, Integer), ] @eval $M.$f(a::$A, b::$B) = like(a, $f(number(a), b)) end export AbstractNumber, AbstractReal end # module
AbstractNumbers
https://github.com/SimonDanisch/AbstractNumbers.jl.git
[ "MIT" ]
0.2.5
c0aa4b519104fecca9bc146c9843393f7cbd3c99
code
4569
using SpecialFunctions all_funcs = ( :~, :conj, :abs, :sin, :cos, :tan, :sinh, :cosh, :tanh, :asin, :acos, :atan, :asinh, :acosh, :atanh, :sec, :csc, :cot, :asec, :acsc, :acot, :sech, :csch, :coth, :asech, :acsch, :acoth, :sinc, :cosc, :cosd, :cotd, :cscd, :secd, :sind, :tand, :acosd, :acotd, :acscd, :asecd, :asind, :atand, :rad2deg, :deg2rad, :log, :log2, :log10, :log1p, :exponent, :exp, :exp2, :expm1, :cbrt, :sqrt, :ceil, :floor, :trunc, :round, :significand, :frexp, :ldexp, :modf, :real, :imag, :!, :identity, :zero, :one, :<<, :>>, :abs2, :sign, :sinpi, :cospi, :exp10, :iseven, :ispow2, :isfinite, :isinf, :isodd, :isinteger, :isreal, :isnan, :isempty, :iszero, :transpose, :copysign, :flipsign, :signbit, :+, :-, :*, :/, :\, :^, :(==), :(!=), :<, :(<=), :>, :(>=), :β‰ˆ, :min, :max, :div, :fld, :rem, :mod, :mod1, :cmp, :&, :|, :xor, :clamp ) special_funcs = ( :airyai, :airyaiprime, :airybi, :airybiprime, :airyaix, :airyaiprimex, :airybix, :airybiprimex, :besselh, :besselhx, :besseli, :besselix, :besselj, :besselj0, :besselj1, :besseljx, :besselk, :besselkx, :bessely, :bessely0, :bessely1, :besselyx, :dawson, :erf, :erfc, :erfcinv, :erfcx, :erfi, :erfinv, :eta, :digamma, :invdigamma, :polygamma, :trigamma, :hankelh1, :hankelh1x, :hankelh2, :hankelh2x, :zeta ) function to_abstract(x::Type{T}) where T <: Number isa(x, Union) && return to_abstract(reduce(Base.typejoin, Base.uniontypes(x))) AbstractNumber end function to_abstract(x::T) where T x == Any && return Number isa(x, TypeVar) && return to_abstract(x.ub) return x end function isa_number(T::Type) return T <: Number || T == Any end function isa_number(tv::TypeVar) isa_number(tv.ub) end function isa_number(tv) false end open(joinpath(@__DIR__, "overloads.jl"), "w") do io for (mod, funcs) in ((Base, all_funcs), (SpecialFunctions, special_funcs)), f in funcs func = getfield(mod, f) ms = methods(func) sigs = [] for m in ms #TODO infer correct types sig = (Base.unwrap_unionall(m.sig).parameters...,)[2:end] if all(isa_number, sig) # _RT = Base.Core.Inference.return_type(func, Tuple{sig...}) # isleaftype(_RT) && (RT = _RT) push!(sigs, m.nargs - 1) end end sigs = sort(unique(sigs)) if f in (:+, :-, :*, :|, :&, :xor) && length(sigs) >= 2 sigs = sigs[1:2] end for n in sigs (n == 3 && f == :cmp) && continue boolfunc = f in ( :(==), :(!=), :<, :(<=), :>, :(>=), :β‰ˆ ) || startswith(string(f), "is") argnames = ntuple(i-> Symbol("arg$i"), n) number_args = map(x-> :($x::AbstractNumber), argnames) real_args = map(x-> :($x::AbstractReal), argnames) converted = map(x-> :(number($x)), argnames) fname = "$mod.$(sprint(show, f))" ret = boolfunc ? "tmp" : "like(arg1, tmp)" println(io, """ function $fname($(join(number_args, ", "))) tmp = $fname($(join(converted, ", "))) $ret end function $fname($(join(real_args, ", "))) tmp = $fname($(join(converted, ", "))) $ret end """) # I think it only makes sense to define all permutations only for binary ops. # The rest seems to be too bug ridden if n == 2 ret = boolfunc ? "tmp" : "like(a, tmp)" println(io, """ function $fname(a::AbstractNumber, b::Number) tmp = $fname(number(a), b) $ret end function $fname(a::AbstractReal, b::Real) tmp = $fname(number(a), b) $ret end """) ret = boolfunc ? "tmp" : "like(b, tmp)" println(io, """ function $fname(a::Number, b::AbstractNumber) tmp = $fname(a, number(b)) $ret end function $fname(a::Real, b::AbstractReal) tmp = $fname(a, number(b)) $ret end """) end end end end
AbstractNumbers
https://github.com/SimonDanisch/AbstractNumbers.jl.git
[ "MIT" ]
0.2.5
c0aa4b519104fecca9bc146c9843393f7cbd3c99
code
62786
function Base.:~(arg1::AbstractNumber) tmp = Base.:~(number(arg1)) like(arg1, tmp) end function Base.:~(arg1::AbstractReal) tmp = Base.:~(number(arg1)) like(arg1, tmp) end function Base.:conj(arg1::AbstractNumber) tmp = Base.:conj(number(arg1)) like(arg1, tmp) end function Base.:conj(arg1::AbstractReal) tmp = Base.:conj(number(arg1)) like(arg1, tmp) end function Base.:abs(arg1::AbstractNumber) tmp = Base.:abs(number(arg1)) like(arg1, tmp) end function Base.:abs(arg1::AbstractReal) tmp = Base.:abs(number(arg1)) like(arg1, tmp) end function Base.:sin(arg1::AbstractNumber) tmp = Base.:sin(number(arg1)) like(arg1, tmp) end function Base.:sin(arg1::AbstractReal) tmp = Base.:sin(number(arg1)) like(arg1, tmp) end function Base.:cos(arg1::AbstractNumber) tmp = Base.:cos(number(arg1)) like(arg1, tmp) end function Base.:cos(arg1::AbstractReal) tmp = Base.:cos(number(arg1)) like(arg1, tmp) end function Base.:tan(arg1::AbstractNumber) tmp = Base.:tan(number(arg1)) like(arg1, tmp) end function Base.:tan(arg1::AbstractReal) tmp = Base.:tan(number(arg1)) like(arg1, tmp) end function Base.:sinh(arg1::AbstractNumber) tmp = Base.:sinh(number(arg1)) like(arg1, tmp) end function Base.:sinh(arg1::AbstractReal) tmp = Base.:sinh(number(arg1)) like(arg1, tmp) end function Base.:cosh(arg1::AbstractNumber) tmp = Base.:cosh(number(arg1)) like(arg1, tmp) end function Base.:cosh(arg1::AbstractReal) tmp = Base.:cosh(number(arg1)) like(arg1, tmp) end function Base.:tanh(arg1::AbstractNumber) tmp = Base.:tanh(number(arg1)) like(arg1, tmp) end function Base.:tanh(arg1::AbstractReal) tmp = Base.:tanh(number(arg1)) like(arg1, tmp) end function Base.:asin(arg1::AbstractNumber) tmp = Base.:asin(number(arg1)) like(arg1, tmp) end function Base.:asin(arg1::AbstractReal) tmp = Base.:asin(number(arg1)) like(arg1, tmp) end function Base.:acos(arg1::AbstractNumber) tmp = Base.:acos(number(arg1)) like(arg1, tmp) end function Base.:acos(arg1::AbstractReal) tmp = Base.:acos(number(arg1)) like(arg1, tmp) end function Base.:atan(arg1::AbstractNumber) tmp = Base.:atan(number(arg1)) like(arg1, tmp) end function Base.:atan(arg1::AbstractReal) tmp = Base.:atan(number(arg1)) like(arg1, tmp) end function Base.:atan(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:atan(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:atan(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:atan(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:atan(a::AbstractNumber, b::Number) tmp = Base.:atan(number(a), b) like(a, tmp) end function Base.:atan(a::AbstractReal, b::Real) tmp = Base.:atan(number(a), b) like(a, tmp) end function Base.:atan(a::Number, b::AbstractNumber) tmp = Base.:atan(a, number(b)) like(b, tmp) end function Base.:atan(a::Real, b::AbstractReal) tmp = Base.:atan(a, number(b)) like(b, tmp) end function Base.:asinh(arg1::AbstractNumber) tmp = Base.:asinh(number(arg1)) like(arg1, tmp) end function Base.:asinh(arg1::AbstractReal) tmp = Base.:asinh(number(arg1)) like(arg1, tmp) end function Base.:acosh(arg1::AbstractNumber) tmp = Base.:acosh(number(arg1)) like(arg1, tmp) end function Base.:acosh(arg1::AbstractReal) tmp = Base.:acosh(number(arg1)) like(arg1, tmp) end function Base.:atanh(arg1::AbstractNumber) tmp = Base.:atanh(number(arg1)) like(arg1, tmp) end function Base.:atanh(arg1::AbstractReal) tmp = Base.:atanh(number(arg1)) like(arg1, tmp) end function Base.:sec(arg1::AbstractNumber) tmp = Base.:sec(number(arg1)) like(arg1, tmp) end function Base.:sec(arg1::AbstractReal) tmp = Base.:sec(number(arg1)) like(arg1, tmp) end function Base.:csc(arg1::AbstractNumber) tmp = Base.:csc(number(arg1)) like(arg1, tmp) end function Base.:csc(arg1::AbstractReal) tmp = Base.:csc(number(arg1)) like(arg1, tmp) end function Base.:cot(arg1::AbstractNumber) tmp = Base.:cot(number(arg1)) like(arg1, tmp) end function Base.:cot(arg1::AbstractReal) tmp = Base.:cot(number(arg1)) like(arg1, tmp) end function Base.:asec(arg1::AbstractNumber) tmp = Base.:asec(number(arg1)) like(arg1, tmp) end function Base.:asec(arg1::AbstractReal) tmp = Base.:asec(number(arg1)) like(arg1, tmp) end function Base.:acsc(arg1::AbstractNumber) tmp = Base.:acsc(number(arg1)) like(arg1, tmp) end function Base.:acsc(arg1::AbstractReal) tmp = Base.:acsc(number(arg1)) like(arg1, tmp) end function Base.:acot(arg1::AbstractNumber) tmp = Base.:acot(number(arg1)) like(arg1, tmp) end function Base.:acot(arg1::AbstractReal) tmp = Base.:acot(number(arg1)) like(arg1, tmp) end function Base.:sech(arg1::AbstractNumber) tmp = Base.:sech(number(arg1)) like(arg1, tmp) end function Base.:sech(arg1::AbstractReal) tmp = Base.:sech(number(arg1)) like(arg1, tmp) end function Base.:csch(arg1::AbstractNumber) tmp = Base.:csch(number(arg1)) like(arg1, tmp) end function Base.:csch(arg1::AbstractReal) tmp = Base.:csch(number(arg1)) like(arg1, tmp) end function Base.:coth(arg1::AbstractNumber) tmp = Base.:coth(number(arg1)) like(arg1, tmp) end function Base.:coth(arg1::AbstractReal) tmp = Base.:coth(number(arg1)) like(arg1, tmp) end function Base.:asech(arg1::AbstractNumber) tmp = Base.:asech(number(arg1)) like(arg1, tmp) end function Base.:asech(arg1::AbstractReal) tmp = Base.:asech(number(arg1)) like(arg1, tmp) end function Base.:acsch(arg1::AbstractNumber) tmp = Base.:acsch(number(arg1)) like(arg1, tmp) end function Base.:acsch(arg1::AbstractReal) tmp = Base.:acsch(number(arg1)) like(arg1, tmp) end function Base.:acoth(arg1::AbstractNumber) tmp = Base.:acoth(number(arg1)) like(arg1, tmp) end function Base.:acoth(arg1::AbstractReal) tmp = Base.:acoth(number(arg1)) like(arg1, tmp) end function Base.:sinc(arg1::AbstractNumber) tmp = Base.:sinc(number(arg1)) like(arg1, tmp) end function Base.:sinc(arg1::AbstractReal) tmp = Base.:sinc(number(arg1)) like(arg1, tmp) end function Base.:cosc(arg1::AbstractNumber) tmp = Base.:cosc(number(arg1)) like(arg1, tmp) end function Base.:cosc(arg1::AbstractReal) tmp = Base.:cosc(number(arg1)) like(arg1, tmp) end function Base.:cosd(arg1::AbstractNumber) tmp = Base.:cosd(number(arg1)) like(arg1, tmp) end function Base.:cosd(arg1::AbstractReal) tmp = Base.:cosd(number(arg1)) like(arg1, tmp) end function Base.:cotd(arg1::AbstractNumber) tmp = Base.:cotd(number(arg1)) like(arg1, tmp) end function Base.:cotd(arg1::AbstractReal) tmp = Base.:cotd(number(arg1)) like(arg1, tmp) end function Base.:cscd(arg1::AbstractNumber) tmp = Base.:cscd(number(arg1)) like(arg1, tmp) end function Base.:cscd(arg1::AbstractReal) tmp = Base.:cscd(number(arg1)) like(arg1, tmp) end function Base.:secd(arg1::AbstractNumber) tmp = Base.:secd(number(arg1)) like(arg1, tmp) end function Base.:secd(arg1::AbstractReal) tmp = Base.:secd(number(arg1)) like(arg1, tmp) end function Base.:sind(arg1::AbstractNumber) tmp = Base.:sind(number(arg1)) like(arg1, tmp) end function Base.:sind(arg1::AbstractReal) tmp = Base.:sind(number(arg1)) like(arg1, tmp) end function Base.:tand(arg1::AbstractNumber) tmp = Base.:tand(number(arg1)) like(arg1, tmp) end function Base.:tand(arg1::AbstractReal) tmp = Base.:tand(number(arg1)) like(arg1, tmp) end function Base.:acosd(arg1::AbstractNumber) tmp = Base.:acosd(number(arg1)) like(arg1, tmp) end function Base.:acosd(arg1::AbstractReal) tmp = Base.:acosd(number(arg1)) like(arg1, tmp) end function Base.:acotd(arg1::AbstractNumber) tmp = Base.:acotd(number(arg1)) like(arg1, tmp) end function Base.:acotd(arg1::AbstractReal) tmp = Base.:acotd(number(arg1)) like(arg1, tmp) end function Base.:acscd(arg1::AbstractNumber) tmp = Base.:acscd(number(arg1)) like(arg1, tmp) end function Base.:acscd(arg1::AbstractReal) tmp = Base.:acscd(number(arg1)) like(arg1, tmp) end function Base.:asecd(arg1::AbstractNumber) tmp = Base.:asecd(number(arg1)) like(arg1, tmp) end function Base.:asecd(arg1::AbstractReal) tmp = Base.:asecd(number(arg1)) like(arg1, tmp) end function Base.:asind(arg1::AbstractNumber) tmp = Base.:asind(number(arg1)) like(arg1, tmp) end function Base.:asind(arg1::AbstractReal) tmp = Base.:asind(number(arg1)) like(arg1, tmp) end function Base.:atand(arg1::AbstractNumber) tmp = Base.:atand(number(arg1)) like(arg1, tmp) end function Base.:atand(arg1::AbstractReal) tmp = Base.:atand(number(arg1)) like(arg1, tmp) end function Base.:atand(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:atand(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:atand(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:atand(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:atand(a::AbstractNumber, b::Number) tmp = Base.:atand(number(a), b) like(a, tmp) end function Base.:atand(a::AbstractReal, b::Real) tmp = Base.:atand(number(a), b) like(a, tmp) end function Base.:atand(a::Number, b::AbstractNumber) tmp = Base.:atand(a, number(b)) like(b, tmp) end function Base.:atand(a::Real, b::AbstractReal) tmp = Base.:atand(a, number(b)) like(b, tmp) end function Base.:rad2deg(arg1::AbstractNumber) tmp = Base.:rad2deg(number(arg1)) like(arg1, tmp) end function Base.:rad2deg(arg1::AbstractReal) tmp = Base.:rad2deg(number(arg1)) like(arg1, tmp) end function Base.:deg2rad(arg1::AbstractNumber) tmp = Base.:deg2rad(number(arg1)) like(arg1, tmp) end function Base.:deg2rad(arg1::AbstractReal) tmp = Base.:deg2rad(number(arg1)) like(arg1, tmp) end function Base.:log(arg1::AbstractNumber) tmp = Base.:log(number(arg1)) like(arg1, tmp) end function Base.:log(arg1::AbstractReal) tmp = Base.:log(number(arg1)) like(arg1, tmp) end function Base.:log(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:log(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:log(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:log(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:log(a::AbstractNumber, b::Number) tmp = Base.:log(number(a), b) like(a, tmp) end function Base.:log(a::AbstractReal, b::Real) tmp = Base.:log(number(a), b) like(a, tmp) end function Base.:log(a::Number, b::AbstractNumber) tmp = Base.:log(a, number(b)) like(b, tmp) end function Base.:log(a::Real, b::AbstractReal) tmp = Base.:log(a, number(b)) like(b, tmp) end function Base.:log2(arg1::AbstractNumber) tmp = Base.:log2(number(arg1)) like(arg1, tmp) end function Base.:log2(arg1::AbstractReal) tmp = Base.:log2(number(arg1)) like(arg1, tmp) end function Base.:log10(arg1::AbstractNumber) tmp = Base.:log10(number(arg1)) like(arg1, tmp) end function Base.:log10(arg1::AbstractReal) tmp = Base.:log10(number(arg1)) like(arg1, tmp) end function Base.:log1p(arg1::AbstractNumber) tmp = Base.:log1p(number(arg1)) like(arg1, tmp) end function Base.:log1p(arg1::AbstractReal) tmp = Base.:log1p(number(arg1)) like(arg1, tmp) end function Base.:exponent(arg1::AbstractNumber) tmp = Base.:exponent(number(arg1)) like(arg1, tmp) end function Base.:exponent(arg1::AbstractReal) tmp = Base.:exponent(number(arg1)) like(arg1, tmp) end function Base.:exp(arg1::AbstractNumber) tmp = Base.:exp(number(arg1)) like(arg1, tmp) end function Base.:exp(arg1::AbstractReal) tmp = Base.:exp(number(arg1)) like(arg1, tmp) end function Base.:exp2(arg1::AbstractNumber) tmp = Base.:exp2(number(arg1)) like(arg1, tmp) end function Base.:exp2(arg1::AbstractReal) tmp = Base.:exp2(number(arg1)) like(arg1, tmp) end function Base.:expm1(arg1::AbstractNumber) tmp = Base.:expm1(number(arg1)) like(arg1, tmp) end function Base.:expm1(arg1::AbstractReal) tmp = Base.:expm1(number(arg1)) like(arg1, tmp) end function Base.:cbrt(arg1::AbstractNumber) tmp = Base.:cbrt(number(arg1)) like(arg1, tmp) end function Base.:cbrt(arg1::AbstractReal) tmp = Base.:cbrt(number(arg1)) like(arg1, tmp) end function Base.:sqrt(arg1::AbstractNumber) tmp = Base.:sqrt(number(arg1)) like(arg1, tmp) end function Base.:sqrt(arg1::AbstractReal) tmp = Base.:sqrt(number(arg1)) like(arg1, tmp) end function Base.:ceil(arg1::AbstractNumber) tmp = Base.:ceil(number(arg1)) like(arg1, tmp) end function Base.:ceil(arg1::AbstractReal) tmp = Base.:ceil(number(arg1)) like(arg1, tmp) end function Base.:floor(arg1::AbstractNumber) tmp = Base.:floor(number(arg1)) like(arg1, tmp) end function Base.:floor(arg1::AbstractReal) tmp = Base.:floor(number(arg1)) like(arg1, tmp) end function Base.:trunc(arg1::AbstractNumber) tmp = Base.:trunc(number(arg1)) like(arg1, tmp) end function Base.:trunc(arg1::AbstractReal) tmp = Base.:trunc(number(arg1)) like(arg1, tmp) end function Base.:round(arg1::AbstractNumber) tmp = Base.:round(number(arg1)) like(arg1, tmp) end function Base.:round(arg1::AbstractReal) tmp = Base.:round(number(arg1)) like(arg1, tmp) end function Base.:significand(arg1::AbstractNumber) tmp = Base.:significand(number(arg1)) like(arg1, tmp) end function Base.:significand(arg1::AbstractReal) tmp = Base.:significand(number(arg1)) like(arg1, tmp) end function Base.:frexp(arg1::AbstractNumber) tmp = Base.:frexp(number(arg1)) like(arg1, tmp) end function Base.:frexp(arg1::AbstractReal) tmp = Base.:frexp(number(arg1)) like(arg1, tmp) end function Base.:ldexp(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:ldexp(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:ldexp(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:ldexp(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:ldexp(a::AbstractNumber, b::Number) tmp = Base.:ldexp(number(a), b) like(a, tmp) end function Base.:ldexp(a::AbstractReal, b::Real) tmp = Base.:ldexp(number(a), b) like(a, tmp) end function Base.:ldexp(a::Number, b::AbstractNumber) tmp = Base.:ldexp(a, number(b)) like(b, tmp) end function Base.:ldexp(a::Real, b::AbstractReal) tmp = Base.:ldexp(a, number(b)) like(b, tmp) end function Base.:modf(arg1::AbstractNumber) tmp = Base.:modf(number(arg1)) like(arg1, tmp) end function Base.:modf(arg1::AbstractReal) tmp = Base.:modf(number(arg1)) like(arg1, tmp) end function Base.:real(arg1::AbstractNumber) tmp = Base.:real(number(arg1)) like(arg1, tmp) end function Base.:real(arg1::AbstractReal) tmp = Base.:real(number(arg1)) like(arg1, tmp) end function Base.:imag(arg1::AbstractNumber) tmp = Base.:imag(number(arg1)) like(arg1, tmp) end function Base.:imag(arg1::AbstractReal) tmp = Base.:imag(number(arg1)) like(arg1, tmp) end function Base.:!(arg1::AbstractNumber) tmp = Base.:!(number(arg1)) like(arg1, tmp) end function Base.:!(arg1::AbstractReal) tmp = Base.:!(number(arg1)) like(arg1, tmp) end function Base.:identity(arg1::AbstractNumber) tmp = Base.:identity(number(arg1)) like(arg1, tmp) end function Base.:identity(arg1::AbstractReal) tmp = Base.:identity(number(arg1)) like(arg1, tmp) end function Base.:zero(arg1::AbstractNumber) tmp = Base.:zero(number(arg1)) like(arg1, tmp) end function Base.:zero(arg1::AbstractReal) tmp = Base.:zero(number(arg1)) like(arg1, tmp) end function Base.:one(arg1::AbstractNumber) tmp = Base.:one(number(arg1)) like(arg1, tmp) end function Base.:one(arg1::AbstractReal) tmp = Base.:one(number(arg1)) like(arg1, tmp) end function Base.:<<(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:<<(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:<<(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:<<(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:<<(a::AbstractNumber, b::Number) tmp = Base.:<<(number(a), b) like(a, tmp) end function Base.:<<(a::AbstractReal, b::Real) tmp = Base.:<<(number(a), b) like(a, tmp) end function Base.:<<(a::Number, b::AbstractNumber) tmp = Base.:<<(a, number(b)) like(b, tmp) end function Base.:<<(a::Real, b::AbstractReal) tmp = Base.:<<(a, number(b)) like(b, tmp) end function Base.:>>(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:>>(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:>>(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:>>(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:>>(a::AbstractNumber, b::Number) tmp = Base.:>>(number(a), b) like(a, tmp) end function Base.:>>(a::AbstractReal, b::Real) tmp = Base.:>>(number(a), b) like(a, tmp) end function Base.:>>(a::Number, b::AbstractNumber) tmp = Base.:>>(a, number(b)) like(b, tmp) end function Base.:>>(a::Real, b::AbstractReal) tmp = Base.:>>(a, number(b)) like(b, tmp) end function Base.:abs2(arg1::AbstractNumber) tmp = Base.:abs2(number(arg1)) like(arg1, tmp) end function Base.:abs2(arg1::AbstractReal) tmp = Base.:abs2(number(arg1)) like(arg1, tmp) end function Base.:sign(arg1::AbstractNumber) tmp = Base.:sign(number(arg1)) like(arg1, tmp) end function Base.:sign(arg1::AbstractReal) tmp = Base.:sign(number(arg1)) like(arg1, tmp) end function Base.:sinpi(arg1::AbstractNumber) tmp = Base.:sinpi(number(arg1)) like(arg1, tmp) end function Base.:sinpi(arg1::AbstractReal) tmp = Base.:sinpi(number(arg1)) like(arg1, tmp) end function Base.:cospi(arg1::AbstractNumber) tmp = Base.:cospi(number(arg1)) like(arg1, tmp) end function Base.:cospi(arg1::AbstractReal) tmp = Base.:cospi(number(arg1)) like(arg1, tmp) end function Base.:exp10(arg1::AbstractNumber) tmp = Base.:exp10(number(arg1)) like(arg1, tmp) end function Base.:exp10(arg1::AbstractReal) tmp = Base.:exp10(number(arg1)) like(arg1, tmp) end function Base.:iseven(arg1::AbstractNumber) tmp = Base.:iseven(number(arg1)) tmp end function Base.:iseven(arg1::AbstractReal) tmp = Base.:iseven(number(arg1)) tmp end function Base.:ispow2(arg1::AbstractNumber) tmp = Base.:ispow2(number(arg1)) tmp end function Base.:ispow2(arg1::AbstractReal) tmp = Base.:ispow2(number(arg1)) tmp end function Base.:isfinite(arg1::AbstractNumber) tmp = Base.:isfinite(number(arg1)) tmp end function Base.:isfinite(arg1::AbstractReal) tmp = Base.:isfinite(number(arg1)) tmp end function Base.:isinf(arg1::AbstractNumber) tmp = Base.:isinf(number(arg1)) tmp end function Base.:isinf(arg1::AbstractReal) tmp = Base.:isinf(number(arg1)) tmp end function Base.:isodd(arg1::AbstractNumber) tmp = Base.:isodd(number(arg1)) tmp end function Base.:isodd(arg1::AbstractReal) tmp = Base.:isodd(number(arg1)) tmp end function Base.:isinteger(arg1::AbstractNumber) tmp = Base.:isinteger(number(arg1)) tmp end function Base.:isinteger(arg1::AbstractReal) tmp = Base.:isinteger(number(arg1)) tmp end function Base.:isreal(arg1::AbstractNumber) tmp = Base.:isreal(number(arg1)) tmp end function Base.:isreal(arg1::AbstractReal) tmp = Base.:isreal(number(arg1)) tmp end function Base.:isnan(arg1::AbstractNumber) tmp = Base.:isnan(number(arg1)) tmp end function Base.:isnan(arg1::AbstractReal) tmp = Base.:isnan(number(arg1)) tmp end function Base.:isempty(arg1::AbstractNumber) tmp = Base.:isempty(number(arg1)) tmp end function Base.:isempty(arg1::AbstractReal) tmp = Base.:isempty(number(arg1)) tmp end function Base.:iszero(arg1::AbstractNumber) tmp = Base.:iszero(number(arg1)) tmp end function Base.:iszero(arg1::AbstractReal) tmp = Base.:iszero(number(arg1)) tmp end function Base.:transpose(arg1::AbstractNumber) tmp = Base.:transpose(number(arg1)) like(arg1, tmp) end function Base.:transpose(arg1::AbstractReal) tmp = Base.:transpose(number(arg1)) like(arg1, tmp) end function Base.:copysign(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:copysign(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:copysign(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:copysign(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:copysign(a::AbstractNumber, b::Number) tmp = Base.:copysign(number(a), b) like(a, tmp) end function Base.:copysign(a::AbstractReal, b::Real) tmp = Base.:copysign(number(a), b) like(a, tmp) end function Base.:copysign(a::Number, b::AbstractNumber) tmp = Base.:copysign(a, number(b)) like(b, tmp) end function Base.:copysign(a::Real, b::AbstractReal) tmp = Base.:copysign(a, number(b)) like(b, tmp) end function Base.:flipsign(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:flipsign(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:flipsign(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:flipsign(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:flipsign(a::AbstractNumber, b::Number) tmp = Base.:flipsign(number(a), b) like(a, tmp) end function Base.:flipsign(a::AbstractReal, b::Real) tmp = Base.:flipsign(number(a), b) like(a, tmp) end function Base.:flipsign(a::Number, b::AbstractNumber) tmp = Base.:flipsign(a, number(b)) like(b, tmp) end function Base.:flipsign(a::Real, b::AbstractReal) tmp = Base.:flipsign(a, number(b)) like(b, tmp) end function Base.:signbit(arg1::AbstractNumber) tmp = Base.:signbit(number(arg1)) like(arg1, tmp) end function Base.:signbit(arg1::AbstractReal) tmp = Base.:signbit(number(arg1)) like(arg1, tmp) end function Base.:+(arg1::AbstractNumber) tmp = Base.:+(number(arg1)) like(arg1, tmp) end function Base.:+(arg1::AbstractReal) tmp = Base.:+(number(arg1)) like(arg1, tmp) end function Base.:+(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:+(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:+(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:+(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:+(a::AbstractNumber, b::Number) tmp = Base.:+(number(a), b) like(a, tmp) end function Base.:+(a::AbstractReal, b::Real) tmp = Base.:+(number(a), b) like(a, tmp) end function Base.:+(a::Number, b::AbstractNumber) tmp = Base.:+(a, number(b)) like(b, tmp) end function Base.:+(a::Real, b::AbstractReal) tmp = Base.:+(a, number(b)) like(b, tmp) end function Base.:-(arg1::AbstractNumber) tmp = Base.:-(number(arg1)) like(arg1, tmp) end function Base.:-(arg1::AbstractReal) tmp = Base.:-(number(arg1)) like(arg1, tmp) end function Base.:-(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:-(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:-(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:-(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:-(a::AbstractNumber, b::Number) tmp = Base.:-(number(a), b) like(a, tmp) end function Base.:-(a::AbstractReal, b::Real) tmp = Base.:-(number(a), b) like(a, tmp) end function Base.:-(a::Number, b::AbstractNumber) tmp = Base.:-(a, number(b)) like(b, tmp) end function Base.:-(a::Real, b::AbstractReal) tmp = Base.:-(a, number(b)) like(b, tmp) end function Base.:*(arg1::AbstractNumber) tmp = Base.:*(number(arg1)) like(arg1, tmp) end function Base.:*(arg1::AbstractReal) tmp = Base.:*(number(arg1)) like(arg1, tmp) end function Base.:*(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:*(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:*(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:*(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:*(a::AbstractNumber, b::Number) tmp = Base.:*(number(a), b) like(a, tmp) end function Base.:*(a::AbstractReal, b::Real) tmp = Base.:*(number(a), b) like(a, tmp) end function Base.:*(a::Number, b::AbstractNumber) tmp = Base.:*(a, number(b)) like(b, tmp) end function Base.:*(a::Real, b::AbstractReal) tmp = Base.:*(a, number(b)) like(b, tmp) end function Base.:/(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:/(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:/(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:/(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:/(a::AbstractNumber, b::Number) tmp = Base.:/(number(a), b) like(a, tmp) end function Base.:/(a::AbstractReal, b::Real) tmp = Base.:/(number(a), b) like(a, tmp) end function Base.:/(a::Number, b::AbstractNumber) tmp = Base.:/(a, number(b)) like(b, tmp) end function Base.:/(a::Real, b::AbstractReal) tmp = Base.:/(a, number(b)) like(b, tmp) end function Base.:\(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:\(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:\(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:\(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:\(a::AbstractNumber, b::Number) tmp = Base.:\(number(a), b) like(a, tmp) end function Base.:\(a::AbstractReal, b::Real) tmp = Base.:\(number(a), b) like(a, tmp) end function Base.:\(a::Number, b::AbstractNumber) tmp = Base.:\(a, number(b)) like(b, tmp) end function Base.:\(a::Real, b::AbstractReal) tmp = Base.:\(a, number(b)) like(b, tmp) end function Base.:^(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:^(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:^(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:^(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:^(a::AbstractNumber, b::Number) tmp = Base.:^(number(a), b) like(a, tmp) end function Base.:^(a::AbstractReal, b::Real) tmp = Base.:^(number(a), b) like(a, tmp) end function Base.:^(a::Number, b::AbstractNumber) tmp = Base.:^(a, number(b)) like(b, tmp) end function Base.:^(a::Real, b::AbstractReal) tmp = Base.:^(a, number(b)) like(b, tmp) end function Base.:(==)(arg1::AbstractNumber) tmp = Base.:(==)(number(arg1)) tmp end function Base.:(==)(arg1::AbstractReal) tmp = Base.:(==)(number(arg1)) tmp end function Base.:(==)(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:(==)(number(arg1), number(arg2)) tmp end function Base.:(==)(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:(==)(number(arg1), number(arg2)) tmp end function Base.:(==)(a::AbstractNumber, b::Number) tmp = Base.:(==)(number(a), b) tmp end function Base.:(==)(a::AbstractReal, b::Real) tmp = Base.:(==)(number(a), b) tmp end function Base.:(==)(a::Number, b::AbstractNumber) tmp = Base.:(==)(a, number(b)) tmp end function Base.:(==)(a::Real, b::AbstractReal) tmp = Base.:(==)(a, number(b)) tmp end function Base.:!=(arg1::AbstractNumber) tmp = Base.:!=(number(arg1)) tmp end function Base.:!=(arg1::AbstractReal) tmp = Base.:!=(number(arg1)) tmp end function Base.:!=(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:!=(number(arg1), number(arg2)) tmp end function Base.:!=(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:!=(number(arg1), number(arg2)) tmp end function Base.:!=(a::AbstractNumber, b::Number) tmp = Base.:!=(number(a), b) tmp end function Base.:!=(a::AbstractReal, b::Real) tmp = Base.:!=(number(a), b) tmp end function Base.:!=(a::Number, b::AbstractNumber) tmp = Base.:!=(a, number(b)) tmp end function Base.:!=(a::Real, b::AbstractReal) tmp = Base.:!=(a, number(b)) tmp end function Base.:<(arg1::AbstractNumber) tmp = Base.:<(number(arg1)) tmp end function Base.:<(arg1::AbstractReal) tmp = Base.:<(number(arg1)) tmp end function Base.:<(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:<(number(arg1), number(arg2)) tmp end function Base.:<(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:<(number(arg1), number(arg2)) tmp end function Base.:<(a::AbstractNumber, b::Number) tmp = Base.:<(number(a), b) tmp end function Base.:<(a::AbstractReal, b::Real) tmp = Base.:<(number(a), b) tmp end function Base.:<(a::Number, b::AbstractNumber) tmp = Base.:<(a, number(b)) tmp end function Base.:<(a::Real, b::AbstractReal) tmp = Base.:<(a, number(b)) tmp end function Base.:<=(arg1::AbstractNumber) tmp = Base.:<=(number(arg1)) tmp end function Base.:<=(arg1::AbstractReal) tmp = Base.:<=(number(arg1)) tmp end function Base.:<=(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:<=(number(arg1), number(arg2)) tmp end function Base.:<=(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:<=(number(arg1), number(arg2)) tmp end function Base.:<=(a::AbstractNumber, b::Number) tmp = Base.:<=(number(a), b) tmp end function Base.:<=(a::AbstractReal, b::Real) tmp = Base.:<=(number(a), b) tmp end function Base.:<=(a::Number, b::AbstractNumber) tmp = Base.:<=(a, number(b)) tmp end function Base.:<=(a::Real, b::AbstractReal) tmp = Base.:<=(a, number(b)) tmp end function Base.:>(arg1::AbstractNumber) tmp = Base.:>(number(arg1)) tmp end function Base.:>(arg1::AbstractReal) tmp = Base.:>(number(arg1)) tmp end function Base.:>(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:>(number(arg1), number(arg2)) tmp end function Base.:>(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:>(number(arg1), number(arg2)) tmp end function Base.:>(a::AbstractNumber, b::Number) tmp = Base.:>(number(a), b) tmp end function Base.:>(a::AbstractReal, b::Real) tmp = Base.:>(number(a), b) tmp end function Base.:>(a::Number, b::AbstractNumber) tmp = Base.:>(a, number(b)) tmp end function Base.:>(a::Real, b::AbstractReal) tmp = Base.:>(a, number(b)) tmp end function Base.:>=(arg1::AbstractNumber) tmp = Base.:>=(number(arg1)) tmp end function Base.:>=(arg1::AbstractReal) tmp = Base.:>=(number(arg1)) tmp end function Base.:>=(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:>=(number(arg1), number(arg2)) tmp end function Base.:>=(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:>=(number(arg1), number(arg2)) tmp end function Base.:>=(a::AbstractNumber, b::Number) tmp = Base.:>=(number(a), b) tmp end function Base.:>=(a::AbstractReal, b::Real) tmp = Base.:>=(number(a), b) tmp end function Base.:>=(a::Number, b::AbstractNumber) tmp = Base.:>=(a, number(b)) tmp end function Base.:>=(a::Real, b::AbstractReal) tmp = Base.:>=(a, number(b)) tmp end function Base.:β‰ˆ(arg1::AbstractNumber) tmp = Base.:β‰ˆ(number(arg1)) tmp end function Base.:β‰ˆ(arg1::AbstractReal) tmp = Base.:β‰ˆ(number(arg1)) tmp end function Base.:β‰ˆ(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:β‰ˆ(number(arg1), number(arg2)) tmp end function Base.:β‰ˆ(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:β‰ˆ(number(arg1), number(arg2)) tmp end function Base.:β‰ˆ(a::AbstractNumber, b::Number) tmp = Base.:β‰ˆ(number(a), b) tmp end function Base.:β‰ˆ(a::AbstractReal, b::Real) tmp = Base.:β‰ˆ(number(a), b) tmp end function Base.:β‰ˆ(a::Number, b::AbstractNumber) tmp = Base.:β‰ˆ(a, number(b)) tmp end function Base.:β‰ˆ(a::Real, b::AbstractReal) tmp = Base.:β‰ˆ(a, number(b)) tmp end function Base.:min(arg1::AbstractNumber) tmp = Base.:min(number(arg1)) like(arg1, tmp) end function Base.:min(arg1::AbstractReal) tmp = Base.:min(number(arg1)) like(arg1, tmp) end function Base.:min(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:min(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:min(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:min(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:min(a::AbstractNumber, b::Number) tmp = Base.:min(number(a), b) like(a, tmp) end function Base.:min(a::AbstractReal, b::Real) tmp = Base.:min(number(a), b) like(a, tmp) end function Base.:min(a::Number, b::AbstractNumber) tmp = Base.:min(a, number(b)) like(b, tmp) end function Base.:min(a::Real, b::AbstractReal) tmp = Base.:min(a, number(b)) like(b, tmp) end function Base.:max(arg1::AbstractNumber) tmp = Base.:max(number(arg1)) like(arg1, tmp) end function Base.:max(arg1::AbstractReal) tmp = Base.:max(number(arg1)) like(arg1, tmp) end function Base.:max(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:max(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:max(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:max(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:max(a::AbstractNumber, b::Number) tmp = Base.:max(number(a), b) like(a, tmp) end function Base.:max(a::AbstractReal, b::Real) tmp = Base.:max(number(a), b) like(a, tmp) end function Base.:max(a::Number, b::AbstractNumber) tmp = Base.:max(a, number(b)) like(b, tmp) end function Base.:max(a::Real, b::AbstractReal) tmp = Base.:max(a, number(b)) like(b, tmp) end function Base.:div(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:div(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:div(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:div(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:div(a::AbstractNumber, b::Number) tmp = Base.:div(number(a), b) like(a, tmp) end function Base.:div(a::AbstractReal, b::Real) tmp = Base.:div(number(a), b) like(a, tmp) end function Base.:div(a::Number, b::AbstractNumber) tmp = Base.:div(a, number(b)) like(b, tmp) end function Base.:div(a::Real, b::AbstractReal) tmp = Base.:div(a, number(b)) like(b, tmp) end function Base.:fld(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:fld(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:fld(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:fld(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:fld(a::AbstractNumber, b::Number) tmp = Base.:fld(number(a), b) like(a, tmp) end function Base.:fld(a::AbstractReal, b::Real) tmp = Base.:fld(number(a), b) like(a, tmp) end function Base.:fld(a::Number, b::AbstractNumber) tmp = Base.:fld(a, number(b)) like(b, tmp) end function Base.:fld(a::Real, b::AbstractReal) tmp = Base.:fld(a, number(b)) like(b, tmp) end function Base.:rem(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:rem(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:rem(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:rem(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:rem(a::AbstractNumber, b::Number) tmp = Base.:rem(number(a), b) like(a, tmp) end function Base.:rem(a::AbstractReal, b::Real) tmp = Base.:rem(number(a), b) like(a, tmp) end function Base.:rem(a::Number, b::AbstractNumber) tmp = Base.:rem(a, number(b)) like(b, tmp) end function Base.:rem(a::Real, b::AbstractReal) tmp = Base.:rem(a, number(b)) like(b, tmp) end function Base.:mod(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:mod(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:mod(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:mod(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:mod(a::AbstractNumber, b::Number) tmp = Base.:mod(number(a), b) like(a, tmp) end function Base.:mod(a::AbstractReal, b::Real) tmp = Base.:mod(number(a), b) like(a, tmp) end function Base.:mod(a::Number, b::AbstractNumber) tmp = Base.:mod(a, number(b)) like(b, tmp) end function Base.:mod(a::Real, b::AbstractReal) tmp = Base.:mod(a, number(b)) like(b, tmp) end function Base.:mod1(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:mod1(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:mod1(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:mod1(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:mod1(a::AbstractNumber, b::Number) tmp = Base.:mod1(number(a), b) like(a, tmp) end function Base.:mod1(a::AbstractReal, b::Real) tmp = Base.:mod1(number(a), b) like(a, tmp) end function Base.:mod1(a::Number, b::AbstractNumber) tmp = Base.:mod1(a, number(b)) like(b, tmp) end function Base.:mod1(a::Real, b::AbstractReal) tmp = Base.:mod1(a, number(b)) like(b, tmp) end function Base.:cmp(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:cmp(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:cmp(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:cmp(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:cmp(a::AbstractNumber, b::Number) tmp = Base.:cmp(number(a), b) like(a, tmp) end function Base.:cmp(a::AbstractReal, b::Real) tmp = Base.:cmp(number(a), b) like(a, tmp) end function Base.:cmp(a::Number, b::AbstractNumber) tmp = Base.:cmp(a, number(b)) like(b, tmp) end function Base.:cmp(a::Real, b::AbstractReal) tmp = Base.:cmp(a, number(b)) like(b, tmp) end function Base.:&(arg1::AbstractNumber) tmp = Base.:&(number(arg1)) like(arg1, tmp) end function Base.:&(arg1::AbstractReal) tmp = Base.:&(number(arg1)) like(arg1, tmp) end function Base.:&(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:&(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:&(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:&(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:&(a::AbstractNumber, b::Number) tmp = Base.:&(number(a), b) like(a, tmp) end function Base.:&(a::AbstractReal, b::Real) tmp = Base.:&(number(a), b) like(a, tmp) end function Base.:&(a::Number, b::AbstractNumber) tmp = Base.:&(a, number(b)) like(b, tmp) end function Base.:&(a::Real, b::AbstractReal) tmp = Base.:&(a, number(b)) like(b, tmp) end function Base.:|(arg1::AbstractNumber) tmp = Base.:|(number(arg1)) like(arg1, tmp) end function Base.:|(arg1::AbstractReal) tmp = Base.:|(number(arg1)) like(arg1, tmp) end function Base.:|(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:|(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:|(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:|(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:|(a::AbstractNumber, b::Number) tmp = Base.:|(number(a), b) like(a, tmp) end function Base.:|(a::AbstractReal, b::Real) tmp = Base.:|(number(a), b) like(a, tmp) end function Base.:|(a::Number, b::AbstractNumber) tmp = Base.:|(a, number(b)) like(b, tmp) end function Base.:|(a::Real, b::AbstractReal) tmp = Base.:|(a, number(b)) like(b, tmp) end function Base.:xor(arg1::AbstractNumber) tmp = Base.:xor(number(arg1)) like(arg1, tmp) end function Base.:xor(arg1::AbstractReal) tmp = Base.:xor(number(arg1)) like(arg1, tmp) end function Base.:xor(arg1::AbstractNumber, arg2::AbstractNumber) tmp = Base.:xor(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:xor(arg1::AbstractReal, arg2::AbstractReal) tmp = Base.:xor(number(arg1), number(arg2)) like(arg1, tmp) end function Base.:xor(a::AbstractNumber, b::Number) tmp = Base.:xor(number(a), b) like(a, tmp) end function Base.:xor(a::AbstractReal, b::Real) tmp = Base.:xor(number(a), b) like(a, tmp) end function Base.:xor(a::Number, b::AbstractNumber) tmp = Base.:xor(a, number(b)) like(b, tmp) end function Base.:xor(a::Real, b::AbstractReal) tmp = Base.:xor(a, number(b)) like(b, tmp) end function Base.:clamp(arg1::AbstractNumber, arg2::AbstractNumber, arg3::AbstractNumber) tmp = Base.:clamp(number(arg1), number(arg2), number(arg3)) like(arg1, tmp) end function Base.:clamp(arg1::AbstractReal, arg2::AbstractReal, arg3::AbstractReal) tmp = Base.:clamp(number(arg1), number(arg2), number(arg3)) like(arg1, tmp) end function SpecialFunctions.:airyai(arg1::AbstractNumber) tmp = SpecialFunctions.:airyai(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyai(arg1::AbstractReal) tmp = SpecialFunctions.:airyai(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyaiprime(arg1::AbstractNumber) tmp = SpecialFunctions.:airyaiprime(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyaiprime(arg1::AbstractReal) tmp = SpecialFunctions.:airyaiprime(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybi(arg1::AbstractNumber) tmp = SpecialFunctions.:airybi(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybi(arg1::AbstractReal) tmp = SpecialFunctions.:airybi(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybiprime(arg1::AbstractNumber) tmp = SpecialFunctions.:airybiprime(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybiprime(arg1::AbstractReal) tmp = SpecialFunctions.:airybiprime(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyaix(arg1::AbstractNumber) tmp = SpecialFunctions.:airyaix(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyaix(arg1::AbstractReal) tmp = SpecialFunctions.:airyaix(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyaiprimex(arg1::AbstractNumber) tmp = SpecialFunctions.:airyaiprimex(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airyaiprimex(arg1::AbstractReal) tmp = SpecialFunctions.:airyaiprimex(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybix(arg1::AbstractNumber) tmp = SpecialFunctions.:airybix(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybix(arg1::AbstractReal) tmp = SpecialFunctions.:airybix(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybiprimex(arg1::AbstractNumber) tmp = SpecialFunctions.:airybiprimex(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:airybiprimex(arg1::AbstractReal) tmp = SpecialFunctions.:airybiprimex(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:besselh(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselh(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselh(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselh(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselh(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselh(number(a), b) like(a, tmp) end function SpecialFunctions.:besselh(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselh(number(a), b) like(a, tmp) end function SpecialFunctions.:besselh(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselh(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselh(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselh(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselh(arg1::AbstractNumber, arg2::AbstractNumber, arg3::AbstractNumber) tmp = SpecialFunctions.:besselh(number(arg1), number(arg2), number(arg3)) like(arg1, tmp) end function SpecialFunctions.:besselh(arg1::AbstractReal, arg2::AbstractReal, arg3::AbstractReal) tmp = SpecialFunctions.:besselh(number(arg1), number(arg2), number(arg3)) like(arg1, tmp) end function SpecialFunctions.:besselhx(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselhx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselhx(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselhx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselhx(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselhx(number(a), b) like(a, tmp) end function SpecialFunctions.:besselhx(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselhx(number(a), b) like(a, tmp) end function SpecialFunctions.:besselhx(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselhx(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselhx(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselhx(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselhx(arg1::AbstractNumber, arg2::AbstractNumber, arg3::AbstractNumber) tmp = SpecialFunctions.:besselhx(number(arg1), number(arg2), number(arg3)) like(arg1, tmp) end function SpecialFunctions.:besselhx(arg1::AbstractReal, arg2::AbstractReal, arg3::AbstractReal) tmp = SpecialFunctions.:besselhx(number(arg1), number(arg2), number(arg3)) like(arg1, tmp) end function SpecialFunctions.:besseli(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besseli(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besseli(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besseli(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besseli(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besseli(number(a), b) like(a, tmp) end function SpecialFunctions.:besseli(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besseli(number(a), b) like(a, tmp) end function SpecialFunctions.:besseli(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besseli(a, number(b)) like(b, tmp) end function SpecialFunctions.:besseli(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besseli(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselix(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselix(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselix(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselix(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselix(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselix(number(a), b) like(a, tmp) end function SpecialFunctions.:besselix(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselix(number(a), b) like(a, tmp) end function SpecialFunctions.:besselix(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselix(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselix(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselix(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselj(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselj(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselj(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselj(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselj(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselj(number(a), b) like(a, tmp) end function SpecialFunctions.:besselj(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselj(number(a), b) like(a, tmp) end function SpecialFunctions.:besselj(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselj(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselj(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselj(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselj0(arg1::AbstractNumber) tmp = SpecialFunctions.:besselj0(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:besselj0(arg1::AbstractReal) tmp = SpecialFunctions.:besselj0(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:besselj1(arg1::AbstractNumber) tmp = SpecialFunctions.:besselj1(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:besselj1(arg1::AbstractReal) tmp = SpecialFunctions.:besselj1(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:besseljx(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besseljx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besseljx(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besseljx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besseljx(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besseljx(number(a), b) like(a, tmp) end function SpecialFunctions.:besseljx(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besseljx(number(a), b) like(a, tmp) end function SpecialFunctions.:besseljx(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besseljx(a, number(b)) like(b, tmp) end function SpecialFunctions.:besseljx(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besseljx(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselk(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselk(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselk(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselk(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselk(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselk(number(a), b) like(a, tmp) end function SpecialFunctions.:besselk(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselk(number(a), b) like(a, tmp) end function SpecialFunctions.:besselk(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselk(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselk(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselk(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselkx(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselkx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselkx(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselkx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselkx(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselkx(number(a), b) like(a, tmp) end function SpecialFunctions.:besselkx(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselkx(number(a), b) like(a, tmp) end function SpecialFunctions.:besselkx(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselkx(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselkx(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselkx(a, number(b)) like(b, tmp) end function SpecialFunctions.:bessely(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:bessely(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:bessely(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:bessely(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:bessely(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:bessely(number(a), b) like(a, tmp) end function SpecialFunctions.:bessely(a::AbstractReal, b::Real) tmp = SpecialFunctions.:bessely(number(a), b) like(a, tmp) end function SpecialFunctions.:bessely(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:bessely(a, number(b)) like(b, tmp) end function SpecialFunctions.:bessely(a::Real, b::AbstractReal) tmp = SpecialFunctions.:bessely(a, number(b)) like(b, tmp) end function SpecialFunctions.:bessely0(arg1::AbstractNumber) tmp = SpecialFunctions.:bessely0(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:bessely0(arg1::AbstractReal) tmp = SpecialFunctions.:bessely0(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:bessely1(arg1::AbstractNumber) tmp = SpecialFunctions.:bessely1(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:bessely1(arg1::AbstractReal) tmp = SpecialFunctions.:bessely1(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:besselyx(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:besselyx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselyx(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:besselyx(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:besselyx(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:besselyx(number(a), b) like(a, tmp) end function SpecialFunctions.:besselyx(a::AbstractReal, b::Real) tmp = SpecialFunctions.:besselyx(number(a), b) like(a, tmp) end function SpecialFunctions.:besselyx(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:besselyx(a, number(b)) like(b, tmp) end function SpecialFunctions.:besselyx(a::Real, b::AbstractReal) tmp = SpecialFunctions.:besselyx(a, number(b)) like(b, tmp) end function SpecialFunctions.:dawson(arg1::AbstractNumber) tmp = SpecialFunctions.:dawson(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:dawson(arg1::AbstractReal) tmp = SpecialFunctions.:dawson(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erf(arg1::AbstractNumber) tmp = SpecialFunctions.:erf(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erf(arg1::AbstractReal) tmp = SpecialFunctions.:erf(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erf(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:erf(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:erf(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:erf(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:erf(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:erf(number(a), b) like(a, tmp) end function SpecialFunctions.:erf(a::AbstractReal, b::Real) tmp = SpecialFunctions.:erf(number(a), b) like(a, tmp) end function SpecialFunctions.:erf(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:erf(a, number(b)) like(b, tmp) end function SpecialFunctions.:erf(a::Real, b::AbstractReal) tmp = SpecialFunctions.:erf(a, number(b)) like(b, tmp) end function SpecialFunctions.:erfc(arg1::AbstractNumber) tmp = SpecialFunctions.:erfc(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfc(arg1::AbstractReal) tmp = SpecialFunctions.:erfc(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfcinv(arg1::AbstractNumber) tmp = SpecialFunctions.:erfcinv(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfcinv(arg1::AbstractReal) tmp = SpecialFunctions.:erfcinv(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfcx(arg1::AbstractNumber) tmp = SpecialFunctions.:erfcx(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfcx(arg1::AbstractReal) tmp = SpecialFunctions.:erfcx(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfi(arg1::AbstractNumber) tmp = SpecialFunctions.:erfi(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfi(arg1::AbstractReal) tmp = SpecialFunctions.:erfi(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfinv(arg1::AbstractNumber) tmp = SpecialFunctions.:erfinv(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:erfinv(arg1::AbstractReal) tmp = SpecialFunctions.:erfinv(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:eta(arg1::AbstractNumber) tmp = SpecialFunctions.:eta(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:eta(arg1::AbstractReal) tmp = SpecialFunctions.:eta(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:digamma(arg1::AbstractNumber) tmp = SpecialFunctions.:digamma(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:digamma(arg1::AbstractReal) tmp = SpecialFunctions.:digamma(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:invdigamma(arg1::AbstractNumber) tmp = SpecialFunctions.:invdigamma(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:invdigamma(arg1::AbstractReal) tmp = SpecialFunctions.:invdigamma(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:polygamma(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:polygamma(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:polygamma(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:polygamma(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:polygamma(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:polygamma(number(a), b) like(a, tmp) end function SpecialFunctions.:polygamma(a::AbstractReal, b::Real) tmp = SpecialFunctions.:polygamma(number(a), b) like(a, tmp) end function SpecialFunctions.:polygamma(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:polygamma(a, number(b)) like(b, tmp) end function SpecialFunctions.:polygamma(a::Real, b::AbstractReal) tmp = SpecialFunctions.:polygamma(a, number(b)) like(b, tmp) end function SpecialFunctions.:trigamma(arg1::AbstractNumber) tmp = SpecialFunctions.:trigamma(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:trigamma(arg1::AbstractReal) tmp = SpecialFunctions.:trigamma(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:hankelh1(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:hankelh1(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh1(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:hankelh1(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh1(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:hankelh1(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh1(a::AbstractReal, b::Real) tmp = SpecialFunctions.:hankelh1(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh1(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:hankelh1(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh1(a::Real, b::AbstractReal) tmp = SpecialFunctions.:hankelh1(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh1x(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:hankelh1x(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh1x(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:hankelh1x(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh1x(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:hankelh1x(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh1x(a::AbstractReal, b::Real) tmp = SpecialFunctions.:hankelh1x(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh1x(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:hankelh1x(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh1x(a::Real, b::AbstractReal) tmp = SpecialFunctions.:hankelh1x(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh2(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:hankelh2(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh2(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:hankelh2(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh2(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:hankelh2(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh2(a::AbstractReal, b::Real) tmp = SpecialFunctions.:hankelh2(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh2(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:hankelh2(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh2(a::Real, b::AbstractReal) tmp = SpecialFunctions.:hankelh2(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh2x(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:hankelh2x(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh2x(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:hankelh2x(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:hankelh2x(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:hankelh2x(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh2x(a::AbstractReal, b::Real) tmp = SpecialFunctions.:hankelh2x(number(a), b) like(a, tmp) end function SpecialFunctions.:hankelh2x(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:hankelh2x(a, number(b)) like(b, tmp) end function SpecialFunctions.:hankelh2x(a::Real, b::AbstractReal) tmp = SpecialFunctions.:hankelh2x(a, number(b)) like(b, tmp) end function SpecialFunctions.:zeta(arg1::AbstractNumber) tmp = SpecialFunctions.:zeta(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:zeta(arg1::AbstractReal) tmp = SpecialFunctions.:zeta(number(arg1)) like(arg1, tmp) end function SpecialFunctions.:zeta(arg1::AbstractNumber, arg2::AbstractNumber) tmp = SpecialFunctions.:zeta(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:zeta(arg1::AbstractReal, arg2::AbstractReal) tmp = SpecialFunctions.:zeta(number(arg1), number(arg2)) like(arg1, tmp) end function SpecialFunctions.:zeta(a::AbstractNumber, b::Number) tmp = SpecialFunctions.:zeta(number(a), b) like(a, tmp) end function SpecialFunctions.:zeta(a::AbstractReal, b::Real) tmp = SpecialFunctions.:zeta(number(a), b) like(a, tmp) end function SpecialFunctions.:zeta(a::Number, b::AbstractNumber) tmp = SpecialFunctions.:zeta(a, number(b)) like(b, tmp) end function SpecialFunctions.:zeta(a::Real, b::AbstractReal) tmp = SpecialFunctions.:zeta(a, number(b)) like(b, tmp) end
AbstractNumbers
https://github.com/SimonDanisch/AbstractNumbers.jl.git