Skip to content

Commit

Permalink
SegmentTools cleanup and optimization
Browse files Browse the repository at this point in the history
- speed up data cropping
- speed up of network evaluation
- uptimized visualization for segmentations
- better network reporting
  • Loading branch information
mfroeling committed Aug 9, 2024
1 parent 90bf1fa commit 44c0e54
Show file tree
Hide file tree
Showing 7 changed files with 7,573 additions and 1,839 deletions.
31 changes: 28 additions & 3 deletions QMRITools/Kernel/ElastixTools.wl
Original file line number Diff line number Diff line change
Expand Up @@ -594,9 +594,9 @@ ConcatenateTransformFiles[files_, outDir_] := Block[{len, filesi, tfile, f, p},
(
f = filesi[[#]];
tfile = If[# == 1, "NoInitialTransform", outDir <> $PathnameSeparator <> "FinalTransform." <> ToString[# - 2] <> ".txt"];
p = Position[Boole[StringContainsQ[#, "InitialTransformParametersFileName"] & /@ f], 1][[1, 1]];
p = Position[Boole[StringContainsQ[#, "InitialTransformParameterFileName"] & /@ f], 1][[1, 1]];

f[[p]] = "(InitialTransformParametersFileName \"" <> tfile <> "\")";
f[[p]] = "(InitialTransformParameterFileName \"" <> tfile <> "\")";
Export[outDir <> $PathnameSeparator <> "FinalTransform." <> ToString[# - 1] <> ".txt", f];
) & /@ len;
]
Expand Down Expand Up @@ -1386,7 +1386,7 @@ RegisterDiffusionData[
(*get vol folders and anat transform files*)
volDirs = FileNames["vol*", tempDir, 1];
tFilesA = FileNames["TransformParameters*", tempDira];

(*create Final Transform files*)
(
tFilesD = FileNames["TransformParameters*", #];
Expand Down Expand Up @@ -1466,6 +1466,31 @@ RegisterDiffusionDataSplit[
StichData[datal, datar]
];

RegisterDiffusionDataSplit[
{data_, mask_, vox: {_?NumberQ, _?NumberQ, _?NumberQ}},
{dataa_, voxa: {_?NumberQ, _?NumberQ, _?NumberQ}},
opts : OptionsPattern[]] := Block[
{datal, datar, dataal, dataar, maskl, maskr, cut1,cut2},

(*find cuts*)
{datal, datar, cut1} = CutData[data];
{dataal, dataar, cut2} = CutData[dataa];

(*align cuts*)
{cut1,cut2}=Round[First@Nearest[{cut1 Last@vox, cut2 Last@voxa}, Round[Last@Dimensions[data]/2] Last@vox] / {Last@vox, Last@voxa}];
(*{cut1,cut2}=Round[Mean[{cut1 vox[[2]], cut2 voxa[[2]]}]/{vox[[2]],voxa[[2]]}];*)

(*cut with the aligned cuts*)
{datal, datar, cut1} = CutData[data,cut1];
{maskl, maskr, cut1} = CutData[mask,cut1];
{dataal, dataar, cut2} = CutData[dataa,cut2];

datal = RegisterDiffusionData[{datal, maskl, vox}, {dataal, voxa}, opts][[2]];
datar = RegisterDiffusionData[{datar, maskr, vox}, {dataar, voxa}, opts][[2]];

StichData[datal, datar]
];

RegisterDiffusionDataSplit[
{data_, mask_, vox: {_?NumberQ, _?NumberQ, _?NumberQ}},
{dataa_, maska_, voxa: {_?NumberQ, _?NumberQ, _?NumberQ}},
Expand Down
77 changes: 38 additions & 39 deletions QMRITools/Kernel/GeneralTools.wl
Original file line number Diff line number Diff line change
Expand Up @@ -915,14 +915,21 @@ Options[FindCrop] = {CropPadding->5}

SyntaxInformation[FindCrop] = {"ArgumentsPattern" -> {_, OptionsPattern[]}};

FindCrop[dat_, OptionsPattern[]] := Block[{unit, crp, p, dim, add, data},
FindCrop[dat_, OptionsPattern[]] := Block[{add, data, dim, d1, d2, unit, crp},
add = {-1, 1} OptionValue[CropPadding];

data = Unitize@Switch[ArrayDepth[dat],
3, dat,
4, dat[[All, 1]],
_, Return[$Failed]
];
dim = Dimensions[data];

data = If[ArrayDepth[dat]===4, dat[[All,1]], dat];
d1 = Unitize@Total[data];
d2 = Unitize@Total[data, {2}];
unit = Unitize[{Total[d2, {2}], Total[d1, {2}], Total[d1]}];

add= OptionValue[CropPadding];
unit = Unitize[Total[Total[data, {#[[1]]}], {#[[2]]}] & /@ {{2, 2}, {1, 2}, {1, 1}}];
dim = Dimensions[data];
crp = (p = Position[#, 1]; Flatten@{First[p] - add, Last[p] + add}) & /@ unit;
crp = MinMax[DeleteCases[# Range[Length[#]], 0]] + add & /@ unit;
Flatten[MapThread[Clip[#1, {1, #2}] &, {crp, dim}]]
]

Expand All @@ -935,18 +942,10 @@ Options[AutoCropData] = {CropPadding->5}

SyntaxInformation[AutoCropData] = {"ArgumentsPattern" -> {_, OptionsPattern[]}}

AutoCropData[data_, opts:OptionsPattern[]] := Module[{datac,crp, add},
add= OptionValue[CropPadding];
datac = Switch[ArrayDepth[data],
3, data,
4, data[[All, 1]],
_, Return[$Failed]
];

crp = FindCrop[datac, opts];

{ApplyCrop[data,crp],crp}
]
AutoCropData[data_, opts:OptionsPattern[]] := Module[{crp},
crp = FindCrop[data, opts];
{ApplyCrop[data,crp], crp}
]


(* ::Subsubsection::Closed:: *)
Expand All @@ -957,7 +956,7 @@ SyntaxInformation[ReverseCrop] = {"ArgumentsPattern" -> {_, _, _, _.}};

ReverseCrop[data_, dim_, crop_] := ReverseCrop[data, dim, crop, {0, 0}]

ReverseCrop[data_, dimI_, crop_, {v1_, v2_}] := Module[{datac, pad, dim},
ReverseCrop[data_, dimI_, crop_, {v1_, v2_}] := Module[{datac, pad, dim, p},

dim = If[Length@Dimensions@data===4, dimI[[{1,3,4}]], dimI];

Expand All @@ -968,13 +967,14 @@ ReverseCrop[data_, dimI_, crop_, {v1_, v2_}] := Module[{datac, pad, dim},
Floor[(v1/v2) Partition[Abs[{1, dim[[1]], 1, dim[[2]], 1, dim[[3]]} - crop], 2]]
];

p = If[IntegerQ[Min@data], 0, 0.];
datac = Switch[ArrayDepth[data],
3, ArrayPad[data, pad, 0.],
4, ArrayPad[data, Insert[pad, {0, 0}, 2], 0.],
3, ArrayPad[data, pad, p],
4, ArrayPad[data, Insert[pad, {0, 0}, 2], p],
_, Return[$Failed, Module]
];

ToPackedArray@N@datac
ToPackedArray@datac
]


Expand All @@ -986,31 +986,30 @@ Options[ApplyCrop]={CropAlways->False}

SyntaxInformation[ApplyCrop] = {"ArgumentsPattern" -> {_, _, _.,OptionsPattern[]}};

ApplyCrop[data_, crop_, opts:OptionsPattern[]] := ApplyCrop[data, crop, {{1,1,1}, {1,1,1}}, opts]
ApplyCrop[data_, crop_?VectorQ, opts:OptionsPattern[]] := ApplyCrop[data, crop, {{1,1,1}, {1,1,1}}, opts]

ApplyCrop[data_, crop_ , {v1_,v2_}, opts:OptionsPattern[]] := Module[{z1, z2, x1, x2, y1, y2, dim, out},
ApplyCrop[data_, crop_?VectorQ , {v1_,v2_}, opts:OptionsPattern[]] := Module[{z1, z2, x1, x2, y1, y2, dim, out},

dim = Dimensions[data];
dim = If[Length[dim]==4,dim[[{1,3,4}]],dim];
out = ToPackedArray@data;
dim = Dimensions[out];
dim = If[Length[dim]==4, dim[[{1,3,4}]], dim];

(*get crops coors*)
{z1, z2, x1, x2, y1, y2} = Round[crop Flatten[{#, #} & /@ (v1/v2)]];

If[OptionValue[CropAlways],
{z1,z2}=Clip[{z1,z2},{1,dim[[1]]}];
{x1,x2}=Clip[{x1,x2},{1,dim[[2]]}];
{y1,y2}=Clip[{y1,y2},{1,dim[[3]]}];
{z1,z2} = Clip[{z1, z2},{1, dim[[1]]}];
{x1,x2} = Clip[{x1, x2},{1, dim[[2]]}];
{y1,y2} = Clip[{y1, y2},{1, dim[[3]]}];
,
If[z1<1||z2>dim[[1]]||x1<1||x2>dim[[2]]||y1<1||y2>dim[[3]],Return[Message[ApplyCrop::dim]]]
If[z1<1||z2>dim[[1]]||x1<1||x2>dim[[2]]||y1<1||y2>dim[[3]], Return[Message[ApplyCrop::dim]]]
];

out = Switch[ArrayDepth[data],
4, data[[z1 ;; z2, All, x1 ;; x2, y1 ;; y2]],
3, data[[z1 ;; z2, x1 ;; x2, y1 ;; y2]],
2, data[[x1 ;; x2, y1 ;; y2]]
];

ToPackedArray@N@out
ToPackedArray@Switch[ArrayDepth[out],
4, out[[z1 ;; z2, All, x1 ;; x2, y1 ;; y2]],
3, out[[z1 ;; z2, x1 ;; x2, y1 ;; y2]],
2, out[[x1 ;; x2, y1 ;; y2]]
]
]


Expand Down Expand Up @@ -1488,9 +1487,9 @@ SyntaxInformation[LLeastSquares] = {"ArgumentsPattern" -> {_, _}};

LLeastSquares[ai_, y_]:=Block[{a},
a = If[Length[y] == Length[ai], ai, Transpose[ai]];
If[RealQ[Total[Flatten[y]]],
If[RealValuedNumberQ[Total[Flatten[y]]],
LLeastSquaresC[a, y],
If[RealQ[Total[Flatten[a]]],
If[RealValuedNumberQ[Total[Flatten[a]]],
LLeastSquaresCC[a, y],
LLeastSquaresCCC[a, y]
]
Expand Down
2 changes: 1 addition & 1 deletion QMRITools/Kernel/MaskingTools.wl
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ Mask[dat_?ArrayQ, tr_?VectorQ, opts:OptionsPattern[]]:= Block[{mask, tresh, data
];

(*smooth the mask if needed*)
Normal@If[OptionValue[MaskSmoothing], SmoothMask[mask, FilterRules[{opts, Options[Mask]}, Options[SmoothMask]]], mask]
Round@Normal@If[OptionValue[MaskSmoothing], SmoothMask[mask, FilterRules[{opts, Options[Mask]}, Options[SmoothMask]]], mask]
]


Expand Down
32 changes: 20 additions & 12 deletions QMRITools/Kernel/PlottingTools.wl
Original file line number Diff line number Diff line change
Expand Up @@ -1827,22 +1827,23 @@ PlotContour[dati_, opts:OptionsPattern[]]:=PlotContour[dati, {1,1,1}, opts]

PlotContour[dati_, vox_, opts:OptionsPattern[]] := Block[{
data, smooth, color, opac, dim , pad, col, style, crp,
ran, coldat, colfunc, scale, range, reso
ran, coldat, colfunc, scale, range, reso, cdim, cfunc
},

If[ArrayDepth[dati]===4,
SeedRandom[12345];
Show[PlotContour[#[[1]], vox, ContourColor->#[[2]], opts]&/@ Transpose[{Transpose[dati], RandomColor[Length@First@dati]}]]
,
smooth = OptionValue[ContourSmoothRadius];
If[smooth === None, smooth = 0];
reso = OptionValue[ContourResolution];
scale = OptionValue[ContourScaling];
color = OptionValue[ContourColor];
opac = OptionValue[ContourOpacity];

If[N[Max[dati]] === 0.,
Graphics3D[],

dim = Dimensions@dati;
pad = 2 (smooth + 1);

Expand All @@ -1855,28 +1856,33 @@ PlotContour[dati_, vox_, opts:OptionsPattern[]] := Block[{
col = If[ColorQ[color], color, If[color==="Random", RandomColor[], GrayLevel[1.]]];
style = Directive[{Opacity[opac], col, Specularity[Lighter@Lighter@col, 5]}];

colfunc = If[! ArrayQ[color],
colfunc = If[!ArrayQ[color],
Automatic,
ran = OptionValue[ContourColorRange];
cfunc = OptionValue[ColorFunction];
ran = If[ran === Automatic,
Quantile[DeleteCases[N@Flatten[color], 0.], {0.02, 0.98}],
ran];
coldat = Rescale[color, ran];
coldat = Clip[Rescale[color, ran], {0, 1}];
cdim = Dimensions[coldat];
style = Directive[{Opacity[opac],Specularity[Red,0]}];
Function[{z, y, x},
ColorData[OptionValue[ColorFunction]][
coldat[[Clip[Round[x], {1, dim[[3]]}],
Clip[Round[y], {1, dim[[2]]}], Clip[Round[z], {1, dim[[1]]}]]]]
ColorData[cfunc][coldat[[
Clip[Round[x/vox[[1]] + 0.5], {1, cdim[[1]]}],
Clip[Round[y/vox[[2]] + 0.5], {1, cdim[[2]]}],
Clip[Round[z/vox[[3]] + 0.5], {1, cdim[[3]]}]
]]]
]
];

reso = Reverse@Round[(vox Dimensions[data]) / Switch[reso, Automatic, Reverse[vox], _, reso]];
reso = Reverse@Round[(vox Dimensions[data]) / Switch[reso, Automatic, 1.5 vox, _, reso]];
scale = Switch[scale, "World", Reverse[vox], _, {1,1,1}];

range = Reverse[Partition[crp, 2]] + {{-pad - 1, pad}, {-pad - 1, pad}, {-pad - 1, pad}};
dim = Reverse[dim];

ListContourPlot3D[data,
Contours -> {0.4},
Contours -> {0.7},
Mesh -> False, BoundaryStyle -> None, Axes -> True,
SphericalRegion -> True,
ColorFunctionScaling -> False, ColorFunction -> colfunc,
Expand Down Expand Up @@ -2299,14 +2305,13 @@ PlotSequence[(*{seq_,hw_,te_}*)inp_, t_] := DynamicModule[{

SyntaxInformation[ColorFAPlot] = {"ArgumentsPattern" -> {_}};

ColorFAPlot[tens_] := Block[{FA, eig, eigv, mid, eigFA, mask, all},
ColorFAPlot[tens_] := DynamicModule[{FA, eig, eigv, mid, eigFA, mask},
mask = Mask[Mean@tens[[1;;3]], 0.00001, MaskSmoothing->False];

{eig, eigv} = EigensysCalc[tens, PerformanceGoal -> "Quality"];

FA = Clip[2 FACalc[eig], {0,1}];
eigv = mask Abs[eigv];
all = {eigv, FA eigv};

Manipulate[
im = Image[all[[i, j, All, All, sel, {3,2,1}]], ColorSpace -> "RGB", ImageSize->size],
Expand All @@ -2315,7 +2320,10 @@ ColorFAPlot[tens_] := Block[{FA, eig, eigv, mid, eigFA, mask, all},
{{i, 2, "method"}, {1 -> "raw", 2 -> "FA"}},
{{sel, 1(*, 2, 3*), "eigenvectors"}, {1 -> "first", 2 -> "second", 3 -> "third"}, ControlType -> SetterBar},
{{size, 400, "image size"}, {200, 300, 400, 600, 1000}},
Button["save image", SaveImage[im], Method -> "Queued"]
Button["save image", SaveImage[im], Method -> "Queued"],

{all, ControlType -> None},
Initialization :> (all = {eigv, FA eigv}; j = Round[Length[all[[1]]]/2])
]
]

Expand Down
Loading

0 comments on commit 44c0e54

Please sign in to comment.