Repository navigation
Expand file tree
/
Copy pathgroup.py
More file actions
1729 lines (1450 loc) · 57.7 KB
/
Copy pathgroup.py
File metadata and controls
1729 lines (1450 loc) · 57.7 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
# -*- coding: utf8 -*-
from __future__ import absolute_import, division, print_function
import fnmatch
import re
import sys
import warnings
from itertools import product, chain
import numpy as np
import pandas as pd
from larray.core.abstractbases import ABCAxis, ABCAxisReference, ABCLArray
from larray.util.oset import *
from larray.util.misc import (basestring, PY2, unique, find_closing_chr, _parse_bound, _seq_summary, _isintstring,
renamed_to, LHDFStore)
def _slice_to_str(key, repr_func=str):
"""
Converts a slice to a string
Examples
--------
>>> _slice_to_str(slice(None))
':'
>>> _slice_to_str(slice(24))
':24'
>>> _slice_to_str(slice(25, None))
'25:'
>>> _slice_to_str(slice(5, 10))
'5:10'
>>> _slice_to_str(slice(None, 5, 2))
':5:2'
"""
start = repr_func(key.start) if key.start is not None else ''
stop = repr_func(key.stop) if key.stop is not None else ''
step = (":" + repr_func(key.step)) if key.step is not None else ''
return '%s:%s%s' % (start, stop, step)
def irange(start, stop, step=None):
"""Create a range, with inclusive stop bound and automatic sign for step.
Parameters
----------
start : int
Start bound
stop : int
Inclusive stop bound
step : int, optional
Distance between two generated numbers. If provided this *must* be a positive integer.
Returns
-------
range
Examples
--------
>>> list(irange(1, 3))
[1, 2, 3]
>>> list(irange(2, 0))
[2, 1, 0]
>>> list(irange(1, 6, 2))
[1, 3, 5]
>>> list(irange(6, 1, 2))
[6, 4, 2]
>>> list(irange(-1, 1))
[-1, 0, 1]
"""
if step is None:
step = 1
elif step <= 0:
raise ValueError("step must be a positive integer or None")
step = step if start <= stop else -step
stop = stop + 1 if start <= stop else stop - 1
return range(start, stop, step)
_range_bound_pattern = re.compile('([0-9]+|[a-zA-Z]+)')
def generalized_range(start, stop, step=1):
"""Create a range, with inclusive stop bound and automatic sign for step. Bounds can be strings.
Parameters
----------
start : int or str
Start bound
stop : int or str
Inclusive stop bound
step : int, optional
Distance between two generated numbers. If provided this *must* be a positive integer.
Returns
-------
range
Examples
--------
works with both number and letter bounds
>>> list(generalized_range(-1, 2))
[-1, 0, 1, 2]
>>> generalized_range('a', 'c')
['a', 'b', 'c']
can generate in reverse
>>> list(generalized_range(2, 0))
[2, 1, 0]
>>> generalized_range('c', 'a')
['c', 'b', 'a']
can combine letters and numbers
>>> generalized_range('a0', 'c1')
['a0', 'a1', 'b0', 'b1', 'c0', 'c1']
any special character is left intact
>>> generalized_range('a_0', 'c_1')
['a_0', 'a_1', 'b_0', 'b_1', 'c_0', 'c_1']
consecutive digits are treated like numbers
>>> generalized_range('A8', 'A10')
['A8', 'A9', 'A10']
one may use zero padding on numbers
>>> generalized_range('A08', 'A10')
['A08', 'A09', 'A10']
consecutive letters create all combinations
>>> generalized_range('AA', 'CC')
['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']
one cannot go from a integer to a letter and vice versa
>>> generalized_range('1', 'F')
Traceback (most recent call last):
...
ValueError: expected an integer for the stop bound (because the start bound is an integer) but got 'F' instead
when using special characters, they must be the same on both sides
>>> generalized_range('a|1', 'a/2')
Traceback (most recent call last):
...
ValueError: Special characters must be the same for start and stop
"""
if isinstance(start, str):
assert isinstance(stop, str)
start_parts = _range_bound_pattern.split(start)
stop_parts = _range_bound_pattern.split(stop)
assert len(start_parts) == len(stop_parts)
ranges = []
for start_part, stop_part in zip(start_parts, stop_parts):
# we only handle non-negative int-like strings on purpose. Int-only bounds should already be converted to
# real integers by now, and mixing negative int-like strings and letters yields some strange results.
if start_part.isdigit():
if not stop_part.isdigit():
raise ValueError("expected an integer for the stop bound (because the start bound is an integer) "
"but got '%s' instead" % stop_part)
rng = irange(int(start_part), int(stop_part))
start_pad = len(start_part) if start_part.startswith('0') else None
stop_pad = len(stop_part) if stop_part.startswith('0') else None
if start_pad is not None and stop_pad is not None and start_pad != stop_pad:
raise ValueError("Inconsistent zero padding for start and stop ({} vs {}) of the numerical part. "
"Must be either the same on both sides or no padding on either side"
.format(start_pad, stop_pad))
elif start_pad is None and stop_pad is None:
r = [str(num) for num in rng]
else:
pad = start_pad if stop_pad is None else stop_pad
r = ['%0*d' % (pad, num) for num in rng]
elif start_part.isalpha():
assert stop_part.isalpha()
int_start = [ord(c) for c in start_part]
int_stop = [ord(c) for c in stop_part]
sranges = [[chr(c) for c in irange(r_start, r_stop) if chr(c).isalnum()]
for r_start, r_stop in zip(int_start, int_stop)]
r = [''.join(p) for p in product(*sranges)]
else:
# special characters
if start_part != stop_part:
raise ValueError("Special characters must be the same for start and stop")
r = [start_part]
ranges.append(r)
res = [''.join(p) for p in product(*ranges)]
return res if step == 1 else res[::step]
else:
return irange(start, stop, step)
_range_str_pattern = re.compile(r'(?P<start>[^\s.]+)?\s*\.\.\s*(?P<stop>[^\s.]+)?(\s+step\s+(?P<step>\d+))?')
def _range_str_to_range(s, stack_depth=1):
"""
Converts a range string to a range (of values).
The end point is included.
Parameters
----------
s : str
String representing a range of values
Returns
-------
range
range of int or list of str.
Examples
--------
>>> list(_range_str_to_range('-1..2'))
[-1, 0, 1, 2]
>>> _range_str_to_range('a..c')
['a', 'b', 'c']
>>> list(_range_str_to_range('2..6 step 2'))
[2, 4, 6]
0 padding
>>> list(_range_str_to_range('01..12'))
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
any special character except . and spaces should work
>>> _range_str_to_range('a|+*@-b .. a|+*@-d')
['a|+*@-b', 'a|+*@-c', 'a|+*@-d']
"""
s = s.strip()
m = _range_str_pattern.match(s)
groups = m.groupdict()
start, stop, step = groups['start'], groups['stop'], groups['step']
start = _parse_bound(start, stack_depth + 1) if start is not None else 0
if stop is None:
raise ValueError("no stop bound provided in range: %r" % s)
stop = _parse_bound(stop, stack_depth + 1)
if isinstance(start, basestring) or isinstance(stop, basestring):
start, stop = str(start), str(stop)
# TODO: use parse_bound
step = int(step) if step is not None else 1
return generalized_range(start, stop, step)
def _range_to_slice(seq, length=None):
"""
Returns a slice if possible (including for sequences of 1 element) otherwise returns the input sequence itself
Parameters
----------
seq : sequence-like of int
List, tuple or ndarray of integers representing the range.
It should be something like [start, start+step, start+2*step, ...]
length : int, optional
length of sequence of positions. This is only useful when you must be able to transform decreasing sequences
which can stop at 0.
Returns
-------
slice or sequence-like
return the input sequence if a slice cannot be defined
Examples
--------
>>> _range_to_slice([3, 4, 5])
slice(3, 6, None)
>>> _range_to_slice([3, 4, 6])
[3, 4, 6]
>>> _range_to_slice([3, 5, 7])
slice(3, 9, 2)
>>> _range_to_slice([-3, -2])
slice(-3, -1, None)
>>> _range_to_slice([-1, -2])
slice(-1, -3, -1)
>>> _range_to_slice([2, 1])
slice(2, 0, -1)
>>> _range_to_slice([1, 0], 4)
slice(-3, -5, -1)
>>> _range_to_slice([1, 0])
[1, 0]
>>> _range_to_slice([1])
slice(1, 2, None)
>>> _range_to_slice([])
[]
"""
if len(seq) < 1:
return seq
start = seq[0]
if len(seq) == 1:
return slice(start, start + 1)
second = seq[1]
step = second - start
prev_value = second
for value in seq[2:]:
if value != prev_value + step:
return seq
prev_value = value
stop = prev_value + step
if prev_value == 0 and step < 0:
if length is None:
return seq
else:
stop -= length
start -= length
if step == 1:
step = None
return slice(start, stop, step)
def _is_object_array(array):
return isinstance(array, np.ndarray) and array.dtype.type == np.object_
def _can_have_groups(seq):
return _is_object_array(seq) or isinstance(seq, (tuple, list))
def _contain_group_ticks(ticks):
return _can_have_groups(ticks) and any(isinstance(tick, Group) for tick in ticks)
def _seq_group_to_name(seq):
if _can_have_groups(seq):
return [v.name if isinstance(v, Group) else v for v in seq]
else:
return seq
def _to_tick(v):
"""
Converts any value to a tick (ie makes it hashable, and acceptable as an ndarray element)
scalar -> not modified
slice -> 'start:stop'
list|tuple -> 'v1,v2,v3'
Group with name -> v.name
Group without name -> _to_tick(v.key)
other -> str(v)
Parameters
----------
v : any
value to be converted.
Returns
-------
any scalar
scalar representing the tick
"""
# the fact that an "aggregated tick" is passed as a LGroup or as a string should be as irrelevant as possible.
# The thing is that we cannot (currently) use the more elegant _to_tick(e.key) that means the LGroup is not
# available in Axis.__init__ after to_ticks, and we need it to update the mapping if it was named. Effectively,
# this creates two entries in the mapping for a single tick. Besides, I like having the LGroup as the tick, as it
# provides extra info as to where it comes from.
if np.isscalar(v):
return v
elif isinstance(v, Group):
return v.name if v.name is not None else _to_tick(v.to_label())
elif isinstance(v, slice):
return _slice_to_str(v)
elif isinstance(v, (tuple, list)):
if len(v) == 1:
return str(v) + ','
else:
# TODO: it would be nicer/saner to use n=1, sep='' but this currently breaks at lot of tests
return _seq_summary(v, n=1000, repr_func=str, sep=',')
else:
return str(v)
# TODO: remove the conversion to list in doctests once Python 2 is dropped
def _to_ticks(s, parse_single_int=False):
"""
Makes a (list of) value(s) usable as the collection of labels for an Axis (ie hashable).
Strip strings, split them on ',' and translate "range strings" to list of values **including the end point** !
Parameters
----------
s : iterable
List of values usable as the collection of labels for an Axis.
Returns
-------
Numpy 1D array containing labels
Examples
--------
>>> list(_to_ticks('M , F'))
['M', 'F']
>>> list(_to_ticks('A,C..E,F..G,Z'))
['A', 'C', 'D', 'E', 'F', 'G', 'Z']
>>> list(_to_ticks('U'))
['U']
>>> list(_to_ticks('..3'))
[0, 1, 2, 3]
>>> list(_to_ticks('01..12'))
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
>>> list(_to_ticks('01,02,03,10,11,12'))
['01', '02', '03', '10', '11', '12']
"""
if isinstance(s, ABCAxis):
return s.labels
if isinstance(s, Group):
# a single LGroup used for all ticks of an Axis
return _to_ticks(s.eval())
elif isinstance(s, np.ndarray):
# we assume it has already been translated
# XXX: Is it a safe assumption?
return s
if isinstance(s, pd.Index):
ticks = s.values
elif isinstance(s, (list, tuple)):
ticks = [_to_tick(e) for e in s]
elif sys.version >= '3' and isinstance(s, range):
ticks = s
elif isinstance(s, basestring):
seq = _seq_str_to_seq(s, parse_single_int=parse_single_int)
if isinstance(seq, slice):
raise ValueError("using : to define axes is deprecated, please use .. instead")
ticks = [seq] if isinstance(seq, (basestring, int)) else seq
elif hasattr(s, '__array__'):
ticks = s.__array__()
else:
try:
ticks = list(s)
except TypeError:
raise TypeError("ticks must be iterable (%s is not)" % type(s))
return np.asarray(ticks)
_axis_name_pattern = re.compile(r'\s*(([A-Za-z0-9]\w*)(\.i)?\s*\[)?(.*)')
def _seq_str_to_seq(s, stack_depth=1, parse_single_int=False):
"""
Converts a sequence string to its sequence (or scalar)
Parameters
----------
s : basestring
string to parse
Returns
-------
scalar, slice, range or list
"""
numcolons = s.count(':')
if numcolons:
assert numcolons <= 2
# bounds can be of len 2 or 3 (if step is provided)
# stack_depth + 2 because the list comp has its own stack
bounds = [_parse_bound(b, stack_depth + 2) for b in s.split(':')]
return slice(*bounds)
elif ',' in s and '..' in s:
# strip extremity commas to avoid empty string sequence elements
s = s.strip(',')
def to_seq(b, stack_depth=1):
if '..' in b:
return _range_str_to_range(b, stack_depth + 1)
else:
parsed = _parse_bound(b, stack_depth + 1)
return (parsed,)
# stack_depth + 2 because the list comp has its own stack
return list(chain(*[to_seq(b, stack_depth + 2) for b in s.split(',')]))
elif ',' in s:
# strip extremity commas to avoid empty string sequence elements
s = s.strip(',')
return [_parse_bound(b, stack_depth + 2) for b in s.split(',')]
elif '..' in s:
return _range_str_to_range(s, stack_depth + 1)
else:
return _parse_bound(s, stack_depth + 1, parse_int=parse_single_int)
def _to_key(v, stack_depth=1, parse_single_int=False):
"""
Converts a value to a key usable for indexing (slice object, list of values,...).
Strings are split on ',' and stripped. Colons (:) are interpreted as slices.
Parameters
----------
v : int or basestring or tuple or list or slice or LArray or Group
value to convert into a key usable for indexing
Returns
-------
key
a key represents any object that can be used for indexing
Examples
--------
>>> _to_key('a:c')
slice('a', 'c', None)
>>> _to_key('a, b,c ,')
['a', 'b', 'c']
>>> _to_key('a..c')
['a', 'b', 'c']
>>> _to_key('a,c..e,g..h,z')
['a', 'c', 'd', 'e', 'g', 'h', 'z']
>>> _to_key('a,')
['a']
>>> _to_key(' a ')
'a'
>>> _to_key(10)
10
>>> _to_key('10')
'10'
>>> _to_key('10:20')
slice(10, 20, None)
>>> _to_key(slice('10', '20'))
slice('10', '20', None)
>>> _to_key('year.i[-1]')
year.i[-1]
>>> _to_key('age[10:19]>>teens')
age[10:19] >> 'teens'
>>> _to_key('a,b,c >> abc')
LGroup(['a', 'b', 'c']) >> 'abc'
>>> _to_key('a:c >> abc')
LGroup(slice('a', 'c', None)) >> 'abc'
>>> _to_key('0[a0]')
0['a0']
>>> _to_key('0.i[a0]')
0.i['a0']
# evaluated variables do not work on Python 2, probably because the stackdepth is different
# >>> ext = [1, 2, 3]
# >>> _to_key('{ext} >> ext')
# LGroup([1, 2, 3]) >> 'ext'
# >>> answer = 42
# >>> _to_key('{answer}')
# 42
# >>> _to_key('{answer} >> answer')
# LGroup(42) >> 'answer'
# >>> _to_key('10:{answer} >> answer')
# LGroup(slice(10, 42, None)) >> 'answer'
# >>> _to_key('4,{answer},2 >> answer')
# LGroup([4, 42, 2]) >> 'answer'
# >>> list(_to_key('40..{answer}'))
# [40, 41, 42]
# >>> _to_key('4,40..{answer},2')
# [4, 40, 41, 42, 2]
# >>> _to_key('4,40..{answer},2 >> answer')
# LGroup([4, 40, 41, 42, 2]) >> 'answer'
"""
if isinstance(v, tuple):
return list(v)
elif isinstance(v, basestring):
# axis name
m = _axis_name_pattern.match(v)
_, axis, positional, key = m.groups()
# group name. using rfind in the unlikely case there is another >>
name_pos = key.rfind('>>')
name = None
if name_pos != -1:
key, name = key[:name_pos].strip(), key[name_pos + 2:].strip()
if axis is not None:
axis = axis.strip()
if _isintstring(axis):
axis = int(axis)
axis_bracket_open = m.end(1) - 1
# check that the string parentheses are correctly balanced
_ = find_closing_chr(v, axis_bracket_open)
# strip closing bracket (it should be at the end because we took care of the name earlier)
assert key[-1] == ']'
key = key[:-1]
if name is not None or axis is not None:
cls = IGroup if positional else LGroup
key = _to_key(key, stack_depth + 1, parse_single_int=positional)
return cls(key, name=name, axis=axis)
else:
return _seq_str_to_seq(v, stack_depth + 1, parse_single_int=parse_single_int)
elif v is Ellipsis or np.isscalar(v) or isinstance(v, (Group, slice, list, np.ndarray, ABCLArray, OrderedSet)):
return v
else:
raise TypeError("%s has an invalid type (%s) for a key" % (v, type(v).__name__))
def _to_keys(value, stack_depth=1):
"""
Converts a (collection of) group(s) to a structure usable for indexing.
'label' or ['l1', 'l2'] or [['l1', 'l2'], ['l3']]
Parameters
----------
value : int or basestring or tuple or list or slice or LArray or Group
(collection of) value(s) to convert into key(s) usable for indexing
Returns
-------
list of keys
Examples
--------
It is only used for .sum(axis=xxx)
>>> _to_keys('P01,P02') # <-- one group => collapse dimension
['P01', 'P02']
>>> _to_keys(('P01,P02',)) # <-- do not collapse dimension
(['P01', 'P02'],)
>>> _to_keys('P01;P02,P03;:')
('P01', ['P02', 'P03'], slice(None, None, None))
# evaluated variables do not work on Python 2, probably because the stack depth is different
# >>> ext = 'P03'
# >>> to_keys('P01,P02,{ext}')
# ['P01', 'P02', 'P03']
# >>> to_keys('P01;P02;{ext}')
# ('P01', 'P02', 'P03')
>>> _to_keys('age[10:19] >> teens ; year.i[-1]')
(age[10:19] >> 'teens', year.i[-1])
# >>> to_keys('P01,P02,:') # <-- INVALID !
# it should have an explicit failure
# we allow this, even though it is a dubious syntax
>>> _to_keys(('P01', 'P02', ':'))
('P01', 'P02', slice(None, None, None))
# it is better to use explicit groups
>>> _to_keys(('P01,', 'P02,', ':'))
(['P01'], ['P02'], slice(None, None, None))
# or even the ugly duck...
>>> _to_keys((('P01',), ('P02',), ':'))
(['P01'], ['P02'], slice(None, None, None))
"""
if isinstance(value, basestring) and ';' in value:
value = tuple(value.split(';'))
if isinstance(value, tuple):
# stack_depth + 2 because the list comp has its own stack
return tuple([_to_key(group, stack_depth + 2) for group in value])
else:
return _to_key(value, stack_depth + 1)
# forbidden characters in sheet names
_sheet_name_pattern = re.compile(r'[\\/?*\[\]:]')
def _translate_sheet_name(sheet_name):
if isinstance(sheet_name, Group):
sheet_name = str(_to_tick(sheet_name))
if isinstance(sheet_name, basestring):
sheet_name = _sheet_name_pattern.sub('_', sheet_name)
if len(sheet_name) > 31:
raise ValueError("Sheet names cannot exceed 31 characters")
return sheet_name
# forbidden characters for dataset names in HDF files
_key_hdf_pattern = re.compile(r'[\\/]')
def _translate_group_key_hdf(key):
if isinstance(key, Group):
key = _key_hdf_pattern.sub('_', str(_to_tick(key)))
return key
# TODO: kill this function
def union(*args):
# TODO: add support for LGroup and lists
"""
Returns the union of several "value strings" as a list.
Parameters
----------
*args
(collection of) value(s) to be converted into label(s). Repeated values are taken only once.
Returns
-------
list of labels
Examples
--------
>>> union('a', 'a, b, c, d', ['d', 'e', 'f'], '..2')
['a', 'b', 'c', 'd', 'e', 'f', 0, 1, 2]
"""
if args:
return list(unique(chain(*(_to_ticks(arg) for arg in args))))
else:
return []
class IGroupMaker(object):
"""
Generates a new instance of IGroup for a given axis and key.
Attributes
----------
axis : Axis
an axis.
Notes
-----
This class is used by the method `Axis.i`
"""
__slots__ = ('axis',)
def __init__(self, axis):
assert isinstance(axis, ABCAxis)
self.axis = axis
def __getitem__(self, key):
if isinstance(key, (int, np.integer)) and not isinstance(self.axis, ABCAxisReference) and key >= len(self.axis):
raise IndexError("{} is out of range for axis of length {}".format(key, len(self.axis)))
return IGroup(key, None, self.axis)
def __len__(self):
return len(self.axis)
# We need a separate class for LGroup and cannot simply create a new Axis with a subset of values/ticks/labels:
# the subset of ticks/labels of the LGroup need to correspond to its *Axis* indices
class Group(object):
"""Abstract Group.
"""
__slots__ = ('key', 'name', 'axis')
format_string = None
def __init__(self, key, name=None, axis=None):
if isinstance(key, tuple):
key = list(key)
if isinstance(key, Group):
key = key.to_label()
self.key = remove_nested_groups(key)
# we do NOT assign a name automatically when missing because that makes it impossible to know whether a name
# was explicitly given or not
self.name = _to_tick(name) if name is not None else name
assert axis is None or isinstance(axis, (basestring, int, ABCAxis)), \
"invalid axis '%s' (%s)" % (axis, type(axis).__name__)
# we could check the key is valid but this can be slow and could be useless
# TODO: for performance reasons, we should cache the result. This will need to be invalidated correctly
# axis.translate(key)
# we store the Axis object and not its name like we did previously so that groups on anonymous axes are more
# meaningful and that we can iterate on a slice of an axis (an LGroup). The reason to store the name instead of
# the object was to make sure that a Group from an axis (or without axis) could be used on another axis with
# the same name. See test_array.py:test_...
self.axis = axis
def __repr__(self):
key = self.key
# eval only returns a slice for groups without an Axis object
if isinstance(key, slice):
key_repr = _slice_to_str(key, repr_func=repr)
elif isinstance(key, (tuple, list, np.ndarray, OrderedSet)):
key_repr = _seq_summary(key, n=1000, repr_func=repr, sep=', ')
else:
key_repr = repr(key)
axis_name = self.axis.name if isinstance(self.axis, ABCAxis) else self.axis
if axis_name is not None:
axis_name = 'X.{}'.format(axis_name) if isinstance(self.axis, ABCAxisReference) else axis_name
s = self.format_string.format(axis=axis_name, key=key_repr)
else:
if self.axis is not None:
# anonymous axis
axis_ref = ', axis={}'.format(repr(self.axis))
else:
axis_ref = ''
if isinstance(key, slice):
key_repr = repr(key)
elif isinstance(key, list):
key_repr = '[{}]'.format(key_repr)
s = '{}({}{})'.format(self.__class__.__name__, key_repr, axis_ref)
return "{} >> {}".format(s, repr(self.name)) if self.name is not None else s
def __str__(self):
return str(self.eval())
# TODO: rename to "to_positional"
def translate(self, bound=None, stop=False):
"""
Translate key to a position if it is not already
Parameters
----------
bound : any, optional
stop : bool, optional
Returns
-------
int-based key (single int, slice of int or tuple/list/array of them)
"""
raise NotImplementedError()
def eval(self):
"""
Translate key to labels, if it is not already, expanding slices in the process.
Returns
-------
label-based key (single scalar or tuple/list/array of them)
"""
raise NotImplementedError()
def to_label(self):
"""
Translate key to labels, if it is not already
Returns
-------
label-based key (single scalar, slice of scalars or tuple/list/array of them)
"""
raise NotImplementedError()
def retarget_to(self, target_axis):
"""Retarget group to another axis.
It will be translated to an LGroup using its former axis, if necessary.
Parameters
----------
target_axis : Axis
axis to conform to
Returns
-------
Group with axis, raise ValueError if retargeting is not possible
"""
if self.axis is target_axis:
return self
elif isinstance(self.axis, basestring) or isinstance(self.axis, ABCAxisReference):
axis_name = self.axis.name if isinstance(self.axis, ABCAxisReference) else self.axis
if axis_name != target_axis.name:
raise ValueError('cannot retarget a Group defined without a real axis object (e.g. using '
'an AxisReference (X.)) to an axis with a different name')
return self.__class__(self.key, self.name, target_axis)
elif isinstance(self.axis, int) or self.axis.equals(target_axis):
# in the case of isinstance(self.axis, int), we can only hope the axis corresponds. This is the
# case if we come from _translate_axis_key_chunk, but if the users calls this manually, we cannot know.
# XXX: maybe changing this to retarget_to_axes would be a good idea after all?
# just change the axis object
return self.__class__(self.key, self.name, target_axis)
else:
# to retarget to another (non-equal) Axis, we need to translate to labels and expand slices
return LGroup(self.eval(), self.name, target_axis)
def __len__(self):
# XXX: we probably want to_label instead of .eval (so that we do not expand slices)
value = self.eval()
# for some reason this breaks having LGroup ticks/labels on an axis
# if isinstance(value, (tuple, list, LArray, np.ndarray, str)):
if hasattr(value, '__len__'):
return len(value)
elif isinstance(value, slice):
start, stop, key_step = value.start, value.stop, value.step
# not using stop - start because that does not work for string bounds
# (and it is different for LGroup & IGroup)
start_pos = self.translate(start)
stop_pos = self.translate(stop)
return stop_pos - start_pos
else:
raise TypeError('len() of unsized object ({})'.format(value))
def __iter__(self):
# XXX: use translate/IGroup instead, so that it works even in the presence of duplicate labels
# possibly, only if axis is set?
axis = self.axis
return iter([LGroup(v, axis=axis) for v in self.eval()])
def named(self, name):
"""Returns group with a different name.
Parameters
----------
name : str
new name for group
Returns
-------
Group
"""
return self.__class__(self.key, name, self.axis)
__rshift__ = named
def with_axis(self, axis):
"""Returns group with a different axis.
Parameters
----------
axis : int, str, Axis
new axis for group
Returns
-------
Group
"""
return self.__class__(self.key, self.name, axis)
def by(self, length, step=None, template=None):
"""Split group into several groups of specified length.
Parameters
----------
length : int
length of new groups
step : int, optional
step between groups. Defaults to length.
template : str, optional
template describing how group names are generated. It is a string containing specific arguments
written inside brackets {}. Available arguments are {start} and {end} representing the first and last label
of each group. By default, template is defined as '{start}:{end}'.
Notes
-----
step can be smaller than length, in which case, this will produce overlapping groups.
Returns
-------
list of Group
Examples
--------
>>> from larray import Axis, X
>>> age = Axis('age=0..100')
>>> young_children = age[0:6]
>>> young_children.by(3)
(age.i[0:3] >> '0:2', age.i[3:6] >> '3:5', age.i[6:7] >> '6')
>>> young_children.by(3, step=2)
(age.i[0:3] >> '0:2', age.i[2:5] >> '2:4', age.i[4:7] >> '4:6', age.i[6:7] >> '6')
>>> young_children.by(3, template='{start}-{end}')
(age.i[0:3] >> '0-2', age.i[3:6] >> '3-5', age.i[6:7] >> '6')
"""
def make_group(start, length, name_template):
g = self[start:start + length]
labels = g.eval()
g.name = name_template.format(start=labels[0], end=labels[-1]) if len(labels) > 1 else str(labels[0])
return g
if step is None:
step = length
if template is None:
template = '{start}:{end}'
return tuple(make_group(start, length, template) for start in range(0, len(self), step))
# TODO: __getitem__ should work by label and .i[] should work by position. I guess it would be more consistent this
# way even if the usefulness of subsetting a group with labels is dubious (but it is sometimes practical to treat
# the group as if it was an axis).
# >>> vla = geo['...']
# >>> # first 10 regions of flanders (this could have some use)
# >>> vla.i[:10] # => IGroup on geo
# >>> vla["antwerp", "gent"] # => LGroup on geo
# LGroup[] => LGroup
# IGroup[] => LGroup
# IGroup.i[] => IGroup
# LGroup.i[] => IGroup
def __getitem__(self, key):
"""
Parameters
----------
key : int, slice of int or list of int
position-based key (even for LGroup)
Returns
-------
Group
"""
cls = self.__class__
orig_key = self.key
# XXX: unsure we should support tuple
if isinstance(orig_key, (tuple, list)):
return cls(orig_key[key], None, self.axis)
elif isinstance(orig_key, slice):
orig_start, orig_stop, orig_step = orig_key.start, orig_key.stop, orig_key.step
if orig_step is None:
orig_step = 1
orig_start_pos = self.translate(orig_start) if orig_start is not None else 0
if isinstance(key, slice):
key_start, key_stop, key_step = key.start, key.stop, key.step
if key_step is None:
key_step = 1
orig_stop_pos = self.translate(orig_stop, stop=True) if orig_stop is not None else len(self)
new_start = orig_start_pos + key_start * orig_step
new_stop = min(orig_start_pos + key_stop * orig_step, orig_stop_pos)
new_step = orig_step * key_step
if new_step == 1:
new_step = None
return IGroup(slice(new_start, new_stop, new_step), None, self.axis)