-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeasure_cac_script.jl
2777 lines (2289 loc) · 93.3 KB
/
measure_cac_script.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v0.19.40
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 7879e86f-e900-45de-a7ba-5e768760d1b1
using DataFrames: DataFrame, rename!, nrow
# ╔═╡ c089c448-09c1-459c-8c88-07b021e1b6f5
using CSV: write
# ╔═╡ 7ede2cbc-c82a-40c4-86be-ac7c61c14f03
using StaticArrays: SVector
# ╔═╡ 8d24da97-a7ab-4fb8-b37b-c48c6c3d3f70
using IterTools: product
# ╔═╡ b8c49cef-c730-464b-b17c-005afdf0fdbe
using LinearAlgebra: normalize, dot
# ╔═╡ aa1f5386-f4f3-4bf6-a19d-41814fdd19f9
using CairoMakie: Figure, Axis, heatmap!, heatmap, scatter!, axislegend, hist!
# ╔═╡ 0cd17411-918f-4f02-b4a9-ffaa6de64bc8
using DICOM: dcmdir_parse
# ╔═╡ a7e5315b-adee-4168-a321-755a49016433
using PlutoUI: TableOfContents, Slider, TextField, confirm, combine
# ╔═╡ c4b10ab5-ef81-4617-be00-6c0e836dcdd8
using StatsBase: countmap, quantile
# ╔═╡ d39fe463-c2b7-4297-918a-490a31b4329e
using ImageMorphology: component_centroids, label_components, component_boxes, dilate
# ╔═╡ 5102b829-2ed0-430b-a942-72d96e21c197
using Statistics: mean, norm, std
# ╔═╡ bd259589-0cc3-40e2-a8e4-c3af710bf65a
using CalciumScoring: score, VolumeFraction, Agatston
# ╔═╡ 41d34cdb-af4c-4c59-9ae8-e020b72b6964
using ImageCore: channelview
# ╔═╡ 29fd1197-53c7-4660-849e-f1e684acd8d1
using DataInterpolations: QuadraticInterpolation
# ╔═╡ 10872202-4a25-4a8b-ab1d-35c4ece5a2a2
using OrderedCollections: OrderedDict
# ╔═╡ beda1edb-4fea-40d1-8bbc-c49953952698
md"""
# Set Up
"""
# ╔═╡ a214f633-3699-4fe6-bca4-02de420d3c1d
md"""
## Environment & Imports
"""
# ╔═╡ 4aff31dc-7fd7-4d89-9a31-26cd1133eeb5
TableOfContents()
# ╔═╡ f97c1ff0-36ae-4fcf-b7db-065c90ea13cf
md"""
## Helper Functions
"""
# ╔═╡ ae78dad9-4246-4c8b-87d3-d0ddc6f9316d
md"""
#### DICOM Utils
"""
# ╔═╡ a4aec909-8214-4615-8782-f4968c532742
function load_dcm_array(dcm_data)
return array = cat(
[dcm_data[i][(0x7fe0, 0x0010)] for i in eachindex(dcm_data)]...; dims=3
)
end
# ╔═╡ b1ad4ce5-c28d-48bb-b249-3760a6acbaec
function get_pixel_size(header)
head = copy(header)
pixel_size =
try
pixel_size = (head[(0x0028, 0x0030)])
push!(pixel_size, head[(0x0018, 0x0050)])
catch
FOV = (head[(0x0018, 0x1100)])
matrix_size = head[(0x0028, 0x0010)]
pixel_size = FOV / matrix_size
push!(pixel_size, head[(0x0018, 0x0050)])
end
return pixel_size
end
# ╔═╡ a95486b1-8cb3-4f03-b761-595bc24bd70c
md"""
#### Active Contours
"""
# ╔═╡ 5419e1ba-1709-4c4b-8a3d-edaef052cbcd
function initial_level_set(shape::Tuple{Int64, Int64})
x₀ = reshape(collect(0:shape[begin]-1), shape[begin], 1)
y₀ = reshape(collect(0:shape[begin+1]-1), 1, shape[begin+1])
𝚽₀ = @. sin(pi / 5 * x₀) * sin(pi / 5 * y₀)
end
# ╔═╡ 42c07efe-f575-40a6-a65b-57b521061c5e
function initial_level_set(shape::Tuple{Int64, Int64, Int64})
x₀ = reshape(collect(0:shape[begin]-1), shape[begin], 1, 1)
y₀ = reshape(collect(0:shape[begin+1]-1), 1, shape[begin+1], 1)
z₀ = reshape(collect(0:shape[begin+2]-1), 1, 1, shape[begin+2])
𝚽₀ = @. sin(pi / 5 * x₀) * sin(pi / 5 * y₀) * sin(pi / 5 * z₀)
end
# ╔═╡ b7d72bb0-4ed8-4d78-bf47-4f333a2daee7
function calculate_averages(
img::AbstractArray{T, N},
H𝚽::AbstractArray{S, N},
area::Int64, ∫u₀::Float64) where {T<:Real, S<:Bool, N}
∫u₀H𝚽 = 0
∫H𝚽 = 0
@inbounds for i in eachindex(img)
if H𝚽[i]
∫u₀H𝚽 += img[i]
∫H𝚽 += 1
end
end
∫H𝚽ⁱ = area - ∫H𝚽
∫u₀H𝚽ⁱ = ∫u₀ - ∫u₀H𝚽
c₁ = ∫u₀H𝚽 / max(1, ∫H𝚽)
c₂ = ∫u₀H𝚽ⁱ / max(1, ∫H𝚽ⁱ)
return c₁, c₂
end
# ╔═╡ e5477a2e-9f40-41f3-888e-0c301302de64
function chan_vese(img;
μ::Real=0.25,
λ₁::Real=1.0,
λ₂::Real=1.0,
tol::Real=1e-3,
max_iter::Int=500,
Δt::Real=0.5,
normalize::Bool=false,
init_level_set=initial_level_set(size(img)))
# Signs used in the codes and comments mainly follow paper[3] in the References.
axes(img) == axes(init_level_set) || throw(ArgumentError("axes of input image and init_level_set should be equal. Instead they are $(axes(img)) and $(axes(init_level_set))."))
img = Float64.(channelview(img))
N = ndims(img)
iter = 0
h = 1.0
del = tol + 1
if normalize
img .= img .- minimum(img)
if maximum(img) != 0
img .= img ./ maximum(img)
end
end
# Precalculation of some constants which helps simplify some integration
area = length(img) # area = ∫H𝚽 + ∫H𝚽ⁱ
∫u₀ = sum(img) # ∫u₀ = ∫u₀H𝚽 + ∫u₀H𝚽ⁱ
# Initialize the level set
𝚽ⁿ = init_level_set
# Preallocation and initializtion
H𝚽 = trues(size(img)...)
𝚽ⁿ⁺¹ = similar(𝚽ⁿ)
Δ = ntuple(d -> CartesianIndex(ntuple(i -> i == d ? 1 : 0, N)), N)
idx_first = first(CartesianIndices(𝚽ⁿ))
idx_last = last(CartesianIndices(𝚽ⁿ))
while (del > tol) & (iter < max_iter)
ϵ = 1e-8
diff = 0
# Calculate the average intensities
@. H𝚽 = 𝚽ⁿ > 0 # Heaviside function
c₁, c₂ = calculate_averages(img, H𝚽, area, ∫u₀) # Compute c₁(𝚽ⁿ), c₂(𝚽ⁿ)
# Calculate the variation of level set 𝚽ⁿ
@inbounds @simd for idx in CartesianIndices(𝚽ⁿ)
𝚽₀ = 𝚽ⁿ[idx] # 𝚽ⁿ(x, y)
u₀ = img[idx] # u₀(x, y)
𝚽₊ = broadcast(i->𝚽ⁿ[i], ntuple(d -> idx[d] != idx_last[d] ? idx + Δ[d] : idx, N))
𝚽₋ = broadcast(i->𝚽ⁿ[i], ntuple(d -> idx[d] != idx_first[d] ? idx - Δ[d] : idx, N))
# Solve the PDE of equation 9 in paper[3]
center_diff = ntuple(d -> (𝚽₊[d] - 𝚽₋[d])^2 / 4., N)
sum_center_diff = sum(center_diff)
C₊ = ntuple(d -> 1. / sqrt(ϵ + (𝚽₊[d] - 𝚽₀)^2 + sum_center_diff - center_diff[d]), N)
C₋ = ntuple(d -> 1. / sqrt(ϵ + (𝚽₋[d] - 𝚽₀)^2 + sum_center_diff - center_diff[d]), N)
K = sum(𝚽₊ .* C₊) + sum(𝚽₋ .* C₋)
δₕ = h / (h^2 + 𝚽₀^2) # Regularised Dirac function
difference_from_average = - λ₁ * (u₀ - c₁) ^ 2 + λ₂ * (u₀ - c₂) ^ 2
𝚽ⁿ⁺¹[idx] = 𝚽 = (𝚽₀ + Δt * δₕ * (μ * K + difference_from_average)) / (1. + μ * Δt * δₕ * (sum(C₊) + sum(C₋)))
diff += (𝚽 - 𝚽₀)^2
end
del = sqrt(diff / area)
# Reinitializing the level set is not strictly necessary, so this part of code is commented.
# If you wants to use the reinitialization, just uncommented codes following.
# Function `reinitialize!` is already prepared.
# reinitialize!(𝚽ⁿ⁺¹, 𝚽ⁿ, Δt, h) # Reinitialize 𝚽 to be the signed distance function to its zero level set
𝚽ⁿ .= 𝚽ⁿ⁺¹
iter += 1
end
return 𝚽ⁿ .> 0
end
# ╔═╡ 26ff0532-dbf6-485d-a83f-199d0f70b0e6
md"""
#### Masks
"""
# ╔═╡ 0a61db85-1f29-4b90-a4da-651f15b0f38b
function create_mask(array, mask)
@assert size(array) == size(mask)
idxs = findall(x -> x == true, mask)
overlayed_mask = zeros(size(array))
for idx in idxs
overlayed_mask[idx] = array[idx]
end
return overlayed_mask
end
# ╔═╡ aae0aaec-8268-4765-a451-0bceb31dd6e2
function calculate_thresholds(kV, mA)
if kV == 80
mA_arr = [10, 20, 40, 100, 150, 250]
threshold_low_arr = [100, 80, 50, 20, 10, 0]
threshold_high_arr = [300, 255, 180, 90, 65, 40]
elseif kV == 100
mA_arr = [10, 20, 40, 100, 150, 250]
threshold_low_arr = [70, 55, 35, 35, 29, 25]
threshold_high_arr = [230, 150, 90, 88, 83, 80]
elseif kV == 120
mA_arr = [10, 15, 20, 25, 30, 40, 50, 100, 150, 250]
threshold_low_arr = [40, 40, 39, 39, 39, 39, 39, 35, 23, 22]
threshold_high_arr = [150, 110, 105, 100, 100, 95, 90, 90, 88, 85]
end
threshold_low_interp = QuadraticInterpolation(threshold_low_arr, mA_arr; extrapolate = true)
threshold_high_interp = QuadraticInterpolation(threshold_high_arr, mA_arr; extrapolate = true)
threshold_low = threshold_low_interp(mA)
threshold_high = threshold_high_interp(mA)
return threshold_low, threshold_high
end
# ╔═╡ 172d043b-c600-43e6-a75d-524bc9dd4955
function threshold_low_high(dcm_arr, kV, mA)
threshold_low, threshold_high = calculate_thresholds(kV, mA)
thresholded_mask_low = dcm_arr .> threshold_low
thresholded_mask_high = dcm_arr .< threshold_high
masked_thresholded = thresholded_mask_high .& thresholded_mask_low
return masked_thresholded
end
# ╔═╡ 18e0ba73-e0f5-42b5-a915-d9287bd9a006
md"""
#### Orthanc Tools
"""
# ╔═╡ bf3d544f-9ab8-430a-b7cb-5da5c7381d52
import HTTP
# ╔═╡ 2861ed2a-adfe-4375-a2cb-0d090f8f1e02
import JSON
# ╔═╡ 89354634-0bec-4d40-a71a-d48f3d9727a1
function get_all_studies(ip_address::String="localhost"; show_warnings=false)
url_studies = HTTP.URI(scheme="http", host=ip_address, port="8042", path="/studies")
studies = JSON.parse(String(HTTP.get(url_studies).body))
studies_dict = OrderedDict{String,Vector}()
for study in studies
s = JSON.parse(String(HTTP.get(string(url_studies, "/", study)).body))
try
accession_num = s["MainDicomTags"]["AccessionNumber"]
if !haskey(studies_dict, accession_num)
push!(studies_dict, accession_num => [study])
else
push!(studies_dict[accession_num], study)
end
catch
if show_warnings
@warn "No accession number for $study"
end
end
end
return studies_dict
end
# ╔═╡ b139733c-638e-40e5-877e-5b2033838f18
function get_all_series(
studies_dict::OrderedDict,
accession_num::String,
ip_address::String="localhost")
url_study = HTTP.URI(scheme="http", host=ip_address, port="8042", path="/studies/$(studies_dict[accession_num]...)")
series = JSON.parse(String(HTTP.get(url_study).body))
series_dict = OrderedDict{String,Vector}()
for ser in series["Series"]
url_series = HTTP.URI(
scheme="http", host=ip_address, port="8042", path=string("/series/", ser)
)
s = JSON.parse(String(HTTP.get(url_series).body))
try
series_num = s["MainDicomTags"]["SeriesNumber"]
if !haskey(series_dict, series_num)
push!(series_dict, series_num => [ser])
else
push!(series_dict[series_num], ser)
end
catch
@warn "No series number for $ser"
end
end
return series_dict
end
# ╔═╡ a75ef71d-c5de-4614-bb76-09355919d783
function get_all_instances(
series_dict::OrderedDict,
series_num::String,
ip_address::String="localhost")
url = HTTP.URI(scheme="http", host=ip_address, port="8042")
instances_dict = OrderedDict{String,Vector}()
for ser in series_dict[series_num]
url_series = HTTP.URI(
scheme="http", host=ip_address, port="8042", path=string("/series/", ser)
)
series = JSON.parse(String(HTTP.get(url_series).body))
instances = series["Instances"]
if !haskey(instances_dict, series_num)
push!(instances_dict, series_num => [instances])
else
push!(instances_dict[series_num], instances)
end
end
return instances_dict
end
# ╔═╡ 08774908-cb99-4673-8470-7881301da059
function download_instances(
instances_dict::OrderedDict,
instance_num::Number,
output_directory::String,
ip_address::String="localhost")
for (key, value) in instances_dict
for i in value[instance_num]
url_instance = string("http://", ip_address, ":8042", string("/instances/", i))
instance = JSON.parse(String(HTTP.get(url_instance).body))
idx = instance["IndexInSeries"]
download(string(url_instance, "/", "file"), joinpath(output_directory, "$(idx).dcm"))
end
end
@info "Files located at $(output_directory)"
end
# ╔═╡ 69c5661c-77c0-4b6b-b0bc-3cf1512b7c60
function process_instances(
instances_dicts, series_num_vec, output_dir, instance_number, ip_address
)
if !isdir(output_dir)
mkpath(output_dir)
end
output_paths = String[]
for (idx, dict) in enumerate(instances_dicts)
_series = collect(keys(dict))[1]
path = joinpath(output_dir, string(series_num_vec[idx]))
if !isdir(path)
mkpath(path)
end
download_instances(instances_dicts[idx], instance_number, path, ip_address)
output_path = joinpath(output_dir, string(_series))
push!(output_paths, output_path)
end
return output_paths
end
# ╔═╡ da41d9b3-e124-4ef8-81e0-d3e5eea52337
md"""
#### Mask Heart Function
"""
# ╔═╡ 17f9ba72-aa80-4ff5-9de2-83512b6c49ce
function erode_mask(img, num_erosions)
new_img = img
i = 0
while i < num_erosions
new_img = erode(new_img)
i += 1
end
return new_img
end
# ╔═╡ 7b84a208-0a59-4aeb-9506-df5eff303305
function create_circle_mask(img, centroids, radius)
# initialize mask with all zeros
mask = zeros(size(img))
# define the center of the circle
x0, y0 = centroids[1], centroids[2]
# set all pixels inside the circle to 1 and all pixels outside the circle to 0
for x in axes(img, 1), y in axes(img, 2)
if ((x - x0)^2 + (y - y0)^2) <= radius^2
mask[x, y] = 1
else
mask[x, y] = 0
end
end
return Bool.(mask)
end
# ╔═╡ cdb712cf-12ee-4e9d-9d04-16f4af14bbd8
function centroids_from_mask(mask)
cc_labels = label_components(mask)
largest_connected_component, _ = sort(collect(pairs(countmap(cc_labels[cc_labels .!= 0]))), by=x->x[2], rev=true)
largest_connected_indices = findall(cc_labels .== largest_connected_component[1])
new_mask = zeros(size(mask))
for i in largest_connected_indices
new_mask[i] = 1
end
centroids = Int.(round.(component_centroids(label_components(new_mask))[end]))
end
# ╔═╡ 3f695cba-2572-4a50-b76a-80fec1056692
function create_initial_level_set(dcm_arr)
half_x, half_y = size(dcm_arr, 1) ÷ 2, size(dcm_arr, 2) ÷ 2
init_circle = create_circle_mask(dcm_arr[:, :, 3], (half_x, half_y), 140)
init_mask = BitArray(undef, size(dcm_arr))
for z in axes(dcm_arr, 3)
init_mask[:, :, z] = init_circle
end
init_mask = init_mask .* initial_level_set(size(init_mask))
return init_mask
end
# ╔═╡ c33aaaa0-6a87-41b4-86ed-669016382b6e
md"""
#### Inserts
"""
# ╔═╡ c9648ed4-44a2-41c0-b019-e8d68e2a7a6a
function get_insert_centers(dcm, threshold)
dcm_slice_thresh = dcm .> threshold
# Use connected component labeling to identify and label all connected components
cc_labels = label_components(dcm_slice_thresh)
# Use the countmap function to count the number of occurrences of each value in the array, excluding 0
counts = countmap(cc_labels[cc_labels .!= 0])
# Find the value with the most occurrences
most_common_value_a, most_common_value_b = sort(collect(pairs(counts)), by=x->x[2], rev=true)
# Find the indices of the most common value in the original array
most_common_indices_a = findall(cc_labels .== most_common_value_a[1])
# Create boolean array from new cartesian indices
bool_arr_a = zeros(size(dcm_slice_thresh))
for i in most_common_indices_a
bool_arr_a[i] = 1
end
centroids_a = Int.(round.(component_centroids(label_components(bool_arr_a))[end]))
box_a = component_boxes(label_components(bool_arr_a))
# Find the indices of the most common value in the original array
most_common_indices_b = findall(cc_labels .== most_common_value_b[1])
# Create boolean array from new cartesian indices
bool_arr_b = zeros(size(dcm_slice_thresh))
for i in most_common_indices_b
bool_arr_b[i] = 1
end
centroids_b = Int.(round.(component_centroids(label_components(bool_arr_b))[end]))
# centers_a, centers_b = [centroids_a..., z], [centroids_b..., z]
centers_a, centers_b = centroids_a, centroids_b
return centers_a, centers_b
end
# ╔═╡ e62f58f7-141f-4c1a-94e0-561d95eec28b
# Modify the in_cylinder function to accept Static Vectors
function _in_cylinder(pt::SVector{3, Int}, pt1::SVector{3, Float64}, pt2::SVector{3, Float64}, radius)
v = pt2 - pt1
w = pt - pt1
# Compute the dot product
c1 = dot(w, v)
if c1 <= 0
return norm(w) <= radius
end
c2 = dot(v, v)
if c2 <= c1
return norm(pt - pt2) <= radius
end
# Compute the perpendicular distance
b = c1 / c2
pb = pt1 + b * v
return norm(pt - pb) <= radius
end
# ╔═╡ 0b72af17-61fc-4b86-a338-8f86d32058fe
function create_cylinder(array, pt1, pt2, radius, offset)
# Convert the points to static arrays
pt1 = SVector{3, Float64}(pt1)
pt2 = SVector{3, Float64}(pt2)
# Compute the unit vector in the direction from pt1 to pt2
direction = normalize(pt2 - pt1)
# Adjust the endpoints of the cylinder by the offset
pt1 = pt1 - offset * direction
pt2 = pt2 + offset * direction
# Initialize the 3D array
cylinder = zeros(Int, size(array)...)
# Iterate over the 3D array
for k in axes(cylinder, 3)
for j in axes(cylinder, 2)
for i in axes(cylinder, 1)
# Create a static vector for the current point
pt = SVector{3, Int}(i, j, k)
# Check if the current point is inside the cylinder
if _in_cylinder(pt, pt1, pt2, radius)
cylinder[i, j, k] = 1
end
end
end
end
return Bool.(cylinder)
end
# ╔═╡ d61f577c-531a-4f16-a806-5bcfc64a94c2
function remove_outliers(vector)
Q1 = quantile(vector, 0.25)
Q3 = quantile(vector, 0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
return [x for x in vector if x > lower_bound]
end
# ╔═╡ da4739f0-4857-4b12-a5a9-bab91c543694
md"""
## Docs
"""
# ╔═╡ d6f176df-b323-4d74-b609-09a50b82a15d
md"""
!!! info ""
See `README.md` in the root directory for more info on the scans
| Accession Number | Scan Name | Series (80 kV) | Series (100 kV) | Series (120 kV) |
| ---------------- | --------- | -------------- | --------------- | --------------- |
| 3082 | C_0bpm | 2-11 | 12-21 | 22-31 |
| 3083 | F_0bpm | 2-11 | 12-21 | 22-31 |
| 3087 | E_0bpm | 2-11 | 12-21 | 22-31 |
| 3095 | D_0bpm | 2-11 | 12-21 | 22-31 |
"""
# ╔═╡ 4f0f5767-5c26-4ae4-a28c-20ca9ed986ee
md"""
# Download From Orthanc
"""
# ╔═╡ 96c15de9-3100-4d4d-b2e0-1380cf0ec31f
md"""
## Get Studies
Insert the IP address associated with the Orthanc server into the input box below and then click "Submit". When the code is finished, you can inspect the files by clicking on the dictionary.
"""
# ╔═╡ 1c611a7b-a89c-4bd3-99cc-296a4ccf43a5
@bind ip_address confirm(TextField(default="128.200.49.26"))
# ╔═╡ af303018-55b9-4330-8e8d-a3e7d1d98697
studies_dict = get_all_studies(ip_address)
# ╔═╡ 6dae0032-6a60-4421-a68e-a94c44416e6e
md"""
## Get Series
Insert the accession number into the input box above and click "Submit". When the code is finished, you can inspect the files by clicking on the dictionary.
"""
# ╔═╡ 6030b8c8-d10b-442b-875c-c9e8f5bd016a
md"""
## Get Instance(s)
You can insert the series number of interest into the input box above and then click "Submit". When the code is finished, you can inspect the files by clicking on the dictionary.
"""
# ╔═╡ b7807c48-6abe-416e-bbd9-5922e9044f33
md"""
# Download DICOM Instance(s)
Type the folder path above, where you want the DICOM files to be saved (or use a temporary directory via `mktempdir()`) in the code cell below. Then type in the instance number that you want to download and click "Submit".
"""
# ╔═╡ 4beb3247-28f0-4b30-b925-0061253ee304
output_dir_temp = mktempdir() # r
# ╔═╡ 87bc30a2-7b7e-4877-8618-aac5b44f88db
function download_info(acc, ser, inst, save_folder_path)
return combine() do Child
inputs = [
md""" $(acc): $(
Child(TextField(default="3082"))
)""",
md""" $(ser): $(
Child(TextField(default="2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31"))
)""",
md""" $(inst): $(
Child(TextField(default="1"))
)""",
md""" $(save_folder_path): $(
Child(TextField(default=output_dir_temp)))
)"""
]
md"""
#### Scan Details
Input the relevant DICOM information to download the appropriate scans
$(inputs)
"""
end
end
# ╔═╡ bb89a69b-35fc-4b42-a36c-9ac7640476c8
@bind details confirm(download_info("Accession Number", "Series Number(s)", "Instance Number", "Output Directory"))
# ╔═╡ e0e10a0c-464b-4185-bff7-d0a4e577cae1
accession_number, series_num, instance_num, output_dir = details
# ╔═╡ a23a7779-6b79-444c-a172-33afdf5fa204
series_dict = get_all_series(studies_dict, accession_number, ip_address)
# ╔═╡ 850df889-4876-4018-bf79-9de790d10091
series_num_vec = parse.(Int, split(series_num, ","))
# ╔═╡ 061edd0d-31a1-4f9a-842e-9b3c113d6e4b
begin
instances_dicts = []
for i in series_num_vec
instances_dict = get_all_instances(series_dict, string(i), ip_address)
push!(instances_dicts, instances_dict)
end
end
# ╔═╡ 1cbc8875-8b23-4660-8eb6-543f31436c73
instances_dicts
# ╔═╡ 986a7b15-a441-412f-88a7-25f9648cfcbc
instance_number = parse(Int64, instance_num)
# ╔═╡ d60685cd-846f-4591-9908-2f2275a193d0
instances_dicts
# ╔═╡ 08e918cd-0032-4f8e-be16-84f2b19d8291
md"""
# Run Script
"""
# ╔═╡ b22040f6-5726-4551-af1d-b65ae876e83c
begin
results_df = DataFrame(
insert_name = String[],
beats_per_minute = String[],
kV = Float64[],
mA = Float64[],
ctdi = Float64[],
gt_mass = Float64[],
vf_mass = Float64[],
vf_mass_bkg_mean = Float64[],
vf_mass_bkg_std = Float64[],
agatston_mass = Float64[],
agatston_mass_bkg_mean = Float64[],
agatston_mass_bkg_std = Float64[]
)
local insert_name
local beats_per_minute
for (i, dicts) in enumerate(instances_dicts)
@info i
output_paths = process_instances([dicts], series_num_vec[i], output_dir, instance_number, ip_address)
output_path = output_paths[end]
# Load DICOMs
dcms = dcmdir_parse(output_path)
dcm_arr = load_dcm_array(dcms)
header = dcms[1].meta
scan_name = header[(0x0010, 0x0020)]
insert_name = split(scan_name, "_")[1]
beats_per_minute = split(scan_name, "_")[2]
mA = header[(0x0018, 0x1151)]
kV = header[(0x0018, 0x0060)]
ctdi = header[(0x0018, 0x9345)] # mGy
x_space, y_space = header[(0x0028, 0x0030)]
slice_thickness = header[(0x0018, 0x0050)]
pixel_size = [x_space, y_space, slice_thickness]
# # Mask Heart
# mask_thresholded = threshold_low_high(dcm_arr, kV, mA)
# centroids = centroids_from_mask(mask_thresholded)
centroids = div.(size(dcm_arr), 2)
heart_rad = 95
heart_mask = create_circle_mask(dcm_arr[:, :, 3], centroids, heart_rad)
## Extract density
if insert_name == "A" || insert_name == "B" || insert_name == "C"
gt_density = 0.050 # mg/mm^3
elseif insert_name == "D" || insert_name == "E" || insert_name == "F"
gt_density = 0.100 # mg/mm^3
end
## Extract diameter
if insert_name == "A" || insert_name == "D"
diameter = 1.2 # mm
elseif insert_name == "B" || insert_name == "E"
diameter = 3.0 # mm
elseif insert_name == "C" || insert_name == "F"
diameter = 5.0 # mm
end
# Inserts
dcm_heart = dcm_arr .* heart_mask
insert_threshold = 500
centers_a, centers_b = get_insert_centers(dcm_heart, insert_threshold)
cylinder_rad = diameter * 2.0
cylinder = create_cylinder(dcm_heart, centers_a, centers_b, cylinder_rad, -25)
background_rad = cylinder_rad + 6
_background_ring = create_cylinder(dcm_heart, centers_a, centers_b, background_rad, -25)
background_ring = Bool.(_background_ring .- cylinder)
binary_calibration = falses(size(dcm_heart))
binary_calibration[centers_a...] = true
binary_calibration = dilate(binary_calibration)
cylinder_clean = remove_outliers(dcm_heart[cylinder])
background_clean = remove_outliers(dcm_heart[background_ring])
# Offset Measurements
off_num = 30
offa1 = (centers_a[1] + off_num, centers_a[2] + off_num, centers_a[3])
offb1 = (centers_b[1] + off_num, centers_b[2] + off_num, centers_b[3])
offa2 = (centers_a[1] - off_num, centers_a[2] - off_num, centers_a[3])
offb2 = (centers_b[1] - off_num, centers_b[2] - off_num, centers_b[3])
offa3 = (centers_a[1] + off_num, centers_a[2] - off_num, centers_a[3])
offb3 = (centers_b[1] + off_num, centers_b[2] - off_num, centers_b[3])
offset_cylinder1 = create_cylinder(dcm_heart, offa1, offb1, cylinder_rad, -25)
offset_cylinder2 = create_cylinder(dcm_heart, offa2, offb2, cylinder_rad, -25)
offset_cylinder3 = create_cylinder(dcm_heart, offa3, offb3, cylinder_rad, -25)
offset_background_ring1 = Bool.(create_cylinder(dcm_heart, offa1, offb1, background_rad, -25) .- offset_cylinder1)
offset_background_ring2 = Bool.(create_cylinder(dcm_heart, offa2, offb2, background_rad, -25) .- offset_cylinder2)
offset_background_ring3 = Bool.(create_cylinder(dcm_heart, offa3, offb3, background_rad, -25) .- offset_cylinder3)
offset_cylinder1_clean = remove_outliers(dcm_heart[offset_cylinder1])
offset_cylinder2_clean = remove_outliers(dcm_heart[offset_cylinder2])
offset_cylinder3_clean = remove_outliers(dcm_heart[offset_cylinder3])
offset_background_ring1_clean = remove_outliers(dcm_heart[offset_background_ring1])
offset_background_ring2_clean = remove_outliers(dcm_heart[offset_background_ring2])
offset_background_ring3_clean = remove_outliers(dcm_heart[offset_background_ring3])
# Ground truth mass
num_inserts = 3
gt_length = 7 # mm
gt_volume = π * (diameter/2)^2 * gt_length * num_inserts # mm^3
gt_mass = gt_density * gt_volume
# Volume fraction mass
## Extract "calibration" from the endpoint inserts (ρ: 400 mg/cc)
hu_calcium_400 = mean(dcm_heart[binary_calibration])
ρ_calcium_400 = 0.400 # mg/mm^3
## Calculate
voxel_size = pixel_size[1] * pixel_size[2] * pixel_size[3]
hu_heart_tissue_bkg = mean(background_clean)
hu_heart_tissue_bkg_offset1 = mean(offset_background_ring1_clean)
hu_heart_tissue_bkg_offset2 = mean(offset_background_ring2_clean)
hu_heart_tissue_bkg_offset3 = mean(offset_background_ring3_clean)
vf_mass = score(cylinder_clean, hu_calcium_400, hu_heart_tissue_bkg, voxel_size, ρ_calcium_400, VolumeFraction())
vf_mass_offset1 = score(offset_cylinder1_clean, hu_calcium_400, hu_heart_tissue_bkg_offset1, voxel_size, ρ_calcium_400, VolumeFraction())
vf_mass_offset2 = score(offset_cylinder2_clean, hu_calcium_400, hu_heart_tissue_bkg_offset2, voxel_size, ρ_calcium_400, VolumeFraction())
vf_mass_offset3 = score(offset_cylinder3_clean, hu_calcium_400, hu_heart_tissue_bkg_offset3, voxel_size, ρ_calcium_400, VolumeFraction())
vf_mass_bkg_mean = mean([vf_mass_offset1, vf_mass_offset2, vf_mass_offset3])
vf_mass_bkg_std = std([vf_mass_offset1, vf_mass_offset2, vf_mass_offset3])
# Agatston
mass_cal_factor = ρ_calcium_400 / hu_calcium_400
agatston_agatston, agatston_volume, agatston_mass = score(cylinder_clean, pixel_size, mass_cal_factor, Agatston(); kV=kV)
_, _, agatston_mass_offset1 = score(offset_cylinder1_clean, pixel_size, mass_cal_factor, Agatston(); kV=kV)
_, _, agatston_mass_offset2 = score(offset_cylinder2_clean, pixel_size, mass_cal_factor, Agatston(); kV=kV)
_, _, agatston_mass_offset3 = score(offset_cylinder3_clean, pixel_size, mass_cal_factor, Agatston(); kV=kV)
agatston_mass_bkg_mean = mean([agatston_mass_offset1, agatston_mass_offset2, agatston_mass_offset3])
agatston_mass_bkg_std = std([agatston_mass_offset1, agatston_mass_offset2, agatston_mass_offset3])
@info """
Ground Truth Mass: $(gt_mass) \n
Volume Fraction Mass: $(vf_mass) \n
Volume Fraction Background Mass Mean + Std: $((vf_mass_bkg_mean, vf_mass_bkg_std)) \n
Agatston Mass: $(agatston_mass) \n
Agatston Background Mass Mean + Std: $((agatston_mass_bkg_mean, agatston_mass_bkg_std))
"""
# Push results to DataFrame
push!(results_df, [insert_name, beats_per_minute, kV, mA, ctdi, gt_mass, vf_mass, vf_mass_bkg_mean, vf_mass_bkg_std, agatston_mass, agatston_mass_bkg_mean, agatston_mass_bkg_std])
end
output_filename = joinpath(pwd(),"data","$(insert_name)_$(beats_per_minute).csv")
write(output_filename, results_df)
end
# ╔═╡ 4951072e-5546-4825-a12c-bb917df5995c
results_df
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
CalciumScoring = "9c0cb1da-21b1-4615-967b-153e03110a28"
DICOM = "a26e6606-dd52-5f6a-a97f-4f611373d757"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
DataInterpolations = "82cc6244-b520-54b8-b5a6-8a565e85f1d0"
HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3"
ImageCore = "a09fc81d-aa75-5fe9-8630-4744c3626534"
ImageMorphology = "787d08f9-d448-5407-9aad-5290dd7ab264"
IterTools = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
OrderedCollections = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
[compat]
CSV = "~0.10.14"
CairoMakie = "~0.12.2"
CalciumScoring = "~0.4.0"
DICOM = "~0.11.0"
DataFrames = "~1.6.1"
DataInterpolations = "~5.2.0"
HTTP = "~1.10.8"
ImageCore = "~0.10.2"
ImageMorphology = "~0.4.5"
IterTools = "~1.10.0"
JSON = "~0.21.4"
OrderedCollections = "~1.6.3"
PlutoUI = "~0.7.59"
StaticArrays = "~1.9.4"
StatsBase = "~0.34.3"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.10.4"
manifest_format = "2.0"
project_hash = "efb9f0687ed4a560919717b6c1ac6293153a8010"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
weakdeps = ["ChainRulesCore", "Test"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "6e1d2a35f2f90a4bc7c2ed98079b2ba09c35b83a"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.3.2"
[[deps.AbstractTrees]]
git-tree-sha1 = "2d9c9a55f9c93e8887ad391fbae72f8ef55e1177"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.5"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "6a55b747d1812e699320963ffde36f1ebdda4099"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "4.0.4"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.AliasTables]]
deps = ["PtrArrays", "Random"]
git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff"
uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
version = "1.1.3"
[[deps.Animations]]
deps = ["Colors"]
git-tree-sha1 = "e81c509d2c8e49592413bfb0bb3b08150056c79d"
uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340"
version = "0.4.1"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "ed2ec3c9b483842ae59cd273834e5b46206d6dda"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.11.0"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceCUDSSExt = "CUDSS"
ArrayInterfaceChainRulesExt = "ChainRules"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceReverseDiffExt = "ReverseDiff"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
CUDSS = "45b445bb-4962-46a0-9369-b4df9d0f772e"
ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Automa]]
deps = ["PrecompileTools", "TranscodingStreams"]
git-tree-sha1 = "588e0d680ad1d7201d4c6a804dcb1cd9cba79fbb"
uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b"
version = "1.0.3"