-
Notifications
You must be signed in to change notification settings - Fork 92
/
selection_nodes.py
1872 lines (1637 loc) · 65.4 KB
/
selection_nodes.py
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
"""Functions that will be used as steps in a decision tree."""
import logging
import numpy as np
import pandas as pd
from scipy.stats import scoreatpercentile
from tedana.docs import fill_doc
from tedana.metrics.dependence import generate_decision_table_score
from tedana.selection.selection_utils import (
change_comptable_classifications,
confirm_metrics_exist,
get_extend_factor,
kappa_elbow_kundu,
log_decision_tree_step,
rho_elbow_kundu_liberal,
selectcomps2use,
)
LGR = logging.getLogger("GENERAL")
RepLGR = logging.getLogger("REPORT")
RefLGR = logging.getLogger("REFERENCES")
@fill_doc
def manual_classify(
selector,
decide_comps,
new_classification,
clear_classification_tags=False,
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
tag=None,
dont_warn_reclassify=False,
):
"""Assign a classification defined in new_classification to the components in decide_comps.
Parameters
----------
%(selector)s
%(decide_comps)s
new_classification : :obj:`str`
Assign all components identified in decide_comps the classification
in new_classification. Options are 'unclassified', 'accepted',
'rejected', or intermediate_classification labels predefined in the
decision tree
clear_classification_tags : :obj:`bool`
If True, reset all values in the 'classification_tags' column to empty
strings. This also can create the classification_tags column if it
does not already exist. If False, do nothing.
tag : :obj:`str`
A classification tag to assign to all components being reclassified.
This should be one of the tags defined by classification_tags in
the decision tree specification
dont_warn_reclassify : :obj:`bool`
By default, if this function changes a component classification from accepted or
rejected to something else, it gives a warning, since those should be terminal
classifications. If this is True, that warning is suppressed.
(Useful if manual_classify is used to reset all labels to unclassified).
Default=False
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
Returns
-------
%(selector)s
%(used_metrics)s
Note
----
This was designed with three use cases in mind:
(1) Set the classifications of all components to unclassified
for the first node of a decision tree. clear_classification_tags=True is
recommended for this use case.
(2) Shift all components between classifications, such as provisionalaccept to accepted for the
penultimate node in the decision tree.
(3) Manually re-classify components by number based on user observations.
Unlike other decision node functions, ``if_true`` and ``if_false`` are not inputs
since the same classification is assigned to all components listed in ``decide_comps``.
"""
# predefine all outputs that should be logged
outputs = {
"decision_node_idx": selector.current_node_idx,
"used_metrics": set(),
"node_label": None,
"n_true": None,
"n_false": None,
}
if only_used_metrics:
return outputs["used_metrics"]
if_true = new_classification
if_false = "nochange"
function_name_idx = f"Step {selector.current_node_idx}: manual_classify"
if custom_node_label:
outputs["node_label"] = custom_node_label
else:
outputs["node_label"] = "Set " + str(decide_comps) + " to " + new_classification
LGR.info(f"{function_name_idx}: {outputs['node_label']} ")
if log_extra_info:
LGR.info(f"{function_name_idx} {log_extra_info}")
if log_extra_report:
RepLGR.info(log_extra_report)
comps2use = selectcomps2use(selector, decide_comps)
if not comps2use:
log_decision_tree_step(function_name_idx, comps2use, decide_comps=decide_comps)
outputs["n_true"] = 0
outputs["n_false"] = 0
else:
decision_boolean = pd.Series(True, index=comps2use)
selector, outputs["n_true"], outputs["n_false"] = change_comptable_classifications(
selector,
if_true,
if_false,
decision_boolean,
tag_if_true=tag,
dont_warn_reclassify=dont_warn_reclassify,
)
log_decision_tree_step(
function_name_idx,
comps2use,
n_true=outputs["n_true"],
n_false=outputs["n_false"],
if_true=if_true,
if_false=if_false,
)
if clear_classification_tags:
selector.component_table["classification_tags"] = ""
LGR.info(function_name_idx + " component classification tags are cleared")
selector.tree["nodes"][selector.current_node_idx]["outputs"] = outputs
return selector
@fill_doc
def dec_left_op_right(
selector,
if_true,
if_false,
decide_comps,
op,
left,
right,
left_scale=1,
right_scale=1,
op2=None,
left2=None,
right2=None,
left2_scale=1,
right2_scale=1,
op3=None,
left3=None,
right3=None,
left3_scale=1,
right3_scale=1,
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
tag_if_true=None,
tag_if_false=None,
):
"""Perform a relational comparison.
Parameters
----------
%(selector)s
%(tag_if_true)s
%(tag_if_false)s
%(decide_comps)s
op: :obj:`str`
Must be one of: ">", ">=", "==", "<=", "<"
Applied the user defined operator to left op right
left, right: :obj:`str` or :obj:`float`
The labels for the two metrics to be used for comparision.
For example: left='kappa', right='rho' and op='>' means this
function will test kappa>rho. One of the two can also be a number.
In that case, a metric would be compared against a fixed threshold.
For example left='T2fitdiff_invsout_ICAmap_Tstat', right=0, and op='>'
means this function will test T2fitdiff_invsout_ICAmap_Tstat>0
left_scale, right_scale: :obj:`float` or :obj:`str`
Multiply the left or right metrics value by a constant. For example
if left='kappa', right='rho', right_scale=2, and op='>' this tests
kappa>(2*rho). These can also be a string that is a value in
cross_component_metrics, since those will resolve to a single value.
This cannot be a label for a component_table column since that would
output a different value for each component. Default=1
op2: :obj:`str`, Default=None
left2, right2, left3, right3: :obj:`str` or :obj:`float`, Default=None
left2_scale, right2_scale, left3_scale, right3_scale: :obj:`float` or :obj:`str`, Default=1
This function can also be used to calculate the intersection of two or three
boolean statements. If op2, left2, and right2 are defined then
this function returns
(left_scale*)left op (right_scale*right) AND (left2_scale*)left2 op2 (right2_scale*right2)
if the "3" parameters are also defined then it's the intersection of all 3 statements
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
%(tag_if_true)s
%(tag_if_false)s
Returns
-------
%(selector)s
%(used_metrics)s
Note
----
This function is ideally run with one boolean statement at a time so that
the result of each boolean is logged. For example, it's better to test
kappa>kappa_elbow and rho>rho_elbow with two separate calls to this function
so that the results of each test can be easily viewed. That said, particularly for
the original kundu decision tree, if you're making decisions on components with
various classifications based on multiple boolean statements, the decision tree
becomes really messy and the added functionality here is useful.
Combinations of boolean statements only test with "and" and not "or". This is
an intentional decision because, if a classification changes if A>B or C>D are true
then A>B and C>D should be logged separately
"""
# predefine all outputs that should be logged
outputs = {
"decision_node_idx": selector.current_node_idx,
"used_metrics": set(),
"used_cross_component_metrics": set(),
"node_label": None,
"n_true": None,
"n_false": None,
}
function_name_idx = f"Step {selector.current_node_idx}: left_op_right"
# Only select components if the decision tree is being run
if not only_used_metrics:
comps2use = selectcomps2use(selector, decide_comps)
def identify_used_metric(val, isnum=False):
"""
Parse the left or right values or scalers to see if they are an
existing used_metric or cross_component_metric
If the value already a number, no parse would be needed
This is also used on left_scale and right_scale to convert
a value in cross_component_metrics to a number. Set the isnum
flag to true for those inputs and this will raise an error
if a number isn't loaded
"""
orig_val = val
if isinstance(val, str):
if val in selector.component_table.columns:
outputs["used_metrics"].update([val])
elif val in selector.cross_component_metrics:
outputs["used_cross_component_metrics"].update([val])
val = selector.cross_component_metrics[val]
# If decision tree is being run, then throw errors or messages
# if a component doesn't exist. If this is just getting a list
# of metrics to be used, then don't bring up warnings
elif not only_used_metrics:
if not comps2use:
LGR.info(
f"{function_name_idx}: {val} is neither a metric in "
"selector.component_table nor selector.cross_component_metrics, "
f"but no components with {decide_comps} remain by this node "
"so nothing happens"
)
else:
raise ValueError(
f"{val} is neither a metric in selector.component_table "
"nor selector.cross_component_metrics"
)
if isnum:
if not isinstance(val, (int, float)):
raise ValueError(f"{orig_val} must be a number. It is {val}")
return val
legal_ops = (">", ">=", "==", "<=", "<")
def confirm_valid_conditional(left_scale, left_val, right_scale, right_val, op_val):
"""
Makes sure the left_scale, left_val, right_scale, right_val, and
operator variables combine into a valid conditional statement
"""
left_val = identify_used_metric(left_val)
right_val = identify_used_metric(right_val)
left_scale = identify_used_metric(left_scale, isnum=True)
right_scale = identify_used_metric(right_scale, isnum=True)
if op_val not in legal_ops:
raise ValueError(f"{op_val} is not a binary comparison operator, like > or <")
return left_scale, left_val, right_scale, right_val
def operator_scale_descript(val_scale, val):
"""
Return a string with one element from the mathematical expression
If val_scale is not 1, include scaling factor (rounded to 2 decimals)
If val is a column in the component_table output the column label
If val is a number (either an inputted number or from cross_component_metrics
include the number (rounded to 2 decimals)
This output is used to great a descriptor for visualizing the decision tree
Unrounded values are saved and rounding here will not affect results
"""
if not isinstance(val, str):
val = str(round(val, 2))
if val_scale == 1:
return val
else:
return f"{round(val_scale,2)}*{val}"
left_scale, left, right_scale, right = confirm_valid_conditional(
left_scale, left, right_scale, right, op
)
descript_left = operator_scale_descript(left_scale, left)
descript_right = operator_scale_descript(right_scale, right)
is_compound = 0
# If any of the values for the second boolean statement are set
if left2 is not None or right2 is not None or op2 is not None:
# Check if they're all set & use them all or raise an error
if left2 is not None and right2 is not None and op2 is not None:
is_compound = 2
left2_scale, left2, right2_scale, right2 = confirm_valid_conditional(
left2_scale, left2, right2_scale, right2, op2
)
descript_left2 = operator_scale_descript(left2_scale, left2)
descript_right2 = operator_scale_descript(right2_scale, right2)
else:
raise ValueError(
"left_op_right can check if a first and second boolean "
"statement are both true. This call includes some but not "
"all variables to define the second boolean statement "
f"left2={left2}, right2={right2}, op2={op2}"
)
# If any of the values for the second boolean statement are set
if left3 or right3 or op3:
if is_compound == 0:
raise ValueError(
"left_op_right is includes parameters for a third conditional "
"(left3, right3, or op3) statement without setting the "
"second statement"
)
# Check if they're all set & use them all or raise an error
if left3 and right3 and op3:
is_compound = 3
left3_scale, left3, right3_scale, right3 = confirm_valid_conditional(
left3_scale, left3, right3_scale, right3, op3
)
descript_left3 = operator_scale_descript(left3_scale, left3)
descript_right3 = operator_scale_descript(right3_scale, right3)
else:
raise ValueError(
"left_op_right can check if three boolean "
"statements are all true. This call includes some but not "
"all variables to define the third boolean statement "
f"left3={left3}, right3={right3}, op3={op3}"
)
if only_used_metrics:
return outputs["used_metrics"]
if custom_node_label:
outputs["node_label"] = custom_node_label
elif is_compound == 0:
outputs["node_label"] = f"{descript_left}{op}{descript_right}"
elif is_compound == 2:
outputs["node_label"] = [
f"{descript_left}{op}{descript_right} & " f"{descript_left2}{op2}{descript_right2}"
]
elif is_compound == 3:
outputs["node_label"] = [
f"{descript_left}{op}{descript_right} & "
f"{descript_left2}{op2}{descript_right2} & "
f"{descript_left3}{op3}{descript_right3}"
]
# Might want to add additional default logging to functions here
# The function input will be logged before the function call
LGR.info(f"{function_name_idx}: {if_true} if {outputs['node_label']}, else {if_false}")
if log_extra_info:
LGR.info(f"{function_name_idx} {log_extra_info}")
if log_extra_report:
RepLGR.info(log_extra_report)
confirm_metrics_exist(
selector.component_table, outputs["used_metrics"], function_name=function_name_idx
)
def parse_vals(val):
"""Get the metric values for the selected components or relevant constant"""
if isinstance(val, str):
return selector.component_table.loc[comps2use, val].copy()
else:
return val # should be a fixed number
if not comps2use:
outputs["n_true"] = 0
outputs["n_false"] = 0
log_decision_tree_step(
function_name_idx,
comps2use,
decide_comps=decide_comps,
if_true=outputs["n_true"],
if_false=outputs["n_false"],
)
else:
left1_val = parse_vals(left) # noqa: F841
right1_val = parse_vals(right) # noqa: F841
decision_boolean = eval(f"(left_scale*left1_val) {op} (right_scale * right1_val)")
if is_compound >= 2:
left2_val = parse_vals(left2) # noqa: F841
right2_val = parse_vals(right2) # noqa: F841
statement1 = decision_boolean.copy()
statement2 = eval(f"(left2_scale*left2_val) {op2} (right2_scale * right2_val)")
# logical dot product for compound statement
decision_boolean = statement1 * statement2
if is_compound == 3:
left3_val = parse_vals(left3) # noqa: F841
right3_val = parse_vals(right3) # noqa: F841
# statement 1 is now the combination of the first two conditional statements
statement1 = decision_boolean.copy()
# statement 2 is now the third conditional statement
statement2 = eval(f"(left3_scale*left3_val) {op2} (right3_scale * right3_val)")
# logical dot product for compound statement
decision_boolean = statement1 * statement2
(
selector,
outputs["n_true"],
outputs["n_false"],
) = change_comptable_classifications(
selector,
if_true,
if_false,
decision_boolean,
tag_if_true=tag_if_true,
tag_if_false=tag_if_false,
)
# outputs["n_true"] = np.asarray(decision_boolean).sum()
# outputs["n_false"] = np.logical_not(decision_boolean).sum()
log_decision_tree_step(
function_name_idx,
comps2use,
n_true=outputs["n_true"],
n_false=outputs["n_false"],
if_true=if_true,
if_false=if_false,
)
selector.tree["nodes"][selector.current_node_idx]["outputs"] = outputs
return selector
@fill_doc
def dec_variance_lessthan_thresholds(
selector,
if_true,
if_false,
decide_comps,
var_metric="variance explained",
single_comp_threshold=0.1,
all_comp_threshold=1.0,
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
tag_if_true=None,
tag_if_false=None,
):
"""Change classifications for components with variance<single_comp_threshold.
If the sum of the variance for all components that meet this criteria
is greater than all_comp_threshold then only change classifications for the
lowest variance components where the sum of their variances is less than
all_comp_threshold
Parameters
----------
%(selector)s
%(tag_if_true)s
%(tag_if_false)s
%(decide_comps)s
var_metric: :obj:`str`
The name of the metric in component_table for variance. Default="variance explained"
This is an option so that it is possible to use "normalized variance explained"
or another metric
single_comp_threshold: :obj:`float`
The threshold for which all components need to have lower variance.
Default=0.1
all_comp_threshold: :obj: `float`
The number of the variance for all components less than single_comp_threshold
needs to be under this threshold. Default=1.0
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
%(tag_if_true)s
%(tag_if_false)s
Returns
-------
%(selector)s
%(used_metrics)s
"""
outputs = {
"decision_node_idx": selector.current_node_idx,
"used_metrics": set([var_metric]),
"node_label": None,
"n_true": None,
"n_false": None,
}
if only_used_metrics:
return outputs["used_metrics"]
function_name_idx = f"Step {selector.current_node_idx}: variance_lt_thresholds"
if custom_node_label:
outputs["node_label"] = custom_node_label
else:
outputs[
"node_label"
] = f"{var_metric}<{single_comp_threshold}. All variance<{all_comp_threshold}"
LGR.info(f"{function_name_idx}: {if_true} if {outputs['node_label']}, else {if_false}")
if log_extra_info:
LGR.info(f"{function_name_idx} {log_extra_info}")
if log_extra_report:
RepLGR.info(log_extra_report)
comps2use = selectcomps2use(selector, decide_comps)
confirm_metrics_exist(
selector.component_table, outputs["used_metrics"], function_name=function_name_idx
)
if not comps2use:
outputs["n_true"] = 0
outputs["n_false"] = 0
log_decision_tree_step(
function_name_idx,
comps2use,
decide_comps=decide_comps,
if_true=outputs["n_true"],
if_false=outputs["n_false"],
)
else:
variance = selector.component_table.loc[comps2use, var_metric]
decision_boolean = variance < single_comp_threshold
# if all the low variance components sum above all_comp_threshold
# keep removing the highest remaining variance component until
# the sum is below all_comp_threshold. This is an inefficient
# way to do this, but it works & should never cause an infinite loop
if variance[decision_boolean].sum() > all_comp_threshold:
while variance[decision_boolean].sum() > all_comp_threshold:
tmpmax = variance == variance[decision_boolean].max()
decision_boolean[tmpmax] = False
(
selector,
outputs["n_true"],
outputs["n_false"],
) = change_comptable_classifications(
selector,
if_true,
if_false,
decision_boolean,
tag_if_true=tag_if_true,
tag_if_false=tag_if_false,
)
log_decision_tree_step(
function_name_idx,
comps2use,
n_true=outputs["n_true"],
n_false=outputs["n_false"],
if_true=if_true,
if_false=if_false,
)
selector.tree["nodes"][selector.current_node_idx]["outputs"] = outputs
return selector
@fill_doc
def calc_median(
selector,
decide_comps,
metric_name,
median_label,
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
):
"""Calculate the median across components for the metric defined by metric_name.
Parameters
----------
%(selector)s
%(decide_comps)s
metric_name: :obj:`str`
The name of a column in selector.component_table. The median of
the values in this column will be calculated
median_label: :obj:`str`
The median will be saved in "median_(median_label)"
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
Returns
-------
%(selector)s
%(used_metrics)s
"""
function_name_idx = f"Step {selector.current_node_idx}: calc_median"
if not isinstance(median_label, str):
raise ValueError(
f"{function_name_idx}: median_label must be a string. It is: {median_label}"
)
else:
label_name = f"median_{median_label}"
if not isinstance(metric_name, str):
raise ValueError(
f"{function_name_idx}: metric_name must be a string. It is: {metric_name}"
)
outputs = {
"decision_node_idx": selector.current_node_idx,
"node_label": None,
label_name: None,
"used_metrics": set([metric_name]),
"calc_cross_comp_metrics": [label_name],
}
if only_used_metrics:
return outputs["used_metrics"]
if label_name in selector.cross_component_metrics:
LGR.warning(
f"{label_name} already calculated. Overwriting previous value in {function_name_idx}"
)
if custom_node_label:
outputs["node_label"] = custom_node_label
else:
outputs["node_label"] = f"Median({label_name})"
LGR.info(f"{function_name_idx}: {outputs['node_label']}")
if log_extra_info:
LGR.info(f"{function_name_idx} {log_extra_info}")
if log_extra_report:
RepLGR.info(log_extra_report)
comps2use = selectcomps2use(selector, decide_comps)
confirm_metrics_exist(
selector.component_table, outputs["used_metrics"], function_name=function_name_idx
)
if not comps2use:
log_decision_tree_step(
function_name_idx,
comps2use,
decide_comps=decide_comps,
)
else:
outputs[label_name] = np.median(selector.component_table.loc[comps2use, metric_name])
selector.cross_component_metrics[label_name] = outputs[label_name]
log_decision_tree_step(function_name_idx, comps2use, calc_outputs=outputs)
selector.tree["nodes"][selector.current_node_idx]["outputs"] = outputs
return selector
@fill_doc
def calc_kappa_elbow(
selector,
decide_comps,
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
):
"""Calculate elbow for kappa across components.
Parameters
----------
%(selector)s
%(decide_comps)s
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
Returns
-------
%(selector)s
%(used_metrics)s
Note
----
This function is currently hard coded for a specific way to calculate the kappa elbow
based on the method by Kundu in the MEICA v2.5 code. This uses the minimum of
a kappa elbow calculation on all components and on a subset of kappa values below
a significance threshold. To get the same functionality as in MEICA v2.5,
decide_comps must be 'all'.
varex_upper_p isn't used for anything in this function, but it is calculated
on kappa values and is used in rho_elbow_kundu_liberal and
dec_reclassify_high_var_comps. For several reasons it made more sense to calculate here.
This also means the kappa elbow should be calculated before those two other functions
are called
"""
outputs = {
"decision_node_idx": selector.current_node_idx,
"node_label": None,
"n_echos": selector.n_echos,
"used_metrics": set(["kappa"]),
"calc_cross_comp_metrics": [
"kappa_elbow_kundu",
"kappa_allcomps_elbow",
"kappa_nonsig_elbow",
"varex_upper_p",
],
"kappa_elbow_kundu": None,
"kappa_allcomps_elbow": None,
"kappa_nonsig_elbow": None,
"varex_upper_p": None,
}
if only_used_metrics:
return outputs["used_metrics"]
function_name_idx = f"Step {selector.current_node_idx}: calc_kappa_elbow"
if ("kappa_elbow_kundu" in selector.cross_component_metrics) and (
"kappa_elbow_kundu" in outputs["calc_cross_comp_metrics"]
):
LGR.warning(
"kappa_elbow_kundu already calculated."
f"Overwriting previous value in {function_name_idx}"
)
if "varex_upper_p" in selector.cross_component_metrics:
LGR.warning(
f"varex_upper_p already calculated. Overwriting previous value in {function_name_idx}"
)
if custom_node_label:
outputs["node_label"] = custom_node_label
else:
outputs["node_label"] = "Calc Kappa Elbow"
LGR.info(f"{function_name_idx}: {outputs['node_label']}")
if log_extra_info:
LGR.info(f"{function_name_idx} {log_extra_info}")
if log_extra_report:
RepLGR.info(log_extra_report)
comps2use = selectcomps2use(selector, decide_comps)
confirm_metrics_exist(
selector.component_table, outputs["used_metrics"], function_name=function_name_idx
)
if not comps2use:
log_decision_tree_step(
function_name_idx,
comps2use,
decide_comps=decide_comps,
)
else:
(
outputs["kappa_elbow_kundu"],
outputs["kappa_allcomps_elbow"],
outputs["kappa_nonsig_elbow"],
outputs["varex_upper_p"],
) = kappa_elbow_kundu(selector.component_table, selector.n_echos, comps2use=comps2use)
selector.cross_component_metrics["kappa_elbow_kundu"] = outputs["kappa_elbow_kundu"]
selector.cross_component_metrics["kappa_allcomps_elbow"] = outputs["kappa_allcomps_elbow"]
selector.cross_component_metrics["kappa_nonsig_elbow"] = outputs["kappa_nonsig_elbow"]
selector.cross_component_metrics["varex_upper_p"] = outputs["varex_upper_p"]
log_decision_tree_step(function_name_idx, comps2use, calc_outputs=outputs)
selector.tree["nodes"][selector.current_node_idx]["outputs"] = outputs
return selector
@fill_doc
def calc_rho_elbow(
selector,
decide_comps,
subset_decide_comps="unclassified",
rho_elbow_type="kundu",
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
):
"""Calculate elbow for rho across components.
Parameters
----------
%(selector)s
%(decide_comps)s
subset_decide_comps: :obj:`str`
This is a string with a single component classification label. For the
elbow calculation used by Kundu in MEICA v.27 thresholds are based
on all components and on unclassified components.
Default='unclassified'.
rho_elbow_type: :obj:`str`
The algorithm used to calculate the rho elbow. Current options are:
'kundu' and 'liberal'. Default='kundu'.
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
Returns
-------
%(selector)s
%(used_metrics)s
Note
----
This script is currently hard coded for a specific way to calculate the rho elbow
based on the method by Kundu in the MEICA v2.5 code. To get the same functionality
in MEICA v2.5, decide_comps must be 'all' and subset_decide_comps must be
'unclassified' See :obj:`tedana.selection.selection_utils.rho_elbow_kundu_liberal`
for a more detailed explanation of the difference between the kundu and liberal
options.
"""
function_name_idx = f"Step {selector.current_node_idx}: calc_rho_elbow"
if rho_elbow_type == "kundu".lower():
elbow_name = "rho_elbow_kundu"
elif rho_elbow_type == "liberal".lower():
elbow_name = "rho_elbow_liberal"
else:
raise ValueError(
f"{function_name_idx}: rho_elbow_type must be 'kundu' or 'liberal' "
f"It is {rho_elbow_type} "
)
outputs = {
"decision_node_idx": selector.current_node_idx,
"node_label": None,
"n_echos": selector.n_echos,
"calc_cross_comp_metrics": [
elbow_name,
"rho_allcomps_elbow",
"rho_unclassified_elbow",
"elbow_f05",
],
"used_metrics": set(["kappa", "rho", "variance explained"]),
elbow_name: None,
"rho_allcomps_elbow": None,
"rho_unclassified_elbow": None,
"elbow_f05": None,
}
if only_used_metrics:
return outputs["used_metrics"]
if (elbow_name in selector.cross_component_metrics) and (
elbow_name in outputs["calc_cross_comp_metrics"]
):
LGR.warning(
f"{elbow_name} already calculated."
f"Overwriting previous value in {function_name_idx}"
)
if custom_node_label:
outputs["node_label"] = custom_node_label
else:
outputs["node_label"] = "Calc Rho Elbow"
LGR.info(f"{function_name_idx}: {outputs['node_label']}")
if log_extra_info:
LGR.info(f"{function_name_idx} {log_extra_info}")
if log_extra_report:
RepLGR.info(log_extra_report)
comps2use = selectcomps2use(selector, decide_comps)
confirm_metrics_exist(
selector.component_table, outputs["used_metrics"], function_name=function_name_idx
)
subset_comps2use = selectcomps2use(selector, subset_decide_comps)
if not comps2use:
log_decision_tree_step(
function_name_idx,
comps2use,
decide_comps=decide_comps,
)
else:
(
outputs[elbow_name],
outputs["rho_allcomps_elbow"],
outputs["rho_unclassified_elbow"],
outputs["elbow_f05"],
) = rho_elbow_kundu_liberal(
selector.component_table,
selector.n_echos,
rho_elbow_type=rho_elbow_type,
comps2use=comps2use,
subset_comps2use=subset_comps2use,
)
selector.cross_component_metrics[elbow_name] = outputs[elbow_name]
selector.cross_component_metrics["rho_allcomps_elbow"] = outputs["rho_allcomps_elbow"]
selector.cross_component_metrics["rho_unclassified_elbow"] = outputs[
"rho_unclassified_elbow"
]
selector.cross_component_metrics["elbow_f05"] = outputs["elbow_f05"]
log_decision_tree_step(function_name_idx, comps2use, calc_outputs=outputs)
selector.tree["nodes"][selector.current_node_idx]["outputs"] = outputs
return selector
@fill_doc
def dec_classification_doesnt_exist(
selector,
new_classification,
decide_comps,
class_comp_exists,
at_least_num_exist=1,
log_extra_report="",
log_extra_info="",
custom_node_label="",
only_used_metrics=False,
tag=None,
):
"""
If there are no components with a classification specified in class_comp_exists,
change the classification of all components in decide_comps.
Parameters
----------
%(selector)s
new_classification: :obj:`str`
Assign all components identified in decide_comps the classification
in new_classification.
%(decide_comps)s
class_comp_exists: :obj:`str` or :obj:`list[str]` or :obj:`int` or :obj:`list[int]`
This has the same structure options as decide_comps. This function tests
whether any components in decide_comps have the classifications defined in this
variable.
at_least_num_exist: :obj:`int`
Instead of just testing whether a classification exists, test whether at least
this number of components have that classification. Default=1
%(log_extra_info)s
%(log_extra_report)s
%(custom_node_label)s
%(only_used_metrics)s
tag: :obj:`str`
A classification tag to assign to all components being reclassified.
This should be one of the tags defined by classification_tags in
the decision tree specification. Default="".
Returns
-------
%(selector)s
%(used_metrics)s
Note
----
This function is useful to end the component selection process early
even if there are additional nodes. For example, in the original
kundu tree, if 0 or 1 components are identified with kappa>elbow and
rho>elbow then, instead of removing everything, it effectively says
something's wrong and conservatively keeps everything. Similarly,
later in the kundu tree, there are several steps deciding how to
classify any remaining provisional components. If none of the
remaining components are "provisionalreject" then it skips those
steps and accepts everything left.
"""
# predefine all outputs that should be logged
outputs = {