-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfileutilities.py
1568 lines (1381 loc) · 67.1 KB
/
fileutilities.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
#!/usr/bin/env python3
"""fileutilities.py
Author: Kimon Froussios
Compatibility tested: python 3.5.2
Last reviewed: 10/05/2019
This module is a solution for Frequently Performed Generic Tasks that involve
multiple files:
* repeating a command for a range of files (not currently parallelized),
* accessing and restructuring (multiple) delimited files.
* miscellaneous stuff. Some of it is auxiliary to the primary functions, some
is a legacy of this module's evolution of concept.
The module provides a library of flexible functions as
well as a main() implementing the primary use scenarios.
Execute with -h in a shell to obtain syntax and help.
"""
# This module consists of:
# - a class for handling lists of files,
# - a library of functions that perform generic tasks on multiple files, and
# - a main that provides access to most of the above functionality
# NOTE about DataFrame indexes and headers:
# Although dataframes support row and column labels, these make content manipulations
# in the context of this module harder. Instead, any labels present in the text
# input are treated as plain rows or columns. These may be optionally dropped or
# preserved, but the dataframe in-built labels for columns and rows are reserved
# solely for custom use. When appropriate these custom labels will be included in
# the output.
import os, sys, string, re, subprocess, random, argparse
import pandas as pd
from builtins import list
from collections import Counter
import mylogs as ml
##### F U N C T I O N S #####
# http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort
def natural_sorted(l):
"""Sort list of numbers/strings in human-friendly order.
Args:
l(list): A list of strings.
Returns:
list
"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
def expand_fpaths(flist):
"""Fully expand and absolute-ify the paths of listed files.
Does not verify path validity. All paths are expanded.
Args:
flist[str]: A list/FilesList of files.
Returns:
[str]: List of expanded paths.
"""
return [os.path.abspath(os.path.expanduser(str(f))) for f in flist]
# Helper function, string check.
def istext(s):
"""Check if a string is (probably) text.
Use heuristic based on characters contained in the string, adapted from:
http://code.activestate.com/recipes/173220-test-if-a-file-or-string-is-text-or-binary/
Args:
s(str): A string to test.
Returns:
bool
"""
# Copy-pasted. No idea what the code means.
text_characters = "".join(list(map(chr, list(range(32, 127)))) + list("\n\r\t\b"))
_null_trans = string.maketrans("", "")
if "\0" in s:
return False
if not s: # Empty files/strings are considered text
return True
# Get the non-text characters (maps a character to itself then
# use the 'remove' option to get rid of the text characters.)
t = s.translate(_null_trans, text_characters)
# If more than 30% non-text characters, then
# this is considered a binary file
if float(len(t))/float(len(s)) > 0.30:
return False
return True
def slink(flist, aliases=None, dir="./", autoext=True):
"""Create symbolic links for multiple files.
Create a link for each of the listed paths into the specified directory,
using the specified aliases. Items in the lists will be matched one for
one.
If the aliases argument is omitted, the names for the links will be drawn
from the aliases attribute of the paths list, if it is a FilesList object.
If no aliases exist in either form, the files will be linked in the current
or specified directory, using names their current basename.
If linking to files of the same name located in different directories, a
number will be automatically suffixed to the basename.
Args:
flist[str]: A list/FilesList of paths to link to.
aliases[str]: A list of respective names for the created links. If
omitted, the alias attribute of the flist argument will be
used, and failing that, the existing basenames will be used.
dir(str): The path to the directory in which the links should be
placed. (Default "./")
autoext(bool): Add the file extensions to the created links, if the
links are created from aliases that lack them.
(Default True)
"""
if not aliases:
# No link names provided. Try to find them elsewhere or create them.
try:
# flist is a FilesList and has the aliases attribute.
aliases = flist.aliases
except AttributeError:
# flist is a plain list, so compute the link name from the file name.
aliases = [os.path.basename(p) for p in flist]
# Check for duplicate aliases and amend them.
# This applies mainly to link names automatically created from filenames, as
# the same file name can exist in different directories.
if len(set(aliases)) < len(flist):
aliases = autonumerate(aliases)
# Add extensions where necessary, if desired.
if autoext:
for i in range(0, len(flist)):
(b, p) = os.path.splitext(flist[i])
c = p
# If it's a .gz, include the next nested extension as well.
if p == ".gz":
p = os.path.splitext(b)[1] + p
# Don't duplicate the extension if the alias already has it.
a = os.path.splitext(aliases[i])[1]
if c != a:
aliases[i] = aliases[i] + p
# Link.
for i, mypath in enumerate(flist):
os.symlink(mypath, os.path.join(dir, aliases[i]))
# Helper function.
def autonumerate(things):
"""Detect duplicate entries in a string list and suffix them.
Suffixes are in _N format where N a natural number >=2. Existing suffixes
in that format will also be detected and incremented.
Args:
things[str]: A list of strings.
Returns:
[str]: A corrected list of strings.
"""
# c = Counter(things);
# # Because I use decrement, reversing the list ensures first instance gets smallest number.
# things.reverse()
# for i, t in enumerate(things):
# n = c[t]
# if n > 1: # The first occurrence is not suffixed.
# newname = t +'_' + str(n)
# while newname in things: # Check for already present suffixes
# n += 1
# newname = t +'_' + str(n)
# things[i] = newname
# c[t] -= 1
# things.reverse()
return things
# Only for this copy of fileutilities. Enumerating inadvertantly messes up filenames when a sample is used in muliple substractions.
# The option for verbatim alias fields was added to newer versions I think but I do not want to update version and risk breaking anything from other changes.
def make_names(items, parameters):
"""Automatically create file names based on parameters.
If automatic names happen to turn out identical with one another, unique
numbers are appended to differentiate them. Check documentation for
autonumerate().
Args:
items[str]: A list of strings/filenames/paths to use as the basis for
the output names.
parameters(str,str,str): The first element is the output directory,
the second is a common prefix to add to the names,
the third is a common suffix to add to the names.
Like so: <out[0]>/<out[1]>item<out[2] .
If any of the 3 values in None, no outnames will be made.
Use current directory and empty strings as necessary.
Returns:
[str]: A list of file paths.
"""
outfiles = []
if None not in parameters:
for i in items:
outfiles.append(os.path.join(os.path.abspath(os.path.expanduser(parameters[0])),
parameters[1] + i + parameters[2]) )
autonumerate(outfiles)
return outfiles
def do_foreach(flist, comm, progress=True, out=(None,None,None), log=False):
"""Execute an arbitrary command for each of the listed files.
Enables executing a shell command over a range of items, by inserting the
item values into the command as directed by place-holder substrings.
Although the above is how it is meant to be used, the values in the
FilesList could be overridden to be any arbitrary string, in which case,
only {val} will have the desired effect. The other placeholder values are
computed with the assumption of the values being files, so may not be
sensible when the items are not files.
This is the only function with comments or progress attributes, because
invoked commands print their own output directly, so any informative messages
controlled by this library will need to be inserted in real time.
Args:
flist[]: A FilesList.
comm[str]: The components of an arbitrary command, with place-holders:
{abs} : absolute path of file.
{dir} : absolute path of the file's directory.
{val} : the actual value specified as target
{bas} : the basename of the file, without the last extension.
{alias}: the alias for the file, if iterating through a FilesList.
Placeholders can be nested, to allow nested calls of fileutilities:
i.e. {{abs}}. A layer of nesting is peeled off each time the function is called,
until the placeholders are allowed to be evaluated.
progress(bool): Show start and completion of iterations on STDERR.
(Default True)
out(str,str,str): The first element is the output directory, the second
is a common prefix to add to the names, the third is a
common suffix to add to the names. Check documentation for
make_names().
log(bool): Log to /commands.log each individual call.
"""
outstream= sys.stdout
# Create output files. [] if out contains None.
outfiles = make_names(flist, out)
for i, (myfile, myalias) in flist.enum():
# Substitute place-holders.
command = []
for c in comm:
# Evaluate placeholders, if they are not nested.
(mypath, mybase) = os.path.split(str(myfile))
c = re.sub(r"(?<!\{){abs}(?!\})", str(myfile), c)
c = re.sub(r"(?<!\{){dir}(?!\})", mypath, c)
c = re.sub(r"(?<!\{){val}(?!\})", mybase, c)
c = re.sub(r"(?<!\{){bas}(?!\})", os.path.splitext(mybase)[0], c)
c = re.sub(r"(?<!\{){ali}(?!\})", str(myalias), c)
# Peel off a layer of nesting for the remaining placeholders and flags.
c = c.replace('{{abs}}', '{abs}')
c = c.replace('{{dir}}', '{dir}')
c = c.replace('{{val}}', '{val}')
c = c.replace('{{bas}}', '{bas}')
c = c.replace('{{ali}}', '{ali}')
c = c.replace(',-', '-')
# This argument is ready to go now.
command.append(c)
# Redirect output.
if outfiles:
outstream = open(outfiles[i], 'w')
# Verbose stuff.
see = " ".join(command)
if log:
ml.log_message(message=see, logfile="./commands.log")
if progress:
sys.stderr.write(ml.infostring("DO: "+ see))
# Do the thing.
subprocess.call(" ".join(command), stdout=outstream, shell=True)
# More verbose stuff.
if progress:
sys.stderr.write(ml.infostring("Finished: "+ str(myalias) +"\n"))
if outfiles:
outstream.close()
def swap_strFiles(flist, insep=[","], outsep="\t"):
"""Replace the column separator with a different one.
Supports multiple different delimiters in the input, to support one-step
uniformity when the input files have different delimiters, but ALL input
will be split at ALL/ANY occurring delimiters. If the delimiter of one
file is present in a different use in an other file, the output may not
be what you want.
Although made for converting delimited text, inseps and outsep could be any
substring in a text, delimited or not.
Args:
flist: A list/FilesList of delimited text files.
insep[str]: A list of regex strings. (Default [","])
outsep(str): New column separator. (Default "\t")
Returns:
[str]: A list of strings with the changed delimiters. One string per
file. It is up to you to decide what to do with the new
strings. The order of strings is the same as the input.
"""
input = []
if flist == []:
# Read all data from STDIN at once. Input[] gets a single entry.
input.append(sys.stdin.read())
else:
# Read in all the files entirely. Input[] gets as many entries as there are files.
for myfile in flist:
with open(myfile) as f:
input.append(f.read())
return swap_substr(input, insep, outsep)
# Helper function
def swap_substr(slist, insep=[","], outsep="\t"):
"""Replace all occurrences of insep with outsep.
Insep may be a regex.
Args:
slist[str]: A list of strings.
insep[str]: A list of regex strings. (Default [","])
outsep(str): New substring. (Default "\t")
Returns:
[str]: A list of the edited strings. The order of the strings is the
same as the input.
"""
rx = re.compile("|".join(insep), re.MULTILINE)
result = []
for s in slist:
# Replace all delimiters with the new one.
result.append(rx.sub(outsep, s))
return result
def prepare_df(df, myalias="", keyCol=None, keyhead="row_ID", header=False, cols=None, appendNum=True):
"""Prepare row names and column names.
Assign column as row labels, rename columns based on their position and an
arbitrary alias name for the dataframe, drop the first row.
Args:
df(pandas.DataFrame): A dataframe.
myalias(str): The basename for the relabelling.
header(bool): Remove first row (Default False).
keyCol(int): Column to be used as row index. If None, no index will be
used. (Default None)
keyhead(str): Label for the index.
cols[int]: Custom index numbers for the columns (Default None). If None
then their current index positions are used.
appendNum(bool): Append the columns' positional indices to the alias
when making the new names (True).
Returns:
pandas.DataFrame
"""
# Set row labels.
if keyhead is None:
keyhead = "row_ID"
if keyCol is not None:
# Add index without dropping it, so as not to affect column positions.
df.set_index(df.columns.values.tolist()[keyCol], inplace=True, drop=False)
df.index.name = str(keyhead)
# Make custom column labels, based on alias and column position.
if not cols:
cols = list(range(0, df.shape[1]))
labels = []
if appendNum:
labels = [str(myalias) +"_|"+ str(i) for i in cols]
else:
labels = [str(myalias) for i in cols]
df.columns = labels
# Remove header.
if header:
df.drop(df.index.values.tolist()[0], axis=0, inplace=True)
return df
def count_columns(flist=[None], colSep=["\t"]):
"""Determine the number of fields in each file by inspecting the first row.
Args:
flist: A list of FilesList of files.
colSep[str]: A list of characters used to separate columns.
Returns:
[int]: A list, in the same order as the given files.
"""
tokenizer = re.compile("|".join(colSep))
counts = []
for file in flist:
f = None
if file is None:
f = sys.stdin
file = "<STDIN>"
else:
f = open(file)
while True:
line = f.readline()
# Skip comments.
if line[0] != "#":
counts.append(len( tokenizer.split(line.rstrip()) ))
break
f.readline
if f != sys.stdin:
f.close()
return counts
def get_valuesSet(flist=[None], axis='r', index=0, filter='a', colSep=["\t"]):
""""List the set of different values in the column(s)/row(s).
Args:
flist: A list of FilesList of files.
colSep[str]: A list of characters used to separate columns.
index: Position index of the required column/row.
axis(str): Data slice orientation - 'r' for row, 'c' for column.
filter(str): non redundant set of: 'a' - all, 'u' - unique, 'r' -
repeated values.
Returns:
[[]]: A list of lists. The inner lists represent the sets in order as
requested.
Raises:
ValueError: Invalid axis or filter values.
"""
tokenizer = "|".join(colSep)
result = []
if flist == []:
# Use None as a flag to read from STDIN
flist.append(None)
# Test if it is a FilesList or plain list. Upgrade it if it's plain.
# It will have at least one entry for sure by now, either way.
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Main part of this function.
results = []
for f, (myfile, myalias) in flist.enum():
# Input.
df = None
instream = sys.stdin
if myfile is not None:
instream = open(myfile)
df = pd.read_csv(instream, sep=tokenizer, header=None, index_col=None, comment="#", engine='python')
if instream != sys.stdin:
instream.close()
# Get value set.
values = None
if axis == 'r':
values = df.iloc[int(index),:].tolist()
elif axis == 'c':
values = df.iloc[:,int(index)].tolist()
else:
raise ValueError("".join(["Unrecognized option: axis=", axis]))
# Get count per value
c = Counter(values);
# Filter.
if filter == 'a':
results.append( set(values) )
elif filter == 'u':
results.append( set([v for v in values if c[v] == 1]) ) # set() is redundant but keeps output type consistent
elif filter == 'r':
results.append( set([v for v in values if c[v] > 1]) )
else:
raise ValueError("".join(["Unrecognized option: filter=", filter]))
return results
def get_columns(flist=[None], cols=[0], colSep=["\t"], header=False, index=None, merge=True):
"""Obtain the specified columns.
Comment lines starting with '#' are ignored.
The data columns are assembled into a single DataFrame.
The returned columns will be labeled based on the name of the file they
came from and their position in it. Existing labels are optionally
preserved as the top row or can be skipped entirely.
If an index is specified, it will be used only for merging, and will NOT be
included in the output columns, unless explicitly present in cols[].
Args:
flist: A list/FilesList of delimited plain text files.
header(bool): Crop the header line (first non-comment line). (Default False)
cols[int/str] : A list of positional indexes or names or ranges of the
desired columns. (Default [0]).
colSep[str]: List of characters used as field separators.
(Default ["\t"]).
merge(bool): Concatenate results from all files into a single
dataframe. If False, a list of dataframes is returned
instead. (Default True).
index(int): Column to be used as row index for merging. (Default None)
Returns:
[pandas.DataFrame]: List of DataFrames. If merge=True, only the
first element will be populated.
"""
tokenizer = "|".join(colSep)
result = []
if flist == []:
# Use None as a flag to read from STDIN
flist.append(None)
# Test if it is a FilesList or plain list. Upgrade it if it's plain.
# It will have at least one entry for sure by now, either way.
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Parse.
keyhead = None
for f, (myfile, myalias) in flist.enum():
# I used to use the pandas parser, with my own parser used only as fallback
# for problematic cases. As flexibility requirements increased, using the
# pandas parser became too opaque and difficult to maintain,
# so now all cases are delegated to mine.
df = get_columns_manual(myfile, cols=cols, colSep=colSep, header=header,
alias=myalias, index=index)
if not keyhead:
keyhead = df.index.name
result.append(df)
# Merge.
if merge:
result = [pd.concat(result, axis=1, join='outer', ignore_index=False, sort=False), ]
result[0].index.name = keyhead
return result
# Helper function
def get_columns_manual(file=None, cols=[0], colSep=["\t"], header=False, index=None, alias=None):
"""Get specified columns from a file where rows have varying numbers of fields.
Some tables contain a fixed set of fields followed by optional fields. In
these rare cases, traditional parsers fail due to inconsistent number of
fields. This function provides a work-around for that.
It is entirely the user's responsibility to ensure that the inconsistent
row lengths are not a symptom of table corruption/malformation and that it
is safe and reliable to extract the desired columns. If a row is shorter
than expected, it is padded with the value "IDXERROR". If this value shows
up in your result and you are not explicitly expecting it, you should stop
and seriously examine your input table.
Args:
file(str): A delimited plain text file.
header(bool): If True, the first non-comment line will not be in
the data. (Default False)
cols[int]: A list of positional indexes of the desired columns.
(Default [0]).
colSep[str]: List of regex strings for field separators.
(Default ["\t"]).
index(int): Position of column to be used as row index. (Default None)
alias(str): An alias for the file. Used for naming the columns.
Returns:
pandas.DataFrame: DataFrame with the columns, labeled by original
column number, ordered as specified.
"""
tokenizer = re.compile("|".join(colSep))
# Input source.
f = None
if file is None:
f = sys.stdin
file = "STDIN"
else:
f = open(file)
if alias is None:
alias = FilesList.autoalias(file)
# Import data.
keyhead = None
values = []
labels = []
for l, line in enumerate(f):
if line[0] == '#' or line == "\n":
# Skip comments and empty lines.
continue
else:
# Get the fields.
fields = tokenizer.split(line.rstrip("\n"))
# Column labels from the first non-comment non-empty row,
# regardless of whether they really are labels or not.
if not labels:
labels = fields
# Find out name of row index.
if (not keyhead) and header and (index is not None):
keyhead = str(fields[index])
# Get columns.
selection = []
expandedcols = []
for c in cols:
v = str(c).split(":")
if len(v) == 1:
try:
expandedcols.append(int(v[0]))
except ValueError:
expandedcols.append(labels.index(v[0]))
else:
try:
expandedcols.extend(list(range(int(v[0]), int(v[1]) + 1)))
except TypeError:
expandedcols.extend(list(range(labels.index(v[0]), labels.index(v[1]) + 1)))
for i in expandedcols:
try:
selection.append(fields[i])
except IndexError:
# Silently adding fields is too dangerous, so a flag value is needed.
# Values like None or NA can sometimes be legitimate values for fields.
selection.append("IDXERROR")
# Add the key at the end, where they won't interfere with column numbers.
if index is not None:
selection.append(fields[index])
values.append(selection)
if f != sys.stdin:
f.close()
# Adjust index of row keys to reflect the fact I stuck them at the end.
if index is not None:
index = len(values[0])-1
expandedcols.append("my_garbage_label_row_key")
# Package data nicely.
df = pd.DataFrame(data=values)
df.astype(str, copy=False) # Uniform string type is simplest and safest.
df = prepare_df(df, myalias=alias, keyCol=index, header=header, cols=expandedcols,
keyhead=keyhead, appendNum=True if len(expandedcols)>1 else False)
if index is not None:
df.drop(alias+"_|my_garbage_label_row_key", 1, inplace=True)
return df
def get_random_columns(flist, colSep=["\t"], k=1, header=False, index=None, merge=True):
""" Get k random columns from each file.
The returned columns will be labeled based on the name of the file they
came from and their position in it. Existing labels are optionally
preserved as the top row or can be skipped entirely.
If an index is specified, it will be used for merging (if applicable) and
will be included as a column in each output file.
Args:
flist: A list or FilesList of files.
k(int): How many columns to get.
colSep[str]: A list of characters used as field separators.
(Default ["\t"])
header(bool): Strip column headers. (Default False)
index(int): Column to use as row index for merging. (Default None)
merge(bool): Concatenate results from all files into a single
dataframe. If False, a list of dataframes is returned
instead. (Default True).
Returns:
[pandas.DataFrame]: List of DataFrames. If merge=True, only the
first element will be populated.
"""
tokenizer = "|".join(colSep)
# The files may have different number of columns
fieldNums = count_columns(flist, colSep)
result = []
if flist == []:
# Use None as a flag to read from STDIN
flist.append(None)
keyhead = None
# Test if it is a FilesList or plain list. Upgrade it if it's plain.
# get_columns() does this too, but as I call it per item in flist, I *must*
# preserve any alias that is potentially already specified.
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Get columns.
for f, (myfile, myalias) in flist.enum():
cols = []
if index is not None:
# Generate random choice of columns.
# range() is right-open.
cols.extend(random.sample(list(range(0, fieldNums[f]-1)), k))
else:
cols = random.sample(list(range(0,fieldNums[f])), k)
# Would normally delegate the actual getting to get_columns() but there
# are too many little differences to accommodate that complicate the code
# to the point of defeating any benefits from code re-use.
df = pd.read_csv(myfile, sep=tokenizer, header=None, index_col=None, comment="#", engine='python')
if (not keyhead) and header and (index is not None):
keyhead = str(df.iloc[0,index])
# Adjust row and column labels.
df = prepare_df(df, myalias=myalias, keyCol=index, header=header, keyhead=keyhead,
appendNum=True if k>1 else False)
# Slice the part I need.
df = df.iloc[:,cols]
result.append(df)
# Merge.
if merge:
result = [pd.concat(result, axis=1, join='outer', ignore_index=False)]
result[0].index.name = keyhead
return result
def append_columns(flist, colSep=["\t"], header=False, index=None, merge=True, type='outer'):
"""Append all columns from the files, as they are.
Inner or outer concatenation by a unique index, or index-less concatenation.
Ideally used with a unique index and for only for same-length files.
Args:
flist: A list/FilesList of files to combine.
colSep[str]: A list of characters used as field delimiters.
(Default ["\t"])
header(bool): First non-comment line as column labels. (Default False)
index(int): Column to use as row index (same in all files).
(Default None)
If None, the number of rows can differ between files and will be
padded (outer) or truncated (inner), otherwise the row number must
be the same in all files.
type(str): Join type 'inner' or 'outer'.
Returns:
pandas.Dataframe
"""
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Determine how many columns each file has.
numofcols = count_columns(flist, colSep=colSep)
# Delegate fetching all the columns.
data = []
keyhead = None
for f, (myfile, myalias) in flist.enum():
# List the columns and remove the index one from among them.
cols = [i for i in range(0,numofcols[f]) if i != index]
df =get_columns(FilesList(files=[myfile], aliases=[myalias]), cols=cols,
colSep=colSep, header=header, merge=False, index=index)[0]
data.append( df )
# Merge. Row indexes will have been assigned by get_columns(), if applicable.
keyhead = data[0].index.name
result = pd.concat(data, axis=1, join=type, ignore_index=False, sort=False)
result.index.name = keyhead
return result
def merge_tables(flist, colSep=["\t"], header=False, index=0, merge=True, type='outer', saveHeader=False, dedup=True):
"""Incrementally merge tables.
Join the first two files and then join the third file to the merged first two, etc.
For assymetric joins (left or right) the order of files in flist can change the outcome.
For symmetric joins (inner or outter) the order of files should not change the outcome.
Args:
flist: A list/FilesList of files to combine.
colSep[str]: A list of characters used as field delimiters.
(Default ["\t"])
header(bool): Crop first non-comment line as column labels. (Default False)
index(int): Column to use as row index (same in all files).
(Default 0)
type(str): 'left', 'right', 'outer' or 'inner' merge. (Default outer)
saveHeader(bool): Exclude the first row from sorting upon merging. (False)
Necessary when the header is not to be cropped.
dedup(bool): Remove repeated index columns (one per file).
Returns:
pandas.Dataframe
"""
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Determine how many columns each file has.
numofcols = count_columns(flist, colSep=colSep)
# Fetch and incrementally merge.
result = None
for f, (myfile, myalias) in flist.enum():
# List the columns and remove the index one from among them.
cols = [i for i in range(0,numofcols[f])]
df = get_columns(FilesList(files=[myfile], aliases=[myalias]), cols=cols,
colSep=colSep, header=header, merge=False, index=index)[0]
if (f == 0):
result = df
else:
if saveHeader:
# Extract headers, merge headers and tables separately, then put merged header on top of the merged table.
hnew = pd.merge(left=result.iloc[[0]], right=df.iloc[[0]], sort=False,
left_index=True, right_index=True, how="outer")
result = pd.concat([hnew, pd.merge(left=result.iloc[1:,:], right=df.iloc[1:,:], how=type, on=None,
left_index=True, right_index=True,
sort=False, suffixes=('','_'+ myalias))],
axis=0, ignore_index=False, sort=False)
else:
result = pd.merge(left=result, right=df, how=type, on=None,
left_index=True, right_index=True,
sort=False, suffixes=('','_'+ myalias))
# In addition to the new row_ID columns, the index column was kept for each table. Drop them as redundant.
# If the index columns are not exact duplicates (due to gappy rows),
# dedup_columns can be used afterwards on the merged file).
if dedup:
index_cols = [col for col in result.columns if '_|' + str(index) in col]
result.drop(columns=index_cols, inplace=True)
return result
# Helper function
def getDuplicateColumns(df):
'''
Get a list of duplicate columns.
It will iterate over all the columns in dataframe and find the columns whose contents are duplicate.
Stolen from https://thispointer.com/how-to-find-drop-duplicate-columns-in-a-dataframe-python-pandas/ .
Args:
df: Dataframe object
Returns:
List of columns whose contents are redudnant (one occurence will of each will not be included in the list).
'''
duplicateColumnNames = set()
# Iterate over all the columns in dataframe
for x in range(df.shape[1]):
# Select column at xth index.
col = df.iloc[:, x]
# Iterate over all the columns in DataFrame from (x+1)th index till end
for y in range(x + 1, df.shape[1]):
# Select column at yth index.
otherCol = df.iloc[:, y]
# Check if two columns at x 7 y index are equal
if col.equals(otherCol):
duplicateColumnNames.add(df.columns.values[y])
return list(duplicateColumnNames)
def dedup_columns(flist, cols=[0,1], colSep=["\t"], merge=True):
"""Merge duplicate columns from the files, as they are.
This function also supports key-aware appending, using outer-join, when a
row index is specified.
Args:
flist: A list/FilesList of files to combine.
colSep[str]: A list of characters used as field delimiters.
(Default ["\t"])
cols[int] : A list of positional indexes of the
desired columns. (Default [0,1]).
Returns:
pandas.Dataframe
"""
try:
flist.aliases[0]
except AttributeError:
flist = FilesList(flist)
# Determine how many columns each file has.
numofcols = count_columns(flist, colSep=colSep)
# Delegate fetching all the columns.
result = []
keyhead = None
for f, (myfile, myalias) in flist.enum():
# List the columns.
allcols = [i for i in range(0,numofcols[f])]
df = get_columns(FilesList(files=[myfile], aliases=[myalias]), cols=allcols,
colSep=colSep, header=False, merge=False, index=None)[0]
# Collect duplicated values, drop duplicated columns, assign values to new column.
v = df.iloc[:, cols].apply(lambda x: next(s for s in x.unique() if s), axis=1)
df.drop(df.columns[cols], axis=1, inplace=True)
df = pd.concat([df, v], axis=1, join='outer', sort=False, ignore_index=False)
if not keyhead:
keyhead = df.index.name
result.append(df)
# Merge.
if merge:
result = [pd.concat(result, axis=1, join='outer', ignore_index=False, sort=False), ]
result[0].index.name = keyhead
return result
def get_crosspoints(flist, cols=[0], rows=[0], colSep=["\t"], header=False, index=None, merge=True):
""" Get the values at selected rows and columns.
The values at the intersections of the selected rows and columns are extracted.
Args:
flist: A [str] list or fileutilities.FilesList of delimited text files.
colSep[str]: List of column separators.
cols[int]: List of columns.
rows[int]: List of rows.
header(bool): Whether there is a header line (False).
index(int): Which column has the row labels (None).
merge(bool): Merge results into single table (True).
Returns:
[pandas.DataFrame]:
"""
results = get_columns(flist, cols=cols, colSep=colSep, header=header, merge=merge, index=index)
for i in range(0, len(results)):
results[i] = results[i].iloc[rows,:]
return results
def store_metadata(flist, numoflines):
"""Store top lines of files into dictionary.
Args:
flist: A list or FilesList.
numoflines(int): Number of lines to save.
Returns:
dict[]: The items of flist[] are used as keys.
"""
metadata = dict()
for myfile in flist:
if myfile is None:
fin = sys.stdin
else:
fin = open(myfile)
lines = []
for i in range(0, numoflines):
lines.append(fin.readline())
metadata[myfile] = "".join(lines)
if fin != sys.stdin:
fin.close()
return metadata
##### C L A S S E S #####
class FilesList(list):
"""A container for a list of files.
An extension of the built-in list, specifically for files, providing a
means to import multiple filenames either from text lists or from
directories. The purpose is to facilitate batch operations and sensible
output of their results.
FilesList is generally backwards compatible with the built-in list and it
should be possible for them to be used interchangeably in most cases. A
plain list can be cast as a FilesList, when necessary, allowing appointment
of default alias values. A FilesList should always work as a plain list
without additional actions (except for its string representation). When a
FilesList is accessed as a plain list, only the full paths will be
accessed. Certain equivalent methods are supplied for
Most basic operations inherited from list are supported. Appending has been
overridden to keep paths and aliases in sync. Sorting, deleting and
inserting of items are currently not supported and will break the
correspondence between paths and aliases.
Attributes defined here:
aliases = [] : Practical aliases for the full file-paths.
"""
def __init__(self, files=None, aliases=None, fromtuples=None, verbatim=True):
"""Construct an instance of the FilesList.
A FilesList can be created:
- empty
- from a list of files (with default aliases automatically assigned)
- from a list of files and a list of aliases (in the same order)
- from a list of (file, alias) tuples.
Args:
verbatim(bool): Whether to skip path pre-preocessing. (Default True)
files[str]: A list of files. (Default None)
aliases[str]: A list of aliases. (Default None)
fromtuples[(str,str)]: A list of tuples (file, alias). (Default
None) If this is specified together with flist and/or
aliases, the data in fromtuples is used only.
"""
# If data is a list of (file, alias) tuples, unpair tuples into lists.
if fromtuples is not None:
data = [list(t) for t in zip(*fromtuples)]
# Any data passed to flist and aliases at method call is discarded.
files = data[0]
aliases = data[1]
# Having aliases without the paths is rather useless.
if aliases:
if not files:
raise ValueError("No files supplied for the aliases.")
else:
# Make None into empty.
aliases = []
# Assign default aliases to be same as files. Expand file paths.
if files is not None:
if not verbatim:
files = expand_fpaths(files)
if not aliases:
for f in files:
aliases.append(self.autoalias(f))
else:
# If still empty, it was an empty call to the constructor.
files = []
# Create the basic list.
super().__init__(files)
# Add a plain list attribute for the aliases with default values.
self.aliases = autonumerate(aliases)
def __str__(self):
"""Represent as string.
Overrides built-in list's representation.
Returns:
str