-
Notifications
You must be signed in to change notification settings - Fork 0
/
Radiology Right Click v1.04.ahk
3433 lines (2913 loc) · 133 KB
/
Radiology Right Click v1.04.ahk
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
; ==========================================
; Radiologist's Helper Script
; Radiology Right Click
; Version: 1.04
; Description: This AutoHotkey script provides various calculation tools and utilities
; for radiologists, including volume calculations, date estimations,
; and statistical analysis of measurements.
; ==========================================
#NoEnv
#SingleInstance, Force
SetWorkingDir, %A_ScriptDir%
;OCR dependency
#include <Vis2> ; Equivalent to #include .\lib\Vis2.ahk
; Global variables for standard functions
global DisplayUnits := true
global DisplayAllValues := true
global ShowEllipsoidVolume := true
global ShowBulletVolume := true
global ShowPSADensity := true
global ShowPregnancyDates := true
global ShowMenstrualPhase := true
global ShowAdrenalWashout := true
global ShowThymusChemicalShift := true
global ShowHepaticSteatosis := true
global ShowMRILiverIron := true
global ShowStatistics := true
global ShowNumberRange := true
global PauseDuration := 180000
global DarkMode := false
global ShowCalciumScorePercentile := true
global ShowCitations := true
global ShowArterialAge :=
global g_SelectedText := ""
global PauseDurationChoice
global TargetApps := ["ahk_class Notepad", "ahk_exe notepad.exe", "ahk_class PowerScribe", "ahk_exe PowerScribe.exe", "ahk_class PowerScribe360", "ahk_exe Nuance.PowerScribe360.exe", "ahk_class PowerScribe | Reporting"]
global ResultText
global InvisibleControl
global originalMouseX, originalMouseY
global ScanDate, ScanTime, PremedProtocol
global ShowFleischnerCriteria := true
global g_Nodules := []
global g_FleischnerNodules := []
global g_ShowFleischnerCitation := false
global g_ShowFleischnerExclusions := false
global recommendations := {}
global ShowNASCETCalculator := true
;======== Global variables for for OCR
global g_arteryNames := {"lm": "Left Main"
,"li": "Left Main"
,"lit": "Left Main"
,"lad": "Left Anterior Descending"
,"cx": "Left Circumflex"
,"rca": "Right Coronary"
,"ca": "Right Coronary"
,"pda": "Posterior Descending Artery"
,"total": "Total"}
global g_levenshteinThreshold := 1.5
global g_ocrAttempts := 3 ; Number of OCR attempts
global CalciumScoreMonitor := 1
global CalciumScoreX := 0
global CalciumScoreY := 0
global CalciumScoreWidth := 0
global CalciumScoreHeight := 0
; Initialize GDI+
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
; Load preferences (keep this function at the top)
LoadPreferencesFromFile() {
global DisplayUnits, DisplayAllValues, ShowEllipsoidVolume, ShowBulletVolume, ShowPSADensity, ShowPregnancyDates, ShowMenstrualPhase, PauseDuration
global ShowAdrenalWashout, ShowThymusChemicalShift, ShowHepaticSteatosis, ShowMRILiverIron, ShowStatistics, ShowNumberRange, DarkMode
global ShowCitations, ShowArterialAge
preferencesFile := A_ScriptDir . "\preferences.ini"
if (FileExist(preferencesFile)) {
IniRead, DisplayUnits, %preferencesFile%, Display, DisplayUnits, 1
IniRead, DisplayAllValues, %preferencesFile%, Display, DisplayAllValues, 1
IniRead, ShowEllipsoidVolume, %preferencesFile%, Calculations, ShowEllipsoidVolume, 1
IniRead, ShowBulletVolume, %preferencesFile%, Calculations, ShowBulletVolume, 1
IniRead, ShowPSADensity, %preferencesFile%, Calculations, ShowPSADensity, 1
IniRead, ShowPregnancyDates, %preferencesFile%, Calculations, ShowPregnancyDates, 1
IniRead, ShowMenstrualPhase, %preferencesFile%, Calculations, ShowMenstrualPhase, 1
IniRead, ShowAdrenalWashout, %preferencesFile%, Calculations, ShowAdrenalWashout, 1
IniRead, ShowThymusChemicalShift, %preferencesFile%, Calculations, ShowThymusChemicalShift, 1
IniRead, ShowHepaticSteatosis, %preferencesFile%, Calculations, ShowHepaticSteatosis, 1
IniRead, ShowMRILiverIron, %preferencesFile%, Calculations, ShowMRILiverIron, 1
IniRead, ShowStatistics, %preferencesFile%, Calculations, ShowStatistics, 1
IniRead, ShowNumberRange, %preferencesFile%, Calculations, ShowNumberRange, 1
IniRead, PauseDuration, %preferencesFile%, Script, PauseDuration, 180000
IniRead, DarkMode, %preferencesFile%, Display, DarkMode, 0
IniRead, ShowCalciumScorePercentile, %preferencesFile%, Calculations, ShowCalciumScorePercentile, 1
IniRead, ShowCitations, %preferencesFile%, Display, ShowCitations, 1
IniRead, ShowArterialAge, %preferencesFile%, Display, ShowArterialAge, 1
IniRead, ShowContrastPremedication, %preferencesFile%, Calculations, ShowContrastPremedication, 1
IniRead, ShowFleischnerCriteria, %preferencesFile%, Calculations, ShowFleischnerCriteria, 1
IniRead, ShowNASCETCalculator, %preferencesFile%, Calculations, ShowNASCETCalculator, 1
IniRead, CalciumScoreMonitor, %preferencesFile%, CalciumScore, Monitor, 1
IniRead, CalciumScoreX, %preferencesFile%, CalciumScore, X, 0
IniRead, CalciumScoreY, %preferencesFile%, CalciumScore, Y, 0
IniRead, CalciumScoreWidth, %preferencesFile%, CalciumScore, Width, 0
IniRead, CalciumScoreHeight, %preferencesFile%, CalciumScore, Height, 0
} else {
MsgBox, Preferences file not found: %preferencesFile%. File will be created if preferences are edited.
}
DisplayUnits := (DisplayUnits = "1")
DisplayAllValues := (DisplayAllValues = "1")
ShowEllipsoidVolume := (ShowEllipsoidVolume = "1")
ShowBulletVolume := (ShowBulletVolume = "1")
ShowPSADensity := (ShowPSADensity = "1")
ShowPregnancyDates := (ShowPregnancyDates = "1")
ShowMenstrualPhase := (ShowMenstrualPhase = "1")
ShowAdrenalWashout := (ShowAdrenalWashout = "1")
ShowThymusChemicalShift := (ShowThymusChemicalShift = "1")
ShowHepaticSteatosis := (ShowHepaticSteatosis = "1")
ShowMRILiverIron := (ShowMRILiverIron = "1")
ShowStatistics := (ShowStatistics = "1")
ShowNumberRange := (ShowNumberRange = "1")
DarkMode := (DarkMode = "1")
ShowCalciumScorePercentile := (ShowCalciumScorePercentile = "1")
ShowCitations := (ShowCitations = "1")
ShowArterialAge := (ShowArterialAge = "1")
ShowNASCETCalculator := (ShowNASCETCalculator = "1")
PauseDuration += 0
}
LoadPreferencesFromFile()
InitializeRecommendations() ; Make sure to call this function before using the Nodule class -- used for fleischner
; ==========================================
; Main Script Logic
; ==========================================
; Set up context menu for target applications
#If IsTargetApp()
; Hook the spacebar to reset the timer if it's pressed after a single period
$Space::
if (A_PriorKey == "." and A_TimeSincePriorHotkey < 500)
{
lastPeriodTime := 0
}
SendInput {Space}
return
RButton::
{
; Activate the window if it's not already active
if (windowUnderCursor != WinActive("A")) {
WinActivate, ahk_id %windowUnderCursor%
}
; Small delay to ensure window activation and to allow for text selection
Sleep, 50
; Get selected text
g_SelectedText := GetSelectedText()
; Show our custom menu
CreateCustomMenu()
Menu, CustomMenu, Show
Menu, CustomMenu, DeleteAll
return
}
#If
; Function to check if the current window is a target application
IsTargetApp() {
MouseGetPos, , , windowUnderCursor
WinGetClass, windowClass, ahk_id %windowUnderCursor%
WinGet, windowExe, ProcessName, ahk_id %windowUnderCursor%
for index, app in TargetApps {
if (windowClass == StrReplace(app, "ahk_class ", "") || windowExe == StrReplace(app, "ahk_exe ", "")) {
return true
}
}
return false
}
; Function to create the custom right-click menu
CreateCustomMenu() {
global ShowEllipsoidVolume, ShowBulletVolume, ShowPSADensity, ShowPregnancyDates, ShowMenstrualPhase
global ShowAdrenalWashout, ShowThymusChemicalShift, ShowHepaticSteatosis
global ShowMRILiverIron, ShowStatistics, ShowNumberRange, DarkMode
global ShowCalciumScorePercentile, ShowContrastPremedication
; Create the menu
Menu, CustomMenu, Add
Menu, CustomMenu, DeleteAll
; Set menu colors and properties based on Dark Mode
if (DarkMode) {
Menu, CustomMenu, Color, 0xA9A9A9
} else {
Menu, CustomMenu, Color, Default
}
; Add standard editing options
Menu, CustomMenu, Add, Cut, MenuCut
Menu, CustomMenu, Add, Copy, MenuCopy
Menu, CustomMenu, Add, Paste, MenuPaste
Menu, CustomMenu, Add, Delete, MenuDelete
Menu, CustomMenu, Add
; Add custom calculation options
Menu, CustomMenu, Add, Compare Measurement Sizes, CompareNoduleSizes
Menu, CustomMenu, Add, Sort Measurement Sizes, SortNoduleSizes
Menu, CustomMenu, Add, Capture Calcium Score, CaptureCalciumScoreMenu
if (ShowCalciumScorePercentile) {
Menu, CustomMenu, Add, Calculate Calcium Score Percentile, CalculateCalciumScorePercentile
}
if (ShowEllipsoidVolume) {
Menu, CustomMenu, Add, Calculate Ellipsoid Volume, CalculateEllipsoidVolume
}
if (ShowBulletVolume) {
Menu, CustomMenu, Add, Calculate Bullet Volume, CalculateBulletVolume
}
if (ShowPSADensity) {
Menu, CustomMenu, Add, Calculate PSA Density, CalculatePSADensity
}
if (ShowPregnancyDates) {
Menu, CustomMenu, Add, Calculate Pregnancy Dates, CalculatePregnancyDates
}
if (ShowMenstrualPhase) {
Menu, CustomMenu, Add, Calculate Menstrual Phase, CalculateMenstrualPhase
}
if (ShowAdrenalWashout) {
Menu, CustomMenu, Add, Calculate Adrenal Washout, CalculateAdrenalWashout
}
if (ShowThymusChemicalShift) {
Menu, CustomMenu, Add, Calculate Thymus Chemical Shift, CalculateThymusChemicalShift
}
if (ShowHepaticSteatosis) {
Menu, CustomMenu, Add, Calculate Hepatic Steatosis, CalculateHepaticSteatosis
}
if (ShowMRILiverIron) {
Menu, CustomMenu, Add, MRI Liver Iron Content, CalculateIronContent
}
if (ShowStatistics) {
Menu, CustomMenu, Add, Calculate Statistics, Statistics
}
if (ShowNumberRange) {
Menu, CustomMenu, Add, Calculate Number Range, Range
}
if (ShowContrastPremedication) {
Menu, CustomMenu, Add, Calculate Contrast Premedication, CalculateContrastPremedication
}
if (ShowFleischnerCriteria) {
Menu, CustomMenu, Add, Calculate Fleischner Criteria, CalculateFleischnerCriteria
}
if (ShowNASCETCalculator) {
Menu, CustomMenu, Add, Calculate NASCET, CalculateNASCET
}
Menu, CustomMenu, Add
Menu, CustomMenu, Add, Pause Script, PauseScript
Menu, CustomMenu, Add, Preferences, ShowPreferences
}
; Standard editing functions
MenuCut:
Send, ^x
return
MenuCopy:
Send, ^c
return
MenuPaste:
Send, ^v
return
MenuDelete:
Send, {Delete}
return
; Custom calculation functions
; Each function now uses g_SelectedText instead of SelectedText
CaptureCalciumScoreMenu:
result := CaptureCalciumScore()
if (result)
ShowCalciumScore(result)
else
MsgBox, No calcium scores were captured or the capture was cancelled.
return
ParseUltrasoundMeasurementsMenu:
result := ParseUltrasoundMeasurements()
if (result && result.measurements.Count() > 0)
ShowUltrasoundMeasurements(result)
else
MsgBox, No measurements were captured or the capture was cancelled.
return
CalculateCalciumScorePercentile:
Result := CalculateCalciumScorePercentile(g_SelectedText)
ShowResult(Result)
return
CalculateEllipsoidVolume:
Result := CalculateEllipsoidVolume(g_SelectedText)
ShowResult(Result)
return
CalculateBulletVolume:
Result := CalculateBulletVolume(g_SelectedText)
ShowResult(Result)
return
CalculatePSADensity:
Result := CalculatePSADensity(g_SelectedText)
ShowResult(Result)
return
CalculatePregnancyDates:
Result := CalculatePregnancyDates(g_SelectedText)
ShowResult(Result)
return
CalculateMenstrualPhase:
Result := CalculateMenstrualPhase(g_SelectedText)
ShowResult(Result)
return
SortNoduleSizes:
ProcessedText := ProcessAllNoduleSizes(g_SelectedText)
if (ProcessedText != g_SelectedText)
{
; Preserve leading and trailing spaces only if they existed in the original input
leadingSpace := (SubStr(g_SelectedText, 1, 1) == " ") ? " " : ""
trailingSpace := (SubStr(g_SelectedText, 0) == " ") ? " " : ""
Clipboard := leadingSpace . Trim(ProcessedText) . trailingSpace
Send, ^v
}
return
Statistics:
Result := CalculateStatistics(g_SelectedText)
ShowResult(Result)
return
CalculateIronContent:
Result := EstimateIronContent(g_SelectedText)
ShowResult(Result)
return
Range:
Result := CalculateRange(g_SelectedText)
ShowResult(Result)
return
CalculateAdrenalWashout:
Result := CalculateAdrenalWashout(g_SelectedText)
ShowResult(Result)
return
CalculateThymusChemicalShift:
Result := CalculateThymusChemicalShift(g_SelectedText)
ShowResult(Result)
return
CalculateHepaticSteatosis:
Result := CalculateHepaticSteatosis(g_SelectedText)
ShowResult(Result)
return
CompareNoduleSizes:
Result := CompareNoduleSizes(g_SelectedText)
ShowResult(Result)
return
CalculateFleischnerCriteria:
Result := ProcessNodules(g_SelectedText)
ShowResult(Result)
return
CalculateNASCET:
Result := CalculateNASCET(g_SelectedText)
ShowResult(Result)
return
CloseResultBox:
Gui, ResultBox:Destroy
return
; Function to get selected text (unchanged)
GetSelectedText() {
OldClipboard := ClipboardAll
Clipboard := ""
Send, ^c
ClipWait, 0.1
if (ErrorLevel)
{
Clipboard := OldClipboard
return ""
}
SelectedText := Clipboard
Clipboard := OldClipboard
return SelectedText
}
ShowResult(Result) {
global DarkMode, originalMouseX, originalMouseY
; Get current mouse position (relative to the entire desktop)
CoordMode, Mouse, Screen
MouseGetPos, originalMouseX, originalMouseY
; Determine which monitor the mouse is on
SysGet, monitorCount, MonitorCount
Loop, %monitorCount%
{
SysGet, monArea, Monitor, %A_Index%
if (originalMouseX >= monAreaLeft && originalMouseX <= monAreaRight && originalMouseY >= monAreaTop && originalMouseY <= monAreaBottom)
{
activeMonitor := A_Index
break
}
}
; Get dimensions of the active monitor
SysGet, workArea, MonitorWorkArea, %activeMonitor%
monitorWidth := workAreaRight - workAreaLeft
monitorHeight := workAreaBottom - workAreaTop
; Calculate maximum dimensions for the GUI (50% of monitor width and height)
maxWidth := monitorWidth * 0.5
maxHeight := monitorHeight * 0.5
; Create a temporary GUI to measure text
Gui, TempMeasure:New, +AlwaysOnTop
Gui, TempMeasure:Font, s10, Segoe UI
Gui, TempMeasure:Add, Text, w%maxWidth% wrap, %Result%
GuiControlGet, TextSize, TempMeasure:Pos, Static1
GuiControl, Focus, Invisible
Gui, TempMeasure:Destroy
; Calculate required width and height
requiredWidth := TextSizeW + 40 ; Add some padding
requiredHeight := TextSizeH + 80 ; Add space for button and padding
; Adjust dimensions if they exceed the maximum
guiWidth := (requiredWidth > maxWidth) ? maxWidth : requiredWidth
guiHeight := (requiredHeight > maxHeight) ? maxHeight : requiredHeight
; Ensure minimum dimensions
guiWidth := (guiWidth < 300) ? 300 : guiWidth
guiHeight := (guiHeight < 200) ? 200 : guiHeight
; Calculate position for the GUI
xPos := originalMouseX + 10
yPos := originalMouseY + 10
; Ensure the GUI doesn't go off-screen
if (xPos + guiWidth > workAreaRight)
xPos := workAreaRight - guiWidth
if (yPos + guiHeight > workAreaBottom)
yPos := workAreaBottom - guiHeight
; Create GUI with AlwaysOnTop option
Gui, ResultBox:New, +AlwaysOnTop -SysMenu +Owner
Gui, ResultBox:Margin, 10, 10
; Apply styling
if (DarkMode) {
Gui, ResultBox:Color, 0x2C2C2C, 0x2C2C2C
textColor := "cE0E0E0"
buttonOptions := "Background333333 c999999"
} else {
Gui, ResultBox:Color, 0xF0F0F0, 0xF0F0F0
textColor := "c000000"
buttonOptions := "Background777777 cFFFFFF"
}
Gui, ResultBox:Font, s10 %textColor%, Segoe UI
; Add text control with vertical scrollbar and word wrap, and no highlighting
editHeight := guiHeight - 50 ; Subtract height for button and margins
Gui, ResultBox:Add, Edit, vResultText ReadOnly -E0x200 +E0x20000 Wrap VScroll w%guiWidth% h%editHeight%, %Result%
; Add a close button with improved styling
Gui, ResultBox:Font, s9 bold, Segoe UI
Gui, ResultBox:Add, Button, gCloseResultBox w90 x10 y+10 %buttonOptions%, Close
; Show the GUI
Gui, ResultBox:Show, x%xPos% y%yPos% w%guiWidth% h%guiHeight%, Result
; Add an invisible control for focus
Gui, ResultBox:Add, Text, Hidden vInvisibleControl
; Show the GUI
Gui, ResultBox:Show, x%xPos% y%yPos% w%guiWidth% h%guiHeight%, Result
; Shift focus to the invisible control
GuiControl, Focus, InvisibleControl
; Get the position of the close button
GuiControlGet, ClosePos, ResultBox:Pos, Close
; Move the mouse over the close button
MouseMove, % xPos + ClosePosX + ClosePosW/2, % yPos + ClosePosY + ClosePosH/2, 0
; Copy result to clipboard
Clipboard := Result
return
}
CalculateEllipsoidVolume(input) {
RegExNeedle := "\s*(\d+(?:\.\d+)?)\s*[x,]\s*(\d+(?:\.\d+)?)\s*[x,]\s*(\d+(?:\.\d+)?)\s*"
if (RegExMatch(input, RegExNeedle, match)) {
dimensions := [match1, match2, match3]
dimensions := SortDimensions(dimensions)
isMillimeters := (InStr(dimensions[1], ".") = 0) && (InStr(dimensions[2], ".") = 0) && (InStr(dimensions[3], ".") = 0)
if (isMillimeters) {
dimensions[1] := dimensions[1] / 10
dimensions[2] := dimensions[2] / 10
dimensions[3] := dimensions[3] / 10
}
volume := (1/6) * 3.14159265358979323846 * (dimensions[1]) * (dimensions[2]) * (dimensions[3])
volumeRounded := (volume < 1) ? Round(volume, 3) : Round(volume, 1)
result := input . " (" . volumeRounded . (DisplayUnits ? " cc" : "") . ")"
return result
} else {
return "Invalid input format for ellipsoid volume calculation.`nSample syntax: 3 x 2 x 1 cm"
}
}
CalculateBulletVolume(input) {
RegExNeedle := "\s*(\d+(?:\.\d+)?)\s*[x,]\s*(\d+(?:\.\d+)?)\s*[x,]\s*(\d+(?:\.\d+)?)\s*"
if (RegExMatch(input, RegExNeedle, match)) {
dimensions := [match1, match2, match3]
dimensions := SortDimensions(dimensions)
isMillimeters := (InStr(dimensions[1], ".") = 0) && (InStr(dimensions[2], ".") = 0) && (InStr(dimensions[3], ".") = 0)
if (isMillimeters) {
dimensions[1] := dimensions[1] / 10
dimensions[2] := dimensions[2] / 10
dimensions[3] := dimensions[3] / 10
}
volume := dimensions[1] * dimensions[2] * dimensions[3] * (5 * 3.14159265358979323846 / 24)
volumeRounded := (volume < 1) ? Round(volume, 3) : Round(volume, 1)
result := input . " (" . volumeRounded . (DisplayUnits ? " cc" : "") . ")"
return result
} else {
return "Invalid input format for bullet volume calculation.`nSample syntax: 3 x 2 x 1 cm"
}
}
CalculatePSADensity(input) {
volNotGiven = 1
volumeMethod = User Supplied
; Regular expression for PSA value
PSARegEx := "i)PSA\s*(?:level|value)?:?\s*(\d+(?:\.\d+)?)\s*(?:ng\/ml|ng\/mL|ng/ml|ng/mL|ng\/cc|ng/cc)?"
; Regular expression for prostate volume (all formats)
VolumeRegEx := "i)(?:(?:Calculated\s*)?(?:ellipsoid\s*)?volume:?\s*(\d+(?:\.\d+)?)\s*(?:cc|cm3|mL|ml)|(?:Prostate )?Size:?.*?\((\d+(?:\.\d+)?)\s*cc\)|(\d+(?:\.\d+)?)\s*x\s*\d+(?:\.\d+)?\s*x\s*\d+(?:\.\d+)?\s*cm\s*\((\d+(?:\.\d+)?)\s*cc\))"
if (RegExMatch(input, PSARegEx, PSAMatch)) {
PSALevel := PSAMatch1
} else {
return "Invalid input format for PSA density calculation.`nSuggested format:`nPSA: 5.6 ng/mL`nSize: 3.5 x 5.4 x 2.5 cm"
}
if (RegExMatch(input, VolumeRegEx, VolumeMatch)) {
ProstateVolume := VolumeMatch1 ? VolumeMatch1 : (VolumeMatch2 ? VolumeMatch2 : (VolumeMatch4 ? VolumeMatch4 : ""))
} else {
volNotGiven=0
; Try to calculate volume using CalculateBullettVolume
bulletResult := CalculateBulletVolume(input)
if (!InStr(bulletResult, "Invalid input")) {
ProstateVolume := RegExReplace(bulletResult, "s).*?(\d+(?:\.\d+)?)(?:\s*cc)?\).*", "$1")
volumeMethod = Bullett Volume
; If volume >= 55 cc, use CalculateEllipsoidVolume instead (https://pubs.rsna.org/doi/10.1148/radiol.2501080290#:~:text=Overall%2C%20between%2066%25%20and%2075,bullet%20formula%20is%20highly%20accurate.)
if (ProstateVolume >= 55) {
ellipsoidResult := CalculateEllipsoidVolume(input)
volumeMethod = Ellipsoid Volume
if (!InStr(ellipsoidResult, "Invalid input")) {
ProstateVolume := RegExReplace(ellipsoidResult, "s).*?(\d+(?:\.\d+)?)(?:\s*cc)?\).*", "$1")
}
}
} else {
return "Prostate volume or dimensions not found or invalid in the input.`nSuggested format:`nPSA: 5.6 ng/mL`nSize: 3.5 x 5.4 x 2.5 cm"
}
}
PSADensity := PSALevel / ProstateVolume
PSADensity := Round(PSADensity, 3)
if(volNotGiven=0){
result := input . "`nProstate volume: " . ProstateVolume . " cc " . "- " . volumeMethod . "`nPSA Density: " . PSADensity . (DisplayUnits ? " ng/mL/cc" : "")
} else {
result := input . "`nPSA Density: " . PSADensity . (DisplayUnits ? " ng/mL/cc" : "")
}
return result
}
CalculatePregnancyDates(input) {
LMPRegEx := "i)(?:LMP|Last\s*Menstrual\s*Period).*?(\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})"
GARegEx := "i)(\d+)(?:\s*(?:weeks?|w))?\s*(?:and|&|,|-|;)?\s*(\d+)?(?:\s*(?:days?|d))?(?:\s*[,;-]?\s+(?:as of|on)\s+(today|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}))?"
if (RegExMatch(input, LMPRegEx, LMPMatch)) {
LMPDate := ParseDate(LMPMatch1)
if (LMPDate = "Invalid Date") {
return "Invalid LMP date format. Please use MM/DD/YYYY, DD/MM/YYYY, or MM/DD/YY."
}
return CalculateDatesFromLMP(LMPDate)
} else if (RegExMatch(input, GARegEx, GAMatch)) {
WeeksGA := GAMatch1 + 0
DaysGA := (GAMatch2 != "") ? GAMatch2 + 0 : 0
ReferenceDate := (GAMatch3 != "") ? (GAMatch3 = "today" ? A_Now : ParseDate(GAMatch3)) : A_Now
return CalculateDatesFromGA(WeeksGA, DaysGA, ReferenceDate)
} else {
return "Invalid input format for pregnancy date calculation.`nSample syntax:`nLMP: 01/15/2023`nor`nGA: 12 weeks and 3 days as of today"
}
}
CalculateMenstrualPhase(input) {
LMPRegEx := "i)(?:LMP|Last\s*Menstrual\s*Period)?\s*:?\s*(\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})"
if (RegExMatch(input, LMPRegEx, LMPMatch)) {
LMPDate := ParseDate(LMPMatch1)
if (LMPDate = "Invalid Date") {
return "Invalid LMP date format. Please use MM/DD/YYYY, DD/MM/YYYY, or MM/DD/YY."
}
return DetermineMenstrualPhase(LMPDate)
} else {
return "Invalid input format for menstrual phase calculation.`nSample syntax: LMP: 05/01/2023"
}
}
ProcessAllNoduleSizes(input) {
RegExNeedleComma3 := "\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*"
RegExNeedleX3 := "\s*(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*"
RegExNeedleComma2 := "\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*"
RegExNeedleX2 := "\s*(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*"
input := ProcessPattern(input, RegExNeedleComma3, 3)
input := ProcessPattern(input, RegExNeedleX3, 3)
input := ProcessPattern(input, RegExNeedleComma2, 2)
input := ProcessPattern(input, RegExNeedleX2, 2)
return input
}
ProcessPattern(input, RegExNeedle, dimensions) {
pos := 1
while (pos := RegExMatch(input, RegExNeedle, match, pos)) {
if (dimensions == 3) {
processed := ProcessNoduleSizes(match1, match2, match3)
} else if (dimensions == 2) {
processed := ProcessNoduleSizes(match1, match2)
}
if (processed != match) {
input := SubStr(input, 1, pos-1) . processed . SubStr(input, pos+StrLen(match))
}
pos += StrLen(processed)
}
return input
}
ProcessNoduleSizes(a, b, c := "") {
; Convert to numbers for comparison, but keep original strings
aNum := a + 0
bNum := b + 0
cNum := c != "" ? c + 0 : ""
if (c != "") {
if (aNum < bNum) {
temp := a
a := b
b := temp
tempNum := aNum
aNum := bNum
bNum := tempNum
}
if (bNum < cNum) {
temp := b
b := c
c := temp
tempNum := bNum
bNum := cNum
cNum := tempNum
}
if (aNum < bNum) {
temp := a
a := b
b := temp
tempNum := aNum
aNum := bNum
bNum := tempNum
}
return " " . Trim(a) . " x " . Trim(b) . " x " . Trim(c) . " "
} else {
if (aNum < bNum) {
temp := a
a := b
b := temp
}
return " " . Trim(a) . " x " . Trim(b) . " "
}
}
CalculateStatistics(input) {
numbers := ExtractNumbers(input)
count := numbers.Length()
if (count == 0) {
return "No numbers found in the selected text."
}
result := "Statistics:`n"
result .= "Count: " . count . "`n"
result .= "Sum: " . Round(CalculateSum(numbers), 1) . "`n"
;result .= "Product: " . CalculateProduct(numbers) . "`n"
result .= "Mean: " . Round(CalculateMean(numbers), 1) . "`n"
result .= "Median: " . Round(CalculateMedian(numbers), 1) . "`n"
result .= "Min: " . Round(Min(numbers*), 1) . "`n"
result .= "Max: " . Round(Max(numbers*), 1) . "`n"
if (count >= 9) {
Q1 := Round(CalculateQuartile(numbers, 0.25), 1)
Q3 := Round(CalculateQuartile(numbers, 0.75), 1)
IQR := Q3 - Q1
median := Round(CalculateMedian(numbers), 1)
result .= "Q1: " . Q1 . "`n"
result .= "Q3: " . Q3 . "`n"
result .= "IQR: " . Round(IQR, 1) . "`n"
result .= "IQR/Median: " . Round(IQR / median, 2) . "`n"
result .= "Standard Deviation: " . Round(CalculateStandardDeviation(numbers), 1) . "`n"
}
return result
}
ExtractNumbers(input) {
numbers := []
input := RegExReplace(input, "i)(?:^|\n|\s)(?:slice|observation|sample|number|#|no\.?)\s*\d+:?\s*", "`n")
RegExNeedle := "(-?\d+(?:\.\d+)?)\s*(?:cm|mm)?"
pos := 1
while (pos := RegExMatch(input, RegExNeedle, match, pos)) {
if (match1 != "") {
numbers.Push(match1 + 0)
}
pos += StrLen(match)
}
return numbers
}
CalculateSum(arr) {
total := 0
for index, value in arr
total += value
return total
}
CalculateProduct(arr) {
total := 1
for index, value in arr
total *= value
return total
}
CalculateMean(numbers) {
sum := 0
for i, num in numbers {
sum += num
}
return Round(sum / numbers.Length(), 2)
}
CalculateMedian(numbers) {
sortedNumbers := SortArray(numbers)
count := sortedNumbers.Length()
if (count == 0) {
return 0
} else if (Mod(count, 2) == 0) {
middle1 := sortedNumbers[count//2]
middle2 := sortedNumbers[(count//2) + 1]
return (middle1 + middle2) / 2
} else {
return sortedNumbers[Floor(count/2) + 1]
}
}
SortArray(numbers) {
sortedNumbers := []
for index, value in numbers {
sortedNumbers.Push(value)
}
sortedNumbers.Sort()
return sortedNumbers
}
CalculateQuartile(numbers, percentile) {
sortedNumbers := SortArray(numbers)
count := sortedNumbers.Length()
position := (count - 1) * percentile + 1
lower := Floor(position)
upper := Ceil(position)
if (lower == upper) {
return Round(sortedNumbers[lower], 2)
} else {
return Round(sortedNumbers[lower] + (position - lower) * (sortedNumbers[upper] - sortedNumbers[lower]), 2)
}
}
CalculateStandardDeviation(numbers) {
mean := CalculateMean(numbers)
sumSquaredDiff := 0
for i, num in numbers {
diff := num - mean
sumSquaredDiff += diff * diff
}
variance := sumSquaredDiff / (numbers.Length() - 1)
return Round(Sqrt(variance), 2)
}
EstimateIronContent(input) {
global ShowCitations
RegExMatch(input, "i)(?:\b|^)(1[.,]5|3[.,]0|1\.5|3\.0)(?:\s*-?\s*)?T(?:esla)?", fieldStrength)
if (!fieldStrength1) {
return "Error: Magnetic field strength (1.5T or 3.0T) not found in the input."
}
fieldStrength1 := StrReplace(fieldStrength1, ",", ".")
R2StarPattern := "i)R2\*?\s*(?:value|reading|measurement)?(?:[\s:=]+of)?\s*[:=]?\s*(\d+(?:[.,]\d+)?)\s*(?:Hz|hertz|s(?:ec(?:ond)?)?⻹|1/s)"
RegExMatch(input, R2StarPattern, R2Star)
if (!R2Star1) {
return "Error: R2* value not found in the input.`nSample syntax: 1.5T, R2*: 50 Hz"
}
R2StarValue := StrReplace(R2Star1, ",", ".")
R2StarValue += 0
if (fieldStrength1 == "1.5") {
ironContent := -0.04 + 2.62 * 10 ** -2 * R2StarValue
} else {
ironContent := 1.41 * 10 ** -2 * R2StarValue
}
result := input . " (" . Round(ironContent, 2) . " mg Fe/g dry liver)"
if (DisplayAllValues) {
result .= "`nMagnetic Field Strength: " . fieldStrength1 . "T`n"
result .= "R2* Value: " . R2StarValue . " Hz`n"
}
if (ShowCitations=1){
result .= "`nHernando D, Cook RJ, Qazi N, Longhurst CA, Diamond CA, Reeder SB. Complex confounder-corrected R2* mapping for liver iron quantification with MRI. Eur Radiol. 2021 Jan;31(1):264-275. doi: 10.1007/s00330-020-07123-x. Epub 2020 Aug 12. PMID: 32785766; PMCID: PMC7755713.`n"
}
return result
}
CalculateRange(input) {
numbers := []
unit := ""
RegExNeedle := "(-?\d+(?:\.\d+)?)\s*((?:cm/s|mm/s|m/s|km/h|mph|cm|mm|Hz|T|mg|m|ml|mL|cc|s|min|hr|days?|weeks?|months?|years?|g|ng|ng/ml|ng/mL|mmol/L|μmol/L|°?F|°?C)(?:/(?:day|week|month|year))?)?"
pos := 1
while (pos := RegExMatch(input, RegExNeedle, match, pos)) {
numbers.Push(match1 + 0)
if (match2 != "" && unit == "") {
unit := match2
}
pos += StrLen(match)
}
if (numbers.Length() == 0) {
return "No numbers found in the selected text."
}
minValue := Min(numbers*)
maxValue := Max(numbers*)
result := Round(minValue, 1) . " - " . Round(maxValue, 1)
if (unit != "") {
result .= " " . unit
}
return result
}
CalculateAdrenalWashout(input) {
global ShowCitations
RegExNeedle := "i)(?:(?:unenhanced|non-?enhanced|intrinsic|pre-?contrast|baseline|native)(?:\s+CT)?(?:\s+density|\s+HU|\s+hounsfield\s+units?)?[\s:]*(-?\d+(?:\.\d+)?)\s*(?:HU|hounsfield\s+units?)?).*?(?:(?:enhanced|post-?contrast|arterial|portal\s+venous?|60-?75\s*(?:second|sec)|1-?2\s*min(?:ute)?)(?:\s+CT)?(?:\s+density|\s+HU|\s+hounsfield\s+units?)?[\s:]*(-?\d+(?:\.\d+)?)\s*(?:HU|hounsfield\s+units?)?).*?(?:(?:delayed|late|15\s*min(?:ute)?|10-?15\s*min(?:ute)?|post-?contrast)(?:\s+CT)?(?:\s+density|\s+HU|\s+hounsfield\s+units?)?[\s:]*(-?\d+(?:\.\d+)?)\s*(?:HU|hounsfield\s+units?)?)"
if (RegExMatch(input, RegExNeedle, match)) {
unenhanced := match1
enhanced := match2
delayed := match3
absoluteWashout := ((enhanced - delayed) / (enhanced - unenhanced)) * 100
relativeWashout := ((enhanced - delayed) / enhanced) * 100
result := input . "`n`n"
result .= "Absolute Washout: " . Round(absoluteWashout, 1) . "% ... (Ref adenomas: >=60%)" . "`n"
result .= "Relative Washout: " . Round(relativeWashout, 1) . "% ... (Ref adenomas: >=40%)" . "`n`n"
if(ShowCitations=1){
result .= "`nMayo-Smith WW, Song JH, Boland GL, Francis IR, Israel GM, Mazzaglia PJ, Berland LL, Pandharipande PV. Management of Incidental Adrenal Masses: A White Paper of the ACR Incidental Findings Committee. J Am Coll Radiol. 2017 Aug;14(8):1038-1044.`n`n"
}
result .= InterpretAdrenalWashout(absoluteWashout, relativeWashout, unenhanced, enhanced, delayed)
return result
} else {
RegExNeedle := "i)(?:(?:enhanced|post-?contrast|arterial|portal\s+venous?|60-?75\s*(?:second|sec)|1-?2\s*min(?:ute)?)(?:\s+CT)?(?:\s+density|\s+HU|\s+hounsfield\s+units?)?[\s:]*(-?\d+(?:\.\d+)?)\s*(?:HU|hounsfield\nits?)?).*?(?:(?:delayed|late|15\s*min(?:ute)?|10-?15\s*min(?:ute)?|post-?contrast)(?:\s+CT)?(?:\s+density|\s+HU|\s+hounsfield\s+units?)?[\s:]*(-?\d+(?:\.\d+)?)\s*(?:HU|hounsfield\s+units?)?)"
if (RegExMatch(input, RegExNeedle, match)) {
enhanced := match1
delayed := match2
relativeWashout := ((enhanced - delayed) / enhanced) * 100
result := input . "`n`n"
result .= "Relative Washout: " . Round(relativeWashout, 1) . "%`n`n"
result .= InterpretAdrenalWashout(0, relativeWashout, unenhanced, enhanced, delayed)
if(ShowCitations=1){
result .= "`n`n`nMayo-Smith WW, Song JH, Boland GL, Francis IR, Israel GM, Mazzaglia PJ, Berland LL, Pandharipande PV. Management of Incidental Adrenal Masses: A White Paper of the ACR Incidental Findings Committee. J Am Coll Radiol. 2017 Aug;14(8):1038-1044.`n`n"
}
return result
} else {
return "Invalid input format for adrenal washout calculation.`nSample syntax: Unenhanced: 10 HU, Enhanced: 80 HU, Delayed: 40 HU"
}
}
}
InterpretAdrenalWashout(absoluteWashout, relativeWashout, unenhanced, enhanced, delayed) {
result := ""
; Check if unenhanced is null or empty
if (unenhanced = "" or unenhanced = "NULL") {
unenhanced := "N/A"
isUnenhancedAvailable := false
} else {
isUnenhancedAvailable := true
unenhanced += 0 ; Convert to number
}
; Check for enhancing mass
if (isUnenhancedAvailable) {
enhancedChange := CheckEnhancement(enhanced, unenhanced)
delayedChange := CheckEnhancement(delayed, unenhanced)
; Add interpretation based on unenhanced HU
if (unenhanced <= 10) {
result .= "Unenhanced HU less than 10 is typically suggestive of a benign adrenal adenoma. "
} else if (unenhanced > 43) {
result .= "Unenhanced HU >43 in a noncalcified, nonhemorrhagic lesion is suspicious for malignancy, regardless of washout characteristics. "
}
if (Abs(enhancedChange) >= 10 or Abs(delayedChange) >= 10) {
if (enhancedChange < 0 or delayedChange < 0) {
result .= "The adrenal mass demonstrates unexpected de-enhancement (decrease in HU in enhanced or delayed phase). This is an atypical finding. "
result .= "Caution: Standard washout calculations may not be applicable in this case. "
} else {
result .= "The adrenal mass demonstrates enhancement. "
; Interpret washout only if there's positive enhancement
if (absoluteWashout >= 60 or relativeWashout >= 40) {
result .= "Adrenal washout characteristics are suggestive of a benign adrenal adenoma. "
} else {
result .= "Washout characteristics are indeterminate. "
}
}
} else {
result .= "The adrenal mass does not demonstrate significant enhancement (<10 HU change in both enhanced and delayed phases compared to unenhanced). This may represent a cyst, hemorrhage, or other non-enhancing lesion. Further characterization with additional imaging may be necessary. "
}