-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathutils.py
More file actions
1236 lines (956 loc) · 35.6 KB
/
utils.py
File metadata and controls
1236 lines (956 loc) · 35.6 KB
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
# This file is part of PyPop
# Copyright (C) 2003. The Regents of the University of California (Regents)
# All Rights Reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
# IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
# INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
# LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
# DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
# REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
# DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
# IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
# UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""Module for common utility classes and functions.
Contains convenience classes for output of text and XML
files.
"""
import copy
import operator
import os
import re
import shutil
import stat
import sys
from collections.abc import Sequence
from pathlib import Path
import numpy as np
from numpy import asarray, take, zeros
from PyPop import logger
GENOTYPE_SEPARATOR = "~"
"""
Separator between genotypes
Example:
In a haplotype
``01:01~13:01~04:02``
"""
GENOTYPE_TERMINATOR = "~"
"""
Terminator of genotypes
Example:
```02:01:01:01~``
"""
class TextOutputStream:
"""Output stream for writing text files.
Args:
file (file): file handle
"""
def __init__(self, file):
self.f = file
def write(self, str):
"""Write to stream.
Args:
str (str): string to write
"""
self.f.write(str)
def writeln(self, str="\n"):
"""Write a newline to stream.
Args:
str (str, optional): defaults to newline
"""
if str == "\n":
self.f.write("\n")
else:
self.f.write(str + "\n")
def close(self):
"""Close stream."""
self.f.close()
def flush(self):
"""Flush to disk."""
self.f.flush()
class XMLOutputStream(TextOutputStream):
"""Output stream for writing XML files."""
def _gentag(self, tagname, **kw):
"""Internal method for generating tag text.
Strip out non-valid tag character: '?'
*Only use internally*.
"""
attr = ""
tagname = tagname.replace("?", "")
# loop through keywords turning each into an attr,key pair
for key, val in kw.items():
attr = attr + key + "=" + '"' + val + '"' + " "
if attr == "":
return f"{tagname}"
return f"{tagname} {attr.strip()}"
def opentag(self, tagname, **kw): # noqa: D417
"""Write an open XML tag to stream.
Tag attributes passed as optional named keyword arguments.
Example:
``opentag('tagname', role=something, id=else)``
produces the result:
``<tagname role="something" id="else">``
Attribute and values are optional:
``opentag('tagname')``
Produces:
``<tagname>``
See Also:
Must be be followed by a :meth:`closetag`.
Args:
tagname (str): name of XML tag
"""
self.f.write(f"<{self._gentag(tagname, **kw)}>")
def emptytag(self, tagname, **kw): # noqa: D417
"""Write an empty XML tag to stream.
This follows the same syntax as :meth:`opentag` but without
XML content (but can contain attributes).
Example:
```emptytag('tagname', attr='val')``
produces:
``<tagname attr="val"/>``
Args:
tagname (str): name of XML tag
"""
self.f.write(f"<{self._gentag(tagname, **kw)}/>")
def closetag(self, tagname):
"""Write a closing XML tag to stream.
Example:
``closetag('tagname')``
Generate a tag in the form:
``</tagname>``
See Also:
Must be be preceded by a :meth:`opentag`.
Args:
tagname (str): name of XML tag
"""
self.f.write(f"</{self._gentag(tagname)}>")
def tagContents(self, tagname, content, **kw): # noqa: D417
"""Write XML tags around contents to a stream.
Example:
``tagContents('tagname', 'foo bar')``
produces:
``<tagname>foo bar</tagname>```
Args:
tagname (str): name of XML tag
content (str): must only be a string. ``&``, ``<`` and
``>`` are converted into valid XML equivalents.
"""
self.opentag(tagname, **kw)
content = content.replace("&", "&")
content = content.replace("<", "<")
content = content.replace(">", ">")
self.f.write(content)
self.closetag(tagname)
class StringMatrix(Sequence):
"""Matrix of strings and other metadata from input file to PyPop.
``StringMatrix`` is a subclass of
:class:`collections.abc.Sequence` class, which stores the data in
an efficient array format, using NumPy-style access.
Args:
rowCount (int): number of rows in matrix
colList (list): list of locus keys in a specified order
extraList (list): other non-matrix metadata
colSep (str): column separator
headerLines (list): list of lines in the header of original file
"""
def __init__(
self, rowCount=None, colList=None, extraList=None, colSep="\t", headerLines=None
):
# colList is a mutable type so we freeze the list of locus
# keys in the original order in file by making a *clone* of
# the list of keys.
# the order of loci in the array will correspond to the
# original file order, and we don't want this tampered with by
# the `callee' function (i.e. effectively override the Python
# 'pass by reference' default and 'pass by value').
self.colList = colList[:]
self.colCount = len(self.colList)
self.rowCount = rowCount
if extraList:
self.extraList = extraList[:]
self.extraCount = len(self.extraList)
else:
self.extraList = None
self.extraCount = 0
self.colSep = colSep
self.headerLines = headerLines
# initialising the internal NumPy array
self.array = zeros(
(self.rowCount, self.colCount * 2 + self.extraCount), dtype="O"
)
self.dtype = self.array.dtype
self.shape = self.array.shape
self._typecode = self.array.dtype
self.name = str(self.__class__).split()[0]
def __repr__(self):
"""Override default representation.
Example:
This is used when the object is 'print'ed, i.e.
>>> a = StringMatrix(2, [1,2])
>>> print (a)
StringMatrix([[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=object)
Returns:
str: new string representation
"""
if len(self.array.shape) > 0:
return (self.__class__.__name__) + repr(self.array)[len("array") :]
return (self.__class__.__name__) + "(" + repr(self.array) + ")"
def __len__(self):
"""Get number of rows (individuals) in the matrix.
This allows StringMatrix instances to be used with `len()`,
iteration, and other Python sequence protocols.
Returns:
int: number of rows in the matrix
"""
return self.array.shape[0]
def dump(self, locus=None, stream=sys.stdout):
"""Write file to a stream in original format.
Args:
locus (str, optional): write just specified locus, if
omitted, default to all loci
stream (TextOutputStream|XMLOutputStream|stdout): output stream
"""
# first write out header, if there is one
if self.headerLines:
for line in self.headerLines:
(stream.write(line),)
# next write out the non-allele column headers, if there are some
if self.extraList:
for elem in self.extraList:
stream.write(elem + self.colSep)
locusList = locus if locus else ":".join(self.colList)
# next write out the allele column headers
for elem in locusList.split(":"):
stream.write(elem + "_1" + self.colSep)
stream.write(
elem + "_2" + self.colSep,
)
stream.write("\n")
# finally the matrix itself
# prepend extra fields if they exist
all_cols = (
":".join(self.extraList) + ":" + locusList if self.extraList else locusList
)
for row in self.__getitem__(all_cols):
for elem in row:
stream.write(str(elem) + self.colSep) # convert element to str
stream.write("\n")
def copy(self):
"""Make a (deep) copy.
Return:
StringMatrix: a deep copy of the current object
"""
# FIXME: currently this goes via the constructor, not sure if
# there is a better way of doing this
thecopy = StringMatrix(
copy.deepcopy(self.rowCount),
copy.deepcopy(self.colList),
copy.deepcopy(self.extraList),
self.colSep,
self.headerLines,
)
thecopy.array = self.array.copy()
return thecopy
def __deepcopy__(self, memo):
"""Create a deepcopy for copy.deepcopy.
This simply calls ``self.copy()`` to allow
``copy.deepcopy(matrixInstance)`` to work out of the box.
Args:
memo (dict): opaque object
Returns:
StringMatrix: copy of the matrix
"""
return self.copy()
def __getslice__(self, i, j):
"""Get slice (overrides built-in).
Warning:
Currently not supported for :class:`StringMatrix`
"""
msg = "slices not currently supported"
raise Exception(msg) # noqa: TRY002
def __getitem__(self, key):
"""Get the item at given key (overrides built-in numpy).
Example:
This is called when instance is called to retrieve a position
>>> matrix = StringMatrix(2, ["A", "B"])
>>> matrix [0, "A"] = ("A0_1", "A0_2")
>>> matrix [1, "A"] = ("A1_1", "A1_2")
>>> li = matrix["A"]
>>> print (li)
[['A0_1', 'A0_2'], ['A1_1', 'A1_2']]
Args:
key (str): locus key
Returns:
list: a list (a single column vector if only one position
specified), or list of lists: (a set of column vectors if
several positions specified) of tuples for ``key``
Raises:
KeyError: if key is not found, or of wrong type
"""
if type(key) is tuple:
row, colName = key
if colName in self.colList:
col = self.extraCount + self.colList.index(colName)
else:
msg = f"can't find {colName} column"
raise KeyError(msg)
return self.array[(row, col)]
if type(key) is str:
colNames = key.split(":")
li = []
for col in colNames:
# check first in list of alleles
if col in self.colList:
# get relative location in list
relativeLoc = self.colList.index(col)
# calculate real locations in array
col1 = relativeLoc * 2 + self.extraCount
col2 = col1 + 1
li.append(col1)
li.append(col2)
# now check in non-allele metadata
elif (self.extraList is not None) and (col in self.extraList):
li.append(self.extraList.index(col))
else:
msg = f"can't find {col} column"
raise KeyError(msg)
if len(colNames) == 1:
# return simply the pair of columns at that location as
# a list
return take(self.array, tuple(li[0:2]), 1).tolist()
# return the matrix consisting of column vectors
# of the designated keys
return take(self.array, tuple(li), 1).tolist()
msg = "keys must be a string or tuple"
raise KeyError(msg)
def getNewStringMatrix(self, key):
"""Create new StringMatrix containing specified loci.
Note:
The format of the keys is identical to :meth:`__getitem__`
except that it returns a full ``StringMatrix`` instance
which includes all metadata
Args:
key (str): a string representing the loci, using the
``locus1:locus2`` format
Returns:
StringMatrix: full instance
Raises:
KeyError: if locus can not be found.
"""
if type(key) is str:
colNames = key.split(":")
# need both column position and names to reconstruct matrix
newColPos = []
newColList = []
newExtraPos = []
newExtraList = []
for col in colNames:
# check first in list of alleles
if col in self.colList:
# get relative location in list
relativeLoc = self.colList.index(col)
# calculate real locations in array
col1 = relativeLoc * 2 + self.extraCount
col2 = col1 + 1
newColPos.append(col1)
newColPos.append(col2)
newColList.append(col)
# now check in non-allele metadata
elif col in self.extraList:
newExtraPos.append(self.extraList.index(col))
newExtraList.append(col)
else:
msg = f"can't find {col} column"
raise KeyError(msg)
# build a new matrix using the parameters from the current
newMatrix = StringMatrix(
rowCount=self.rowCount,
colList=newColList,
extraList=newExtraList,
colSep=self.colSep,
headerLines=self.headerLines,
)
# copy just the columns we requested, both loci cols + extras
newExtraPos.extend(newColPos)
newMatrix.array = self.array[:, newExtraPos]
return newMatrix
def __setitem__(self, index, value):
"""Set the value at an index (override built in).
This is called when instance is called to assign a value.
Example:
.. code-block:: python
matrix[3, 'A'] = (entry1, entry2)
Args:
index (tuple): index into matrix
value (tuple|str): can set using a tuple of strings, or a
single string (for metadata)
Raises:
IndexError: if ``index`` is not a tuple
ValueError: if ``value`` is not a tuple or string
KeyError: if the ``index`` can't be found
"""
if type(index) is tuple:
row, colName = index
else:
msg = "index is not a tuple"
raise IndexError(msg)
if type(value) is tuple:
value1, value2 = value
elif type(value) is str:
# don't need to do anything
pass
else:
msg = "value being assigned is not a tuple"
raise ValueError(msg)
if colName in self.colList:
# find the location in order in the array
col = self.colList.index(colName)
# calculate the offsets to the actual array location
col1 = col * 2
col2 = col1 + 1
# store each element in turn
self.array[(row, col1 + self.extraCount)] = (
value1 if type(value1) is str else asarray(value1, dtype=self.dtype)
)
self.array[(row, col2 + self.extraCount)] = (
value2 if type(value2) is str else asarray(value2, dtype=self.dtype)
)
elif colName in self.extraList:
col = self.extraList.index(colName)
self.array[(row, col)] = (
value if type(value) is str else asarray(value, self.dtype)
)
else:
msg = f"can't find {col} column"
raise KeyError(msg)
def getUniqueAlleles(self, key):
"""Get naturally sorted list of unique alleles.
Args:
key (str): loci to get
Returns:
list: list of unique integers sorted by allele name using
natural sort
"""
uniqueAlleles = []
for genotype in self.__getitem__(key):
for allele in genotype:
str_allele = str(allele)
if str_allele not in uniqueAlleles:
uniqueAlleles.append(str_allele)
uniqueAlleles.sort(key=natural_sort_key) # natural sort
return uniqueAlleles
def convertToInts(self):
"""Convert the matrix to integers.
Note:
This function is used by the :class:`PyPop.Haplo.Haplostats`
class. Note that integers start at 1 for compatibility with
haplo-stats module
Returns:
StringMatrix: matrix where the original allele names are now
represented by integers
"""
# FIXME: check whether we need to release memory
# create a new copy
newMatrix = self.copy()
for colName in self.colList:
uniqueAlleles = self.getUniqueAlleles(colName)
for row, genotype in enumerate(self.__getitem__(colName)):
factor_genotype = []
for allele in genotype:
pos = uniqueAlleles.index(str(allele)) + 1
factor_genotype.append(pos)
newMatrix[row, colName] = tuple(factor_genotype)
return newMatrix
def countPairs(self):
"""Count all possible pairs of haplotypes for each matrix row.
Warning:
This does *not* do any involved handling of missing data as
per ``geno.count.pairs`` from R ``haplo.stats`` module.
Returns:
list: each element is the number of pairs in row order
"""
# FIXME: should these methods eventually be moved to the
# :class:`PyPop.ParseFile.Genotype` class?
# count number of unique alleles at each loci
n_alleles = {}
for colName in self.colList:
n_alleles[colName] = len(self.getUniqueAlleles(colName))
# count pairs of haplotypes for subjects without any missing alleles
# FIXME: maybe convert to it's own method as per getUniqueAlleles
h1 = self.array[:, 0::2] # get "_1" allele (odd cols)
h2 = self.array[:, 1::2] # get "_2" allele (even cols)
n_het = np.sum(np.not_equal(h1, h2), 1) # equivalent of: apply(h1!=h2,1,sum)
n_het = np.where(
n_het == 0, 1, n_het
) # equivalent of: ifelse(n.het==0,1,n.het)
n_pairs = 2 ** (n_het - 1) # equivalent of: n.pairs = 2^(n.het-1)
return n_pairs.tolist()
def flattenCols(self):
"""Flatten columns into a single list.
Important:
Currently assumes entries are integers.
Returns:
list: all alleles, the two genotype columns concatenated
for each locus
"""
flattened_matrix = []
for col in self.colList: # FIXME: currently assume we want whole matrix
# FIXME: possibly refactor extracting column logic with __getitem__
relativeLoc = self.colList.index(col)
col1 = relativeLoc * 2 + self.extraCount
col2 = col1 + 1
first_col = [int(x) for x in self.array[:, col1]]
flattened_matrix.extend(first_col)
second_col = [int(x) for x in self.array[:, col2]]
flattened_matrix.extend(second_col)
return flattened_matrix
def filterOut(self, key, blankDesignator):
"""Get matrix rows filtered by a designator.
Args:
key (str): locus to filter
blankDesignator (str): string to exclude
Returns:
list: the rows of the matrix that *do not* contain
``blankDesignator`` at any rows
"""
def f(x, designator=blankDesignator):
for value in x:
if value == designator:
return 0
return 1
filtered_list = list(filter(f, self.__getitem__(key)))
return filtered_list[:]
def getSuperType(self, key):
"""Get a matrix grouped by specified key.
Example:
Return a new matrix with the column vector with the alleles
for each genotype concatenated like so:
>>> matrix = StringMatrix(2, ["A", "B"])
>>> matrix[0, "A"] = ("A01", "A02")
>>> matrix[1, "A"] = ("A11", "A12")
>>> matrix[0, "B"] = ("B01", "B02")
>>> matrix[1, "B"] = ("B11", "B12")
>>> print(matrix)
StringMatrix([['A01', 'A02', 'B01', 'B02'],
['A11', 'A12', 'B11', 'B12']], dtype=object)
>>> matrix.getSuperType("A:B")
StringMatrix([['A01:B01', 'A02:B02'],
['A11:B11', 'A12:B12']], dtype=object)
Args:
key (str): loci to group
Returns:
StringMatrix: a new matrix with the columns concatenated
"""
li = self.__getitem__(key)
colName = key.replace(":", "-")
newMatrix = StringMatrix(
rowCount=copy.deepcopy(self.rowCount),
colList=copy.deepcopy([colName]),
extraList=copy.deepcopy(self.extraList),
colSep=self.colSep,
headerLines=self.headerLines,
)
for pos, i in enumerate(li):
# newMatrix[pos, colName] = (i[0::2].join(":"), i[1::2].join(":"))
newMatrix[pos, colName] = (":".join(i[0::2]), ":".join(i[1::2]))
return newMatrix
class Group:
"""Group list or sequence into non-overlapping chunks.
Example:
>>> for pair in Group('aabbccddee', 2):
... print(pair) # doctest: +NORMALIZE_WHITESPACE
...
aa
bb
cc
dd
ee
>>> a = Group('aabbccddee', 2)
>>> a[0]
'aa'
>>> a[3]
'dd'
Args:
li (str|list): string or list
size (int): size of grouping
"""
def __init__(self, li, size):
self.size = size
self.li = li
def __getitem__(self, group):
"""Get the item by position.
Args:
group (int): get the item by position
Returns:
str|list: the value at that position
Raises:
IndexError: if ``group`` is out of bounds
"""
idx = group * self.size
if idx > len(self.li):
msg = "Out of range"
raise IndexError(msg)
return self.li[idx : idx + self.size]
class OrderedDict:
"""A dictionary class with **ordered** pairs.
.. deprecated:: 1.3.1
Will be removed in a later release, to be replaced by internal
Python version
"""
__version__ = "1.1"
def __init__(self, hash=None):
"""Creates an ordered dict."""
if hash is None:
hash = []
self.__hash = {}
self.KEYS = []
while hash:
k, v, hash = hash[0], hash[1], hash[2:]
self.__hash[k] = v
self.KEYS.append(k)
def __addval__(self, key, value):
"""Internal function to add/change key-value pair (at end)."""
try:
self.KEYS.index(key)
except Exception:
self.__hash[key] = value
self.KEYS.append(key)
else:
self.__hash[key] = value
def __setitem__(self, i, hash):
"""Adds key-value pairs (existing keys not moved)."""
if type(i) is type(Index()):
del self.__hash[self.KEYS[i.i]]
if len(hash) != 1:
self.KEYS[i.i], hash = hash[0], hash[1:]
self.__hash[self.KEYS[i.i]] = hash[0]
else:
self.__addval__(i, hash)
def __getitem__(self, key):
"""Returns value of given key."""
if type(key) is type(Index()):
key = self.KEYS[key.i]
return [key, self.__hash[key]]
return self.__hash[key]
def __len__(self):
"""Returns the number of pairs in the dict."""
return len(self.KEYS)
def index(self, key):
"""Returns position of key in dict."""
return self.KEYS.index(key)
def keys(self):
"""Returns list of keys in dict."""
return self.KEYS
def values(self):
"""Returns list of values in dict."""
ret = []
for key in self.KEYS:
ret.append(self.__hash[key])
return ret
def items(self):
"""Returns list of tuples of keys and values."""
ret = []
for key in self.KEYS:
ret.append((key, self.__hash[key]))
return ret
def insert(self, i, key, value):
"""Inserts a key-value pair at a given index."""
InsertError = "Duplicate key entry"
if key in self.__hash:
raise InsertError
self.KEYS.insert(i, key)
self.__hash[key] = value
def remove(self, i):
"""Removes a key-value pair from the dict."""
del self.__hash[i]
self.KEYS.remove(i)
def __delitem__(self, i):
"""Removes a key-value pair from the dict."""
if type(i) is not type(Index()):
i = Index(self.KEYS.index(i))
del self.__hash[self.KEYS[i.i]]
del self.KEYS[i.i]
def reverse(self):
"""Reverses the order of the key-value pairs."""
self.KEYS.reverse()
def sort(self, cmp=0):
"""Sorts the dict (allows for sort algorithm)."""
if cmp:
self.KEYS.sort(cmp)
else:
self.KEYS.sort()
def clear(self):
"""Clears all the entries in the dict."""
self.__hash = {}
self.KEYS = []
def copy(self):
"""Makes copy of dict, also of OrderdDict class."""
hash = OrderedDict()
hash.KEYS = self.KEYS[:]
hash.__hash = self.__hash.copy()
return hash
def get(self, key):
"""Returns the value of a key."""
return self.__hash[key]
def has_key(self, key):
"""Looks for existence of key in dict."""
return key in self.__hash
def update(self, dict):
"""Updates entries in a dict based on another."""
self.__hash.update(dict)
def count(self, key):
"""Finds occurrences of a key in a dict (0/1)."""
return key in self.__hash
def __getslice__(self, i, j):
"""Returns an OrderedDict of key-value pairs from a dict."""
ret = []
for x in range(i, j):
ret.append(self.KEYS[x])
ret.append(self.__hash[self.KEYS[x]])
return OrderedDict(ret)
def __setslice__(self, i, j, hash):
"""Sets a slice of elements from the dict."""
hash = list(hash)
for x in range(i, j):
k, v, hash = hash[0], hash[1], hash[2:]
self.__setitem__(Index(x), [k, v])
class Index:
"""Returns an Index object for :class:`OrderedDict`.
.. deprecated:: 1.3.1
Will be removed in a later release, to be replaced by internal
Python version
"""
def __init__(self, i=0):
self.i = i
### global FUNCTIONS start here
def critical_exit(message, *args): # noqa: D417
"""Log a CRITICAL message and exit with status 1.
.. versionadded:: 1.4.0
Args:
message (str): Logging format string.
"""
logger.critical(message, *args, stacklevel=2)
sys.exit(1)
def getStreamType(stream):
"""Get the type of stream.
Args:
stream (TextOutputStream|XMLOutputStream): stream to check
Returns:
string: either ``xml`` or ``text``.
"""
return "xml" if isinstance(stream, XMLOutputStream) == 1 else "text"
def glob_with_pathlib(pattern):
"""Use globbing with ``pathlib``.
Args:
pattern (str): globbing pattern
Returns:
list: of pathlib globs
"""
path = Path(pattern).resolve()
return list(path.parent.glob(path.name))
def natural_sort_key(s, _nsre=re.compile(r"([0-9]+)")):
"""Generate a key for natural (human-friendly) sorting.
This function splits a string into text and number components so that
numbers are compared by value instead of lexicographically. It is
intended for use as the ``key`` function in :meth:`list.sort` or
:func:`sorted`.
Example:
>>> items = ["item2", "item10", "item1"]
>>> sorted(items, key=natural_sort_key)