Repository navigation
Expand file tree
/
Copy pathcore.py
More file actions
10019 lines (8756 loc) · 325 KB
/
Copy pathcore.py
File metadata and controls
10019 lines (8756 loc) · 325 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
__version__ = "0.19.1"
__all__ = [
'LArray', 'Axis', 'AxisCollection', 'LGroup', 'LSet', 'PGroup',
'union', 'stack',
'read_csv', 'read_eurostat', 'read_excel', 'read_hdf', 'read_tsv',
'read_sas',
'x',
'zeros', 'zeros_like', 'ones', 'ones_like', 'empty', 'empty_like',
'full', 'full_like', 'create_sequential', 'ndrange', 'labels_array',
'ndtest',
'identity', 'diag', 'eye',
'larray_equal', 'aslarray',
'all', 'any', 'sum', 'prod', 'cumsum', 'cumprod', 'min', 'max', 'mean',
'ptp', 'var', 'std', 'median', 'percentile',
'__version__'
]
"""
Matrix class
"""
# * when trying to aggregate on an non existing Axis (using x.blabla),
# the error message is awful
# ? implement multi group in one axis getitem:
# lipro['P01,P02;P05'] <=> (lipro.group('P01,P02'), lipro.group('P05'))
# <=> (lipro['P01,P02'], lipro['P05'])
# discuss VG with Geert:
# I do not "expand" key (eg :) upon group creation for perf reason
# VG[:] is much faster than [A01,A02,...,A99]
# I could make that all "contiguous" ranges are conv to slices (return views)
# but that might introduce confusing differences if they update/setitem their
# arrays
# * we need an API to get to the "next" label. Sometimes, we want to use
# label+1, but when label is not numeric, or has not a step of 1, that's
# problematic. x.agegroup[x.agegroup.after(25):]
# * implement keepaxes=True for _group_aggregate instead of/in addition to
# group tuples
# ? implement newaxis
# * split unit tests
# * reindex array (ie make it conform to another index, eg of another
# array). This can be used both for doing operations (add, divide, ...)
# involving arrays with incompatible axes and to (manually) reorder one axis
# labels
# * test to_csv: does it consume too much mem?
# ---> test pandas (one dimension horizontally)
# * add labels in LGroups.__str__
# * docstring for all methods
# * IO functions: csv/hdf/excel?/...?
# >> needs discussion of the formats (users involved in the discussion?)
# + check pandas dialects
# * plotting (see plot.py)
# >> check pandas API
# * implement more Axis functions:
# - arithmetic operations: + -
# - regexp functions: geo.group('A3*')
# - sequence?: geo.seq('A31', 'A38')
# this NOT exactly equivalent to geo['A31':'A38'] because the later
# can contain A22 if it is defined between A31 and A38
# * re-implement row_totals/col_totals? or what do we do with them?
# * all the other TODO/XXX in the code
# * time specific API so that we know if we go for a subclass or not
# * data alignment in arithmetic methods
# * test structured arrays
# * review all method & argument names
# ? move "utils" to its own project (so that it is not duplicated between
# larray and liam2)
# OR
# include utils only in larray project and make larray a dependency of liam2
# (and potentially rename it to reflect the broader scope)
import csv
from itertools import product, chain, groupby, islice
import os
import re
import sys
import warnings
try:
import builtins
except ImportError:
import __builtin__ as builtins
import numpy as np
import pandas as pd
try:
import xlwings as xw
except ImportError:
xw = None
try:
from numpy import nanprod as np_nanprod
except ImportError:
np_nanprod = None
from larray.oset import *
from larray.utils import (table2str, size2str, unique, csv_open, unzip, long,
decode, basestring, unicode, bytes, izip, rproduct,
ReprString, duplicates, array_lookup2, strip_rows,
skip_comment_cells, find_closing_chr, PY3)
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, 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 _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'
"""
# examples of result: ":24" "25:" ":" ":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
else:
assert step > 0
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('P01', 'P12')
['P01', 'P02', 'P03', 'P04', 'P05', 'P06', 'P07', 'P08', 'P09', 'P10', 'P11', 'P12']
consecutive letters create all combinations
>>> generalized_range('AA', 'CC')
['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']
"""
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():
assert stop_part.isdigit()
numchr = max(len(start_part), len(stop_part))
r = ['%0*d' % (numchr, num) for num in irange(int(start_part), int(stop_part))]
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
assert start_part == stop_part
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('(?P<start>[^\s.]+)?\s*\.\.\s*(?P<stop>[^\s.]+)?(\s+step\s+(?P<step>\d+))?')
def _range_str_to_range(s):
"""
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]
any special character except . and spaces should work
>>> _range_str_to_range('a|+*@-b .. a|+*@-d')
['a|+*@-b', 'a|+*@-c', 'a|+*@-d']
"""
m = _range_str_pattern.match(s)
groups = m.groupdict()
start, stop, step = groups['start'], groups['stop'], groups['step']
start = _parse_bound(start) 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)
step = int(step) if step is not None else 1
return generalized_range(start, stop, step)
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.key)
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)
def _to_ticks(s):
"""
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
-------
collection of labels
Notes
-----
This function is only used in Axis.__init__ and union().
Examples
--------
>>> _to_ticks('H , F')
['H', 'F']
>>> list(_to_ticks('..3'))
[0, 1, 2, 3]
"""
if isinstance(s, Group):
# a single LGroup used for all ticks of an Axis
return _to_ticks(s.eval())
elif isinstance(s, pd.Index):
return s.values
elif isinstance(s, np.ndarray):
# we assume it has already been translated
# XXX: Is it a safe assumption?
return s
elif isinstance(s, (list, tuple)):
return [_to_tick(e) for e in s]
elif sys.version >= '3' and isinstance(s, range):
return list(s)
elif isinstance(s, basestring):
if ':' in s:
raise ValueError("using : to define axes is deprecated, please use .. instead")
elif '..' in s:
return _range_str_to_range(s)
else:
return [v.strip() for v in s.split(',')]
elif hasattr(s, '__array__'):
return s.__array__()
else:
try:
return list(s)
except TypeError:
raise TypeError("ticks must be iterable (%s is not)" % type(s))
def _isintstring(s):
return s.isdigit() or (len(s) > 1 and s[0] == '-' and s[1:].isdigit())
def _parse_bound(s, stack_depth=1, parse_int=True):
"""Parse a string representing a single value, converting int-like
strings to integers and evaluating expressions within {}.
Parameters
----------
s : str
string to evaluate
stack_depth : int
how deep to go in the stack to get local variables for evaluating
{expressions}.
Returns
-------
any
Examples
--------
>>> _parse_bound(' a ')
'a'
>>> # returns None
>>> _parse_bound(' ')
>>> ext = 1
>>> _parse_bound(' {ext + 1} ')
2
>>> _parse_bound('42')
42
"""
s = s.strip()
if s == '':
return None
elif s[0] == '{':
expr = s[1:find_closing_chr(s)]
return eval(expr, sys._getframe(stack_depth).f_locals)
elif parse_int and _isintstring(s):
return int(s)
else:
return s
_axis_name_pattern = re.compile('\s*(([A-Za-z]\w*)(\.i)?\s*\[)?(.*)')
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,')
['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'
# 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], name='ext')
# >>> answer = 42
# >>> _to_key('{answer}')
# 42
# >>> _to_key('{answer} >> answer')
# LGroup(42, name='answer')
# >>> _to_key('10:{answer} >> answer')
# LGroup(slice(10, 42, None), name='answer')
# >>> _to_key('4,{answer},2 >> answer')
# LGroup([4, 42, 2], name='answer')
"""
if isinstance(v, tuple):
return list(v)
elif isinstance(v, Group):
return v.__class__(_to_key(v.key, stack_depth + 1), v.name, v.axis)
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()
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]
cls = PGroup if positional else LGroup
if name is not None or axis is not None:
key = _to_key(key, stack_depth + 1, parse_single_int=positional)
return cls(key, name=name, axis=axis)
else:
numcolons = v.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 v.split(':')]
return slice(*bounds)
else:
if ',' in v:
# strip extremity commas to avoid empty string keys
v = v.strip(',')
# stack_depth + 2 because the list comp has its own stack
return [_parse_bound(b, stack_depth + 2)
for b in v.split(',')]
else:
return _parse_bound(v, stack_depth + 1, parse_int=parse_single_int)
elif v is Ellipsis or np.isscalar(v) or isinstance(v, (slice, list, np.ndarray, LArray, 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)
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 []
def larray_equal(first, other):
"""
Compares two arrays and returns True if they have the
same axes and elements, False otherwise.
Parameters
----------
first, other : LArray
Input arrays.
Returns
-------
bool
Returns True if the arrays are equal.
Examples
--------
>>> age = Axis('age', range(0, 100, 10))
>>> sex = Axis('sex', ['M', 'F'])
>>> a = ndrange([age, sex])
>>> b = a.copy()
>>> larray_equal(a, b)
True
>>> b['F'] += 1
>>> larray_equal(a, b)
False
>>> b = a.set_labels(x.sex, ['Men', 'Women'])
>>> larray_equal(a, b)
False
"""
if not isinstance(first, LArray) or not isinstance(other, LArray):
return False
return (first.axes == other.axes and
np.array_equal(np.asarray(first), np.asarray(other)))
def _isnoneslice(v):
"""
Checks if input is slice(None) object.
"""
return isinstance(v, slice) and v == slice(None)
def _seq_summary(seq, n=3, repr_func=repr, sep=' '):
"""
Returns a string representing a sequence by showing only the n first and last elements.
Examples
--------
>>> _seq_summary(range(10), 2)
'0 1 ... 8 9'
"""
if len(seq) <= 2 * n:
short_seq = [repr_func(v) for v in seq]
else:
short_seq = [repr_func(v) for v in seq[:n]] + ['...'] + [repr_func(v) for v in seq[-n:]]
return sep.join(short_seq)
class PGroupMaker(object):
"""
Generates a new instance of PGroup for a given axis and key.
Attributes
----------
axis : Axis
an axis.
Notes
-----
This class is used by the method `Axis.i`
"""
def __init__(self, axis):
assert isinstance(axis, Axis)
self.axis = axis
def __getitem__(self, key):
return PGroup(key, None, self.axis)
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
class Axis(object):
"""
Represents an axis. It consists of a name and a list of labels.
Parameters
----------
name : str or Axis
name of the axis or another instance of Axis.
In the second case, the name of the other axis is simply copied.
labels : array-like or int
collection of values usable as labels, i.e. numbers or strings or the size of the axis.
In the last case, a wildcard axis is created.
Attributes
----------
name : str
name of the axis.
labels : array-like or int
collection of values usable as labels, i.e. numbers or strings
Examples
--------
>>> age = Axis('age', 10)
>>> age
Axis('age', 10)
>>> age.name
'age'
>>> age.labels
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> sex = Axis('sex', ['M', 'F'])
>>> sex
Axis('sex', ['M', 'F'])
"""
# ticks instead of labels?
# XXX: make name and labels optional?
def __init__(self, name, labels):
if isinstance(name, Axis):
name = name.name
# make sure we do not have np.str_ as it causes problems down the
# line with xlwings. Cannot use isinstance to check that though.
is_python_str = type(name) is unicode or type(name) is bytes
assert name is None or isinstance(name, int) or is_python_str, \
type(name)
self.name = name
self._labels = None
self.__mapping = None
self.__sorted_keys = None
self.__sorted_values = None
self._length = None
self._iswildcard = False
self.labels = labels
@property
def _mapping(self):
# To map labels with their positions
mapping = self.__mapping
if mapping is None:
labels = self._labels
# TODO: this would be more efficient for wildcard axes but
# does not work in all cases
# mapping = labels
mapping = {label: i for i, label in enumerate(labels)}
if not self._iswildcard:
# we have no choice but to do that!
# otherwise we could not make geo['Brussels'] work efficiently
# (we could have to traverse the whole mapping checking for each
# name, which is not an option)
# TODO: only do this if labels.dtype is object, or add
# "contains_lgroup" flag in above code (if any(...))
# 0.179
mapping.update({label.name: i for i, label in enumerate(labels)
if isinstance(label, Group)})
self.__mapping = mapping
return mapping
def _update_key_values(self):
mapping = self._mapping
if mapping:
sorted_keys, sorted_values = tuple(zip(*sorted(mapping.items())))
else:
sorted_keys, sorted_values = (), ()
keys, values = np.array(sorted_keys), np.array(sorted_values)
self.__sorted_keys = keys
self.__sorted_values = values
return keys, values
@property
def _sorted_keys(self):
if self.__sorted_keys is None:
keys, _ = self._update_key_values()
return self.__sorted_keys
@property
def _sorted_values(self):
values = self.__sorted_values
if values is None:
_, values = self._update_key_values()
return values
@property
def i(self):
"""
Allows to define a subset using positions along the axis
instead of labels.
Examples
--------
>>> sex = Axis('sex', ['M', 'F'])
>>> time = Axis('time', [2007, 2008, 2009, 2010])
>>> arr = ndrange([sex, time])
>>> arr
sex\\time | 2007 | 2008 | 2009 | 2010
M | 0 | 1 | 2 | 3
F | 4 | 5 | 6 | 7
>>> arr[time.i[0, -1]]
sex\\time | 2007 | 2010
M | 0 | 3
F | 4 | 7
"""
return PGroupMaker(self)
@property
def labels(self):
"""
List of labels.
"""
return self._labels
@labels.setter
def labels(self, labels):
if labels is None:
raise TypeError("labels should be a sequence or a single int")
if isinstance(labels, (int, long)):
length = labels
labels = np.arange(length)
iswildcard = True
else:
# TODO: move this to _to_ticks????
# we convert to an ndarray to save memory for scalar ticks (for
# LGroup ticks, it does not make a difference since a list of VG
# and an ndarray of VG are both arrays of pointers)
ticks = _to_ticks(labels)
if _contain_group_ticks(ticks):
# avoid getting a 2d array if all LGroup have the same length
labels = np.empty(len(ticks), dtype=object)
# this does not work if some values have a length (with a valid __len__) and others not
# labels[:] = ticks
for i, tick in enumerate(ticks):
labels[i] = tick
else:
labels = np.asarray(ticks)
length = len(labels)
iswildcard = False
self._length = length
self._labels = labels
self._iswildcard = iswildcard
def extend(self, labels):
"""
Append new labels to an axis or increase its length
in case of wildcard axis.
Note that `extend` does not occur in-place: a new axis
object is allocated, filled and returned.
Parameters
----------
labels : int, iterable or Axis
New labels to append to the axis.
Passing directly another Axis is also possible.
If the current axis is a wildcard axis, passing a length is enough.
Returns
-------
Axis
A copy of the axis with new labels appended to it or
with increased length (if wildcard).
Examples
--------
>>> time = Axis('time', [2007, 2008])
>>> time
Axis('time', [2007, 2008])
>>> time.extend([2009, 2010])
Axis('time', [2007, 2008, 2009, 2010])
>>> waxis = Axis('wildcard_axis', 10)
>>> waxis
Axis('wildcard_axis', 10)
>>> waxis.extend(5)