-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoh_handle_entries.py
1933 lines (1557 loc) · 59.3 KB
/
coh_handle_entries.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
"""Contains functions and classes for handling entries within objects.
CLASSES
-------
FillerObject
- Empty object that can be filled with attributes that would otherwise not be
accessible as a class attribute.
METHODS
-------
check_lengths_dict_identical
- Checks whether the lengths of entries within a dictionary are identical.
check_lengths_dict_equals_n
- Checks whether the lengths of entries within a dictionary is equal to a
given number.
check_lengths_list_identical
- Checks whether the lengths of entries within a list are identical.
check_lengths_list_equals_n
- Checks whether the lengths of entries within a list is equal to a given
number.
check_repeated_vals
- Checks whether duplicates exist within an input list.
check_matching_entries
- Checks whether the entries of objects match one another.
check_master_entries_in_sublists
- Checks whether all values in a master list are present in a set of sublists.
check_sublist_entries_in_master
- Checks whether all values in a set of sublists are present in a master list.
ordered_list_from_dict
- Creates a list from entries in a dictionary, sorted based on a given order.
ordered_dict_from_list
- Creates a dictionary with keys occurring in a given order.
ragged_array_to_list
- Converts a ragged numpy array of nested arrays to a ragged list of nested
lists.
drop_from_list
- Drops specified entries from a list.
drop_from_dict
- Removes specified entries from a dictionary.
sort_inputs_results
- Checks that the values in 'results' are in the appropriate format for
processing with PostProcess or Plotting class objects.
dict_to_df
- Converts a dictionary into a pandas DataFrame.
"""
from copy import deepcopy
from itertools import chain
from typing import Any, Optional, Union
from numpy.typing import NDArray
import numpy as np
import pandas as pd
from coh_exceptions import (
DuplicateEntryError,
EntryLengthError,
MissingEntryError,
PreexistingAttributeError,
UnidenticalEntryError,
)
class FillerObject:
"""Creates an empty object that can be filled with attributes that would
otherwise not be accessible as a class attribute."""
def _find_lengths_dict(
to_check: dict,
ignore_values: Optional[list] = None,
ignore_keys: Optional[list] = None,
) -> list[int]:
"""Finds the lengths of entries within a dictionary.
PARAMETERS
----------
to_check : dict
- The dictionary for which the lengths of the entries should be checked.
ignore_values : list | None; default None
- The values of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no values are ignored.
ignore_keys : list | None; default None
- The keys of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no keys are ignored.
RETURNS
-------
entry_lengths : list[int]
- The lengths of entries in the list.
"""
if ignore_values is None:
ignore_values = []
if ignore_keys is None:
ignore_keys = []
entry_lengths = []
for key, value in to_check.items():
if key not in ignore_keys or value not in ignore_values:
entry_lengths.append(len(value))
return entry_lengths
def check_lengths_dict_identical(
to_check: dict,
ignore_values: Optional[list] = None,
ignore_keys: Optional[list] = None,
) -> tuple[bool, Union[int, list[int]]]:
"""Checks whether the lengths of entries in the input dictionary are
identical.
PARAMETERS
----------
to_check : dict
- The dictionary for which the lengths of the entries should be checked.
ignore_values : list | None; default None
- The values of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no values are ignored.
ignore_keys : list | None; default None
- The keys of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no keys are ignored.
RETURNS
-------
identical : bool
- Whether or not the lengths of the entries are identical.
lengths : int | list
- The length(s) of the entries. If the lengths are identical,
'lengths' is an int representing the length of all items.
- If the lengths are not identical, 'lengths' is a list containing the
lengths of the individual entries (i.e. 'entry_lengths').
"""
entry_lengths = _find_lengths_dict(
to_check=to_check, ignore_values=ignore_values, ignore_keys=ignore_keys
)
if entry_lengths.count(entry_lengths[0]) == len(entry_lengths):
identical = True
lengths = entry_lengths[0]
else:
identical = False
lengths = entry_lengths
return identical, lengths
def check_lengths_dict_equals_n(
to_check: dict,
n: int,
ignore_values: Optional[list] = None,
ignore_keys: Optional[list] = None,
) -> bool:
"""Checks whether the lengths of entries in the input dictionary are equal
to a given number.
PARAMETERS
----------
to_check : list
- The list for which the lengths of the entries should be checked.
ignore_values : list | None; default None
- The values of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no values are ignored.
n : int
- The integer which the lengths of the entries should be equal to.
RETURNS
-------
all_n : bool
- Whether or not the lengths of the entries are equal to 'n'.
"""
entry_lengths = _find_lengths_dict(
to_check=to_check, ignore_values=ignore_values, ignore_keys=ignore_keys
)
if entry_lengths.count(n) == len(entry_lengths):
all_n = True
else:
all_n = False
return all_n
def _find_lengths_list(
to_check: list, ignore_values: Optional[list], axis: int
) -> list[int]:
"""Finds the lengths of entries within a list.
PARAMETERS
----------
to_check : list
- The list for which the lengths of the entries should be checked.
ignore_values : list | None
- The values of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None, no values are ignored.
axis : int
- The axis of the list whose lengths should be checked.
RETURNS
-------
entry_lengths : list[int]
- The lengths of entries in the list.
"""
if ignore_values is None:
ignore_values = []
entry_lengths = []
for value in to_check:
if value not in ignore_values:
value = np.asarray(value, dtype=object)
entry_lengths.append(np.shape(value)[axis])
return entry_lengths
def check_lengths_list_identical(
to_check: list, ignore_values: Optional[list] = None, axis: int = 0
) -> tuple[bool, Union[int, list[int]]]:
"""Checks whether the lengths of entries in the input list are identical.
PARAMETERS
----------
to_check : list
- The list for which the lengths of the entries should be checked.
ignore_values : list | None; default None
- The values of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no values are ignored.
axis : int | default 0
- The axis of the list whose length should be checked.
RETURNS
-------
identical : bool
- Whether or not the lengths of the entries are identical.
lengths : int | list
- The length(s) of the entries. If the lengths are identical,
'lengths' is an int representing the length of all items.
- If the lengths are not identical, 'lengths' is a list containing the
lengths of the individual entries (i.e. 'entry_lengths').
"""
entry_lengths = _find_lengths_list(
to_check=to_check, ignore_values=ignore_values, axis=axis
)
if entry_lengths.count(entry_lengths[0]) == len(entry_lengths):
identical = True
lengths = entry_lengths[0]
else:
identical = False
lengths = entry_lengths
return identical, lengths
def check_lengths_list_equals_n(
to_check: list, n: int, ignore_values: Optional[list] = None, axis: int = 0
) -> bool:
"""Checks whether the lengths of entries in the input dictionary are equal
to a given number.
PARAMETERS
----------
to_check : list
- The list for which the lengths of the entries should be checked.
n : int
- The integer which the lengths of the entries should be equal to.
ignore_values : list | None; default None
- The values of entries within 'to_check' to ignore when checking the
lengths of entries.
- If None (default), no values are ignored.
axis : int | default 0
- The axis of the list whose lengths should be checked.
RETURNS
-------
all_n : bool
- Whether or not the lengths of the entries are equal to 'n'.
"""
entry_lengths = _find_lengths_list(
to_check=to_check, ignore_values=ignore_values, axis=axis
)
if entry_lengths.count(n) == len(entry_lengths):
all_n = True
else:
all_n = False
return all_n
def unique(values: list) -> list:
"""Finds the unique values in a list in the original order in which the
entries occur in the the original list.
- Similar to calling numpy's 'unique' with 'return_index' set to 'True'
and then reordering the result of numpy's 'unique' to restore the order
in which the unique values occurred in the original list.
PARAMETERS
----------
values : list
- The values whose unique entries should be found.
RETURNS
-------
unique_values : list
- The unique entries in 'values'.
"""
unique_values = []
for entry in values:
if entry not in unique_values:
unique_values.append(entry)
return unique_values
def check_vals_identical_list(
to_check: list,
) -> tuple[bool, Union[list, None]]:
"""Checks whether all values within a list are identical.
PARAMETERS
----------
to_check : list
- The list whose values should be checked.
RETURNS
-------
is_identical : bool
- Whether or not all values within the list are identical.
unique_vals : list | None
- The unique values in the list. If all values are identical, this is
'None'.
"""
is_identical = True
compare_against = to_check[0]
for val in to_check[1:]:
if val != compare_against:
is_identical = False
if is_identical:
unique_vals = None
else:
unique_vals = unique(to_check)
return is_identical, unique_vals
def check_vals_identical_df(
dataframe: pd.DataFrame, keys: list[str], idcs: list[list[int]]
) -> None:
"""Checks that a DataFrame attribute's values at specific indices are
identical.
PARAMETERS
----------
dataframe : pandas DataFrame
- DataFrame containing the values to check.
keys : list[str]
- Names of the attributes in the DataFrame whose values should be checked.
idcs : list[list[int]]
- The indices of the entries in the attributes whose values should be
checked.
- Each entry is a list of integers corresponding to the indices of
the results to compare together.
RAISES
------
UnidenticalEntryError
- Raised if any of the groups of values being compared are not identical.
"""
for key in keys:
for group_idcs in idcs:
if len(group_idcs) > 1:
is_identical, unique_vals = check_vals_identical_list(
to_check=dataframe[key].iloc[group_idcs].tolist()
)
if not is_identical:
raise UnidenticalEntryError(
"Error when checking that the attributes of "
"results belonging to the same group share the "
f"same values:\nThe values of '{key}' in rows "
f"{group_idcs} do not match.\nValues:{unique_vals}\n"
)
def get_eligible_idcs_lists(
to_check: dict[list],
eligible_vals: dict[list],
idcs: Union[list[int], None] = None,
) -> list[int]:
"""Finds indices of items in multiple lists that have a certain value.
- Indices are found in turn for each list, such that the number of
eligible indices can decrease for every list being checked.
PARAMETERS
----------
to_check : dict[list]
- Lists whose values should be checked, stored in a dictionary.
- The keys of the dictionary should be the same as those in
'eligible_vals' for the corresponding eligible values.
eligible_vals : dict[list]
- Lists containing values that are considered 'eligible', and whose
indices will be recorded, stored in a dictionary.
- The keys of the dictionary should be the same as those in 'to_check' for
the corresponding values to be checked.
idcs : list[int] | None; default None
- Indices of the items in the first list of 'to_check' to check.
- If 'None', all items in the first list are checked.
RETURNS
-------
idcs : list[int]
- List containing the indices of 'eligible' entries across all lists.
"""
idcs = deepcopy(idcs)
if idcs is None:
_, length = check_lengths_dict_identical(to_check=to_check)
idcs = np.arange(length).tolist()
for key, value in to_check.items():
if key in eligible_vals.keys():
idcs = get_eligible_idcs_list(
vals=value, eligible_vals=eligible_vals[key], idcs=idcs
)
return idcs
def get_eligible_idcs_list(
vals: list,
eligible_vals: list,
idcs: Union[list[int], None] = None,
) -> list[int]:
"""Finds indices of items in a list that have a certain value.
PARAMETERS
----------
vals : list
- List whose values should be checked.
eligible_vals : list
- List containing values that are considered 'eligible', and whose indices
will be recorded.
idcs : list[int] | None; default None
- Indices of the items in 'to_check' to check.
- If 'None', all items are checked.
RETURNS
-------
list[int]
- List containing the indices of items in 'to_check' with 'eligible'
values.
"""
if idcs is None:
idcs = range(len(vals))
return [idx for idx in idcs if vals[idx] in eligible_vals]
def get_group_names_idcs(
dataframe: pd.DataFrame,
keys: Union[list[str], None] = None,
eligible_idcs: Union[list[int], None] = None,
replacement_idcs: Union[list[int], None] = None,
special_vals: Union[dict[str], None] = None,
keys_in_names: bool = True,
) -> dict[int]:
"""Combines the values of DataFrame columns into a string on a row-by-row
basis (i.e. one string for each row) and finds groups of items containing
these values, returning the names of the groups and their indices.
PARAMETERS
----------
dataframe : pandas DataFrame
- DataFrame whose values should be combined across columns.
keys : list[str] | None
- Names of the columns in the DataFrame whose values should be combined.
- If 'None', all columns are used.
eligible_idcs : list[int] | None
- Indices of the rows in the DataFrame whose values should be combined.
- If 'None', all rows are used.
replacement_idcs : list[int] | None
- List containing indices that the indices of items in 'vals' should be
replaced with.
- Must have the same length as 'vals'.
- E.g. if items in positions 0, 1, and 2 of 'vals' were grouped together
and the values of 'replacement_idcs' in positions 0 to 2 were [2, 6, 9],
respectively, the resulting indices for this group would be [2, 6, 9].
- If None, the original indices are used.
special_vals : dict[str] | None
- Instructions for how to treat specific values in the DataFrame.
- Keys are the special values that the values should begin with, whilst
values are the values that the special values should be replaced with.
- E.g. {"avg[": "avg_"} would mean values in the DataFrame beginning with
'avg[' would have this beginning replaced with 'avg_', followed by the
column name, so a value beginning with 'avg[' in the 'channels' column
would become 'avg_channels'.
keys_in_names : bool; default True
- Whether or not the names of groups should contain the keys to which the
value belong.
RETURNS
-------
group_names_idcs : dict[int]
- Dictionary where each key is the name of the group, and each value the
indices of rows in 'dataframe' corresponding to this group.
"""
combined_values = combine_col_vals_df(
dataframe=dataframe,
keys=keys,
idcs=eligible_idcs,
special_vals=special_vals,
include_keys=keys_in_names,
)
group_idcs, group_names = get_group_idcs(
vals=combined_values, replacement_idcs=replacement_idcs
)
group_names_idcs = {}
for idx, name in enumerate(group_names):
group_names_idcs[name] = group_idcs[idx]
return group_names_idcs
def get_group_idcs(
vals: list, replacement_idcs: Union[list[int], None] = None
) -> tuple[list[list[int]], list]:
"""Finds groups of items in a list containing the same values, and returns
their indices.
PARAMETERS
----------
vals : list
- List containing the items that should be compared.
replacement_idcs : list[int] | None
- List containing indices that the indices of items in 'vals' should be
replaced with.
- Must have the same length as 'vals'.
- E.g. if items in positions 0, 1, and 2 of 'vals' were grouped together
and the values of 'replacement_idcs' in positions 0 to 2 were [2, 6, 9],
respectively, the resulting indices for this group would be [2, 6, 9].
- If None, the original indices are used.
RETURNS
-------
group_idcs : list[list[int]]
- List of lists where each list contains the indices for a group of items
in 'vals' that share the same value.
unique_vals : list
- List of the unique values, corresponding to the groups in 'group_idcs'.
RAISES
------
EntryLengthError
- Raised if 'vals' and 'replacement_idcs' do not have the same length.
"""
if replacement_idcs is None:
replacement_idcs = range(len(vals))
else:
if len(replacement_idcs) != len(vals):
raise EntryLengthError(
"Error when trying to find the group indices of items:\nThe "
"values and replacement indices do not have the same lengths "
f"({len(vals)} and {len(replacement_idcs)}, respectively).\n"
)
unique_vals = unique(vals)
group_idcs = []
for unique_val in unique_vals:
group_idcs.append([])
for idx, val in enumerate(vals):
if unique_val == val:
group_idcs[-1].append(replacement_idcs[idx])
return group_idcs, unique_vals
def reorder_rows_dataframe(
dataframe: pd.DataFrame, key: str, values_order: list
) -> pd.DataFrame:
"""Reorders the rows of a pandas DataFrame based on the order in which
values occur in a given column.
If certain values are not present in the data, they are not included in the
ordering. If no values are present in the data, no ordering is performed.
PARAMETERS
----------
dataframe : pandas DataFrame
- DataFrame to reorder.
key : str
- Name of the column of the DataFrame to use for the reordering.
values_order : list
- Values in the column of the DataFrame used for the reordering. The order
in which values occur in 'values_order' determines the order in which
the DataFrame rows are reordered.
RETURNS
-------
dataframe : pandas DataFrame
- Reordered DataFrame.
"""
unique_values = np.unique(dataframe[key].tolist())
remove_values = []
for value in values_order:
if value not in unique_values:
remove_values.append(value)
values_order = [val for val in values_order if val not in remove_values]
for value in unique_values:
if value not in values_order:
values_order.append(value)
if values_order != []:
dataframe = deepcopy(dataframe)
dataframe = dataframe.set_index(key).loc[values_order].reset_index()
return dataframe
def combine_col_vals_df(
dataframe: pd.DataFrame,
keys: Union[list[str], None] = None,
idcs: Union[list[int], None] = None,
special_vals: Union[dict[str], None] = None,
joiner: str = " & ",
include_keys: bool = True,
) -> list[str]:
"""Combines the values of DataFrame columns into a string on a row-by-row
basis (i.e. one string for each row).
PARAMETERS
----------
dataframe : pandas DataFrame
- DataFrame whose values should be combined across columns.
keys : list[str] | None
- Names of the columns in the DataFrame whose values should be combined.
- If 'None', all columns are used.
idcs : list[int] | None
- Indices of the rows in the DataFrame whose values should be combined.
- If 'None', all rows are used.
special_vals : dict[str] | None
- Instructions for how to treat specific values in the DataFrame.
- Keys are the special values that the values should begin with, whilst
values are the values that the special values should be replaced with.
- E.g. {"avg[": "avg_"} would mean values in the DataFrame beginning with
'avg[' would have this beginning replaced with 'avg_', followed by the
column name, so a value beginning with 'avg[' in the 'channels' column
would become 'avg_channels'.
joiner : str; default " & "
- String to join each entry for a given row with.
include_keys : bool; default True
- Whether or not the names of groups should contain the keys to which the
values belong.
RETURNS
-------
combined_vals : list[str]
- The values of the DataFrame columns combined on a row-by-row basis, with
length equal to that of 'idcs'.
"""
if keys is None:
keys = dataframe.keys().tolist()
if idcs is None:
idcs = dataframe.index.tolist()
if special_vals is None:
special_vals = {}
combined_vals = []
for entry_i, row_i in enumerate(idcs):
combined_vals.append("")
for key in keys:
value = str(dataframe[key].iloc[row_i])
if include_keys:
value = f"{key}-{value}"
for to_replace, replacement in special_vals.items():
start_i = len(f"{key}-")
end_i = start_i + len(to_replace)
if value[start_i:end_i] == to_replace:
value = f"{replacement}{key}"
combined_vals[entry_i] += f"{value}{joiner}"
combined_vals[entry_i] = combined_vals[entry_i][: -len(joiner)]
return combined_vals
def combine_vals_list(
obj: list,
idcs: Union[list[int], None] = None,
special_vals: Union[dict[str], None] = None,
joiner: str = " & ",
) -> str:
"""Combines the values of DataFrame columns into a string on a row-by-row
basis (i.e. one string for each row).
PARAMETERS
----------
obj : list
- List whose values should be combined.
idcs : list[int] | None
- Indices of the values that should be combined.
- If 'None', all values are used.
special_vals : dict[str] | None
- Instructions for how to treat specific values in the list.
- Keys are the special values that the values should begin with, whilst
values are the values that the special values should be replaced with.
- E.g. {"avg[": "avg_"} would mean values in the list beginning with
'avg[' would have this beginning replaced with 'avg_', followed by the
column name, so a value beginning with 'avg[' in the 'channels' column
would become 'avg_channels'.
joiner : str; default " & "
- String to join each value with.
RETURNS
-------
combined_vals : str
- The values of the list combined into a single string.
"""
if idcs is None:
idcs = np.arange(len(obj))
if special_vals is None:
special_vals = {}
combined_vals = ""
for val_i, val in enumerate(obj):
if val_i in idcs:
for to_replace, replacement in special_vals.items():
if val[: len(to_replace)] == to_replace:
val = replacement
combined_vals += f"{val}{joiner}"
return combined_vals[: -len(joiner)]
def separate_vals_string(obj: str, separate_at: str) -> list[str]:
"""Splits a string into substrings based on the occurrence of characters
within the string, printing a warning if no separation takes place.
PARAMETERS
----------
obj : str
- The string to separate.
separate_at : str
- Characters in the string to split the data at.
- E.g. if 'separate_at' were " & ", the string "one & two" would be split
into two strings: "one" and "two".
RETURNS
-------
separated_vals : list[str]
- The string split into substrings.
"""
separated_vals = []
start_i = 0
while True:
separate_i = obj.find(separate_at, start_i)
if separate_i == -1:
separated_vals.append(obj[start_i:])
break
separated_vals.append(obj[start_i:separate_i])
start_i = separate_i + len(separate_at)
if len(separated_vals) == 1:
print(
"Warning: The string was not split into multiple substrings, as no "
f"occurrence of '{separate_at}' within the input string was found."
)
return separated_vals
def rearrange_axes(
obj: Union[list, NDArray], old_order: list[str], new_order: list[str]
) -> Union[list, NDArray]:
"""Rearranges the axes of an object.
PARAMETERS
----------
obj : list | numpy array
- The object whose axes should be rearranged.
old_order : list[str]
- Names of the axes in 'obj' in their current positions.
new_axes : list[str]
- Names of the axes in 'obj' in their desired positions.
RETURNS
-------
list | numpy array
- The object with the rearranged axis order.
"""
return np.transpose(obj, [old_order.index(dim) for dim in new_order])
def check_repeated_vals(
to_check: list,
) -> tuple[bool, Optional[list]]:
"""Checks whether repeated values exist within an input list.
PARAMETERS
----------
to_check : list
- The list of values whose entries should be checked for repeats.
RETURNS
-------
repeats : bool
- Whether or not repeats are present.
repeated_vals : list | None
- The list of repeated values, or 'None' if no repeats are present.
"""
seen = set()
seen_add = seen.add
repeated_vals = list(
set(val for val in to_check if val in seen or seen_add(val))
)
if not repeated_vals:
repeats = False
repeated_vals = None
else:
repeats = True
return repeats, repeated_vals
def check_non_repeated_vals_lists(
lists: list[list], allow_non_repeated: bool = True
) -> bool:
"""Checks that each list in a list of lists contains values which also
occur in each and every other list.
PARAMETERS
----------
lists : list[lists]
- Master list containing the lists whose values should be checked for
non-repeating values.
allow_non_repeated : bool; default True
- Whether or not to allow non-repeated values to be present. If not, an
error is raised if a non-repeated value is detected.
RETURNS
-------
all_repeated : bool
- Whether or not all values of the lists are present in each and every
other list.
RAISES
------
MissingEntryError
- Raised if a list contains a value that does not occur in each and every
other list and 'allow_non_repeated' is 'False'.
"""
compare_list = lists[0]
all_repeated = True
checking = True
while checking:
for check_list in lists[1:]:
non_repeated_vals = [
val for val in compare_list if val not in check_list
]
non_repeated_vals.extend(
[val for val in check_list if val not in compare_list]
)
if non_repeated_vals:
if not allow_non_repeated:
raise MissingEntryError(
"Error when checking whether all values of a list are "
"repeated in another list:\nThe value(s) "
f"{non_repeated_vals} is(are) not present in all "
"lists.\n"
)
else:
all_repeated = False
checking = False
checking = False
return all_repeated
def check_matching_entries(objects: list) -> bool:
"""Checks whether the entries of objects match one another.
PARAMETERS
----------
objects : list
- The objects whose entries should be compared.
RETURNS
-------
matching : bool
- If True, the entries of the objects match. If False, the entries do not
match.
RAISES
------
EntryLengthError
- Raised if the objects do not have equal lengths.
"""
equal, length = check_lengths_list_identical(objects)
if not equal:
raise EntryLengthError(
"Error when checking whether the entries of objects are "
f"identical:\nThe lengths of the objects ({length}) do not "
"match."
)
checking = True
matching = True
while checking and matching:
object_i = 1
for entry_i, base_value in enumerate(objects[0]):
for object_values in objects[1:]:
object_i += 1
if object_values[entry_i] != base_value:
matching = False
checking = False
checking = False
return matching