-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsequence.py
More file actions
2506 lines (2092 loc) · 101 KB
/
sequence.py
File metadata and controls
2506 lines (2092 loc) · 101 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
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Python Computer Graphics Kit.
#
# The Initial Developer of the Original Code is Matthias Baas.
# Portions created by the Initial Developer are Copyright (C) 2004
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
# $Id: rmshader.py,v 1.9 2006/05/26 21:33:29 mbaas Exp $
import sys
import string
import os.path
import re
import glob as _glob
import copy
import shutil
import fnmatch
class SeqString:
"""Sequence string class.
Sequence strings treat numbers inside strings as integer numbers
and not as strings. This can be used to sort numerically (e.g.
``anim01`` is smaller than ``anim0002``).
A sequence string is initialized by passing a regular string to
the constructor. It can be converted back using the :func:`str()` operator.
The main task of a :class:`SeqString` is comparing two strings which can
be done with the normal comparison operators. Example:
>>> a = SeqString('a08')
>>> b = SeqString('a2')
>>> a<b
False
>>> a>b
True
By default, all numbers are treated as unsigned numbers. The constructor
argument *signedNums* can be used to change this behavior. The value
can either be a boolean to turn all numbers into signed numbers which means
any preceding minus sign will be considered to be part of the number or
you may pass a list of indices to only turn certain numbers into signed
numbers. The indices may also be negative if you want to count from the
end. For example, setting *signedNums* to ``[-1]`` will only turn the
last number (which often is the frame number when dealing with file names)
into a signed number and leave all other numbers unsigned.
>>> s=SeqString("sequence-2.-012.tif")
>>> s.getNums()
[2, 12]
>>> s=SeqString("sequence-2.-012.tif", signedNums=True)
>>> s.getNums()
[-2, -12]
>>> s=SeqString("sequence-2.-012.tif", signedNums=[-1])
>>> s.getNums()
[2, -12]
"""
def __init__(self, s=None, signedNums=None):
"""Constructor.
The sequence string is initialized with s which can be a regular
string, another SeqString or anything else that can be turned into
a string using str(s). s can also be None which is equivalent
to an empty string.
signedNum is either a boolean that can be used to turn all numbers
into signed numbers or it may be a list containing the indices of
the numbers that should be treated as signed numbers. An index may
also be negative to count from the end. By default, all numbers
are unsigned.
"""
# This is an alternating sequence of text and number values
# (always beginning and ending with a text (which might both be empty)).
# The value part is a tuple (value,numdigits) where value
# is an integer and numdigits the number of digits the
# value was made of. The list can never be empty (it always contains
# at least one string, even when that one is empty).
# Example: 'anim1_0001.png' -> ['anim', (1,1), '_', (1,4), '.png']
self._value = [""]
self._initSeqString(s)
if signedNums is not None:
if type(signedNums) is bool:
if signedNums:
for i in range(self.numCount()):
self._toSignedNum(i)
elif type(signedNums) is list:
for idx in signedNums:
if type(idx) is not int:
raise TypeError("The items inside the 'signedNums' list must be integers.")
self._toSignedNum(idx)
else:
raise TypeError("Argument 'signedNums' must be a boolean or a list of integers.")
def __repr__(self):
return "'%s'"%self.__str__()
def __str__(self):
"""Convert the sequence string into a normal string.
The number of digits is maintained. The result is the original
string.
"""
return self._valueToStr(self._value)
def _valueToStr(self, valueList):
"""Convert a value list into a string again.
valueList is a list that has the same form as self._value.
"""
res=""
for i, vn in enumerate(valueList):
if i%2==0:
res += vn
else:
val,ndigits = vn
a = '%'+"0%dd"%ndigits
res += a%val
return res
def __eq__(self, other):
return self._cmp(other)==0
def __ne__(self, other):
return self._cmp(other)!=0
def __lt__(self, other):
return self._cmp(other)<0
def __le__(self, other):
return self._cmp(other)<=0
def __gt__(self, other):
return self._cmp(other)>0
def __ge__(self, other):
return self._cmp(other)>=0
def _cmp(self, other):
"""Comparison operator.
The text parts are treated as strings, the number parts as numbers
(e.g. 'a08' is greater than 'a2').
If other is a regular string, then only a regular string comparison
is done.
"""
if other is None:
return 1
if not isinstance(other, SeqString):
if not isinstance(other, basestring):
return 1
# If other is a regular string, then turn self into a string as well
# and use normal string comparison
s = str(self)
if s<other:
return -1
elif s>other:
return 1
else:
return 0
# Check the 'structure' of the strings first.
# The numeric comparison is only done when the strings have the same
# text/num patterns.
res = self.match_cmp(other)
if res!=0:
return res
# Compare the individual components of the values side by side
for i, (a,b) in enumerate(zip(self._value, other._value)):
if i%2==1:
# Get the numbers
a = a[0]
b = b[0]
if a<b:
return -1
if a>b:
return 1
# If we are here everything has been equal so far, but maybe
# one string has one component more in _value
s1 = len(self._value)
s2 = len(other._value)
if s1<s2:
return -1
elif s1>s2:
return 1
else:
return 0
def _initSeqString(self, s):
"""Initialize the sequence string with a string.
s can either be a regular string, another sequence string (to create
a copy) or anything else that can be turned into a string using str(s).
s can also be None which is equivalent to passing an empty string.
Internally, the string is split into its text components and
number components.
"""
if s is None:
s = ""
s = str(s)
textbuf = ""
numtup = (0,0)
res = []
# State
z = 0
for c in s:
# State: Collect text
if (z==0):
# Is this the beginning of a number?
if (c in string.digits):
res.append(textbuf)
numtup = (0,1)
textbuf = c
z = 1
# Store text in buffer
else:
textbuf += c
# State: Collect number
else:
# Another digit?
if (c in string.digits):
numtup = (0,numtup[1]+1)
textbuf += c
# No more digits
else:
numtup = (int(textbuf),numtup[1])
res.append(numtup)
textbuf = c
z = 0
# Add last value
if z==0:
res.append(textbuf)
else:
numtup = (int(textbuf),numtup[1])
res.append(numtup)
res.append("")
self._value = res
def _toSignedNum(self, idx):
"""Turn a number into a signed number.
If the number is preceded by a '-' character, that character is removed
from the string part and the number is negated.
idx is the index of the number. The index may also be negative.
An IndexError exception is thrown if the index is out of range.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
idx *= 2
strVal = self._value[idx]
if strVal.endswith("-"):
# Negate the value following the string
numTup = self._value[idx+1]
self._value[idx+1] = (-numTup[0], numTup[1]+1)
# Remove the '-' from the string
self._value[idx] = strVal[:-1]
def match(self, template, numPos=None):
"""Check if one sequence string is equal to another except for one or all numbers.
Returns ``True`` if the text parts of *self* and *template* are equal,
i.e. both strings belong to the same sequence. *template* must be
a :class:`SeqString` object.
*numPos* is the index of the number that is allowed to vary. For example,
if *numPos* is -1, only the last number in a string may be different for two
strings to be in the same sequence. All other numbers must match exactly
(including the padding). If *numPos* is ``None``, all numbers may vary.
"""
if not isinstance(template, SeqString):
raise TypeError("The template argument must be a SeqString object")
# The lengths of the value lists must be equal
if len(self._value)!=len(template._value):
return False
if numPos is not None:
if numPos<0:
numPos = self.numCount()+numPos
numPos = 2*numPos + 1
for i, (va,vb) in enumerate(zip(self._value, template._value)):
# Only compare the text parts and ignore the numbers
if i%2==0:
if va!=vb:
return False
elif numPos is not None and i!=numPos and va!=vb:
return False
return True
def match_cmp(self, template):
"""Comparison function to build groups.
Compare the text parts (the group name) of two sequence strings.
Numbers within the strings are ignored.
0 is returned if *self* and *template* belong to the same group,
a negative value is returned if *self* comes before *template* and
a positive value is returned if *self* comes after *template*.
"""
a = self.groupRepr()
b = template.groupRepr()
if a<b:
return -1
elif a>b:
return 1
else:
return 0
def fnmatch(self, pattern):
"""Match the string against a file name pattern.
Similar to the function in the :mod:`fnmatch` module, this function
can be used to match the string against a pattern that may contain
wildcards (``"*"``, ``"?"``). Additionally, the pattern may contain
placeholders for numbers which is either a ``"#"`` for a 4-padded
number or a sequence of ``"@"`` characters for a custom padded number.
Note that matching against a number pattern of a certain width will
also match numbers whose width is larger unless they have been padded
with zeros.
Returns ``True`` if the string matches the input pattern.
"""
patternList = []
s = pattern
while 1:
m = re.search(r"#|@+", s)
if m is None:
patternList.append(s)
break
patternList.append(s[:m.start()])
p = m.group()
if p=="#":
patternList.append(4)
else:
patternList.append(len(p))
s = s[m.end():]
return self._fnmatch(self._value, patternList)
def _fnmatch(self, valueList, patternList):
"""Helper function for fnmatch.
valueList is a list of the same form as self._value.
patternList is a list of the form [string, int, string, int, ...]
where string is a fnmatch pattern and the integer is the number of
digits that a number at this position must have (larger numbers are
allowed as well as there could have been an overflow when the original
string was created).
patternList must have an odd number of items (which also means it must
not be empty).
"""
prefixPattern = patternList[0]
# Is there only one item in patternList? Then there is no number anymore
# and we just have to do a normal fnmatch call...
if len(patternList)==1:
s = self._valueToStr(valueList)
return fnmatch.fnmatch(s, prefixPattern)
numDigits = patternList[1]
# Iterate over all numbers in the valueList and check if it fulfills
# the numDigits constraint. If it does, check whether the preceding
# string matches the string prefix pattern. If all that matches, we
# can call _fnmatch recursively with the remaining parts.
for i in range(1,len(valueList), 2):
val,ndig = valueList[i]
# Is the current number a match for the pattern?
if ndig==numDigits or (ndig>numDigits and not self._valueToStr(["",(val,ndig)]).startswith("0")):
# Check if the string prior to the number matches as well
prefix = self._valueToStr(valueList[:i])
if fnmatch.fnmatch(prefix, prefixPattern):
if self._fnmatch(valueList[i+1:], patternList[2:]):
return True
return False
def groupRepr(self, numChar="*"):
"""Return a template string where the numbers are replaced by the given character.
"""
res=""
numChar = str(numChar)
for i,v in enumerate(self._value):
if i%2==0:
res += v
else:
res += numChar
return res
def numCount(self):
"""Return the number of number occurrences in the string.
Examples:
- ``anim01.tif`` -> 1
- ``anim1_018.tif`` -> 2
- ``anim`` -> 0
"""
return len(self._value)//2
def getNum(self, idx):
"""Return a particular number inside the string.
*idx* is the index of the number (0-based) which may also be
negative. The return value is an integer containing the number
at that position.
Raises an :exc:`IndexError` exception when *idx* is out of range.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
return self._value[idx*2+1][0]
def getNumStr(self, idx):
"""Return a particular number as a string just as it appears in the original string.
*idx* is the index of the number (0-based) which may also be
negative. The return value is a string that contains the number
as it appears in the string (including padding).
Raises an :exc:`IndexError` exception when *idx* is out of range.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
val,ndigits = self._value[idx*2+1]
a = '%'+"0%dd"%ndigits
return a%val
def getNums(self):
"""Return all numbers.
Returns a list of all numbers in the order as they appear in the string.
"""
res=[]
for i in range(self.numCount()):
res.append(self.getNum(i))
return res
def setNum(self, idx, value, width=None):
"""Set a new number.
*idx* is the index of the number (may be negative) and *value*
is the new integer value. If *width* is given, it will be the new
width of the number, otherwise the number keeps its old width.
Raises an :exc:`IndexError` exception when *idx* is out of range.
Note: It is possible to set a negative value. But when converted to
a string and then back to a sequence string again, that negative
number becomes a positive number and the minus symbol is part of
the preceding text part.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
if width is None:
width = self._value[idx*2+1][1]
self._value[idx*2+1] = (int(value),int(width))
def setNums(self, nums):
"""Set all numbers at once.
*nums* is a list of integers. The number of values may not
exceed the number count in the string, otherwise an :exc:`IndexError`
exception is thrown. There may be fewer items in *nums* though in
which case the remaining numbers in the string keep their old value.
"""
for i,val in enumerate(nums):
self.setNum(i, val)
def getNumWidth(self, idx):
"""Return the number of digits of a particular number.
*idx* is the index of the number (may be negative).
Raises an :meth:`IndexError` exception when *idx* is out of range.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
return self._value[idx*2+1][1]
def setNumWidth(self, idx, width):
"""Set the number of digits of a number.
*idx* is the index of the number (may be negative) and *width*
the new number of digits.
Raises an :exc:`IndexError` exception when *idx* is out of range.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
width = int(width)
val = self._value[idx*2+1][0]
self._value[idx*2+1] = (val,width)
def getNumWidths(self):
"""Return the number of digits of all numbers.
Returns a list of width values.
"""
res=[]
for i in range(self.numCount()):
res.append(self.getNumWidth(i))
return res
def setNumWidths(self, widths):
"""Set the number of digits for all numbers.
*widths* must be a list of integers. The number of values may not
exceed the number count in the string, otherwise an :exc:`IndexError`
exception is thrown.
"""
for i,w in enumerate(widths):
self.setNumWidth(i, w)
def deleteNum(self, idx):
"""Delete a number inside the string.
This is the same as replacing the number by an empty string.
*idx* is the index of the number (0-based) which may also be
negative.
Raises an :exc:`IndexError` exception when *idx* is out of range.
"""
self.replaceNum(idx, "")
def replaceNum(self, idx, txt):
"""Replace a number by a string.
The string is merged with the surrounding string parts.
*idx* is the index of the number (0-based) which may also be
negative. *txt* is a string that will replace the number.
Raises an :exc:`IndexError` exception when *idx* is out of range.
"""
if idx<0:
idx = self.numCount()+idx
if idx<0 or idx>=self.numCount():
raise IndexError("index out of range")
# Insert the text
self._value[idx*2] += str(txt)
# Concatenate the adjacent texts
if len(self._value)>idx*2+2:
self._value[idx*2] += self._value[idx*2+2]
# Remove the number
del self._value[idx*2+1:idx*2+3]
def replaceStr(self, idx, txt):
"""Replace a string part by another string.
*idx* is the index of the sub-string (0-based) which may also be
negative. *txt* is a string that will replace the sub-string.
Raises an :exc:`IndexError` exception when *idx* is out of range.
"""
if idx<0:
idx2 = len(self._value)+2*idx
# Does the value list end in a text part? Then we need to adjust the index
if len(self._value)%2==1:
idx2 += 1
else:
idx2 = 2*idx
# Check if the index is valid
if idx2<0 or idx2>=len(self._value):
raise IndexError("index out of range")
# Replace the text
self._value[idx2] = str(txt)
class Sequence:
"""A list of names/objects that all belong to the same sequence.
The sequence can store the original objects that are associated with a
name or it can only store the names (as :class:`SeqString` objects).
Whether the original objects are available or not depends on how the
sequence was built. If the *nameFunc* parameter was used when building
the sequence (see :func:`buildSequences`), then the original objects will be available.
The class can be used like a list (using :func:`len()`, index operator or
iteration).
"""
def __init__(self):
"""Constructor.
"""
# A list of file names (stored as SeqString objects)
self._names = []
# The actual objects. This is either a list that always has as many
# items as _names or it is None.
self._objects = None
def __str__(self):
placeholder,ranges = self.sequenceName()
if len(ranges)==0:
return placeholder
else:
infoStr = "; ".join(ranges)
if len(infoStr)>20:
infoStr = "%d items"%len(self._names)
return "%s (%s)"%(placeholder, infoStr)
def __repr__(self):
return "<Sequence %s>"%self.__str__()
def __len__(self):
"""Return the length of the sequence.
"""
return len(self._names)
def __getitem__(self, idx):
"""Return the object at position idx.
The return value is either the original object that was stored
in the sequence or it is a SeqString containing the name if the
original object was just a string.
"""
if self._objects is None:
return self._names[idx]
else:
return self._objects[idx]
def iterNames(self):
"""Iterates over the object names.
Yields :class:`SeqString` objects.
"""
return iter(self._names)
def iterObjects(self):
"""Iterate over the objects.
Yields the original objects or the names as :class:`SeqString` objects
if the objects haven't been stored in the sequence.
Using this method is equivalent to iterating over the sequence
object directly.
"""
if self._objects is None:
return self.iterNames()
else:
return iter(self._objects)
def match(self, name, numPos=None):
"""Check if a name matches the names in this sequence.
*name* is a string or :class:`SeqString` object that is tested if
it matches the names in the sequence.
If the sequence doesn't contain any name at all yet, then any name
will match.
*numPos* is an integer that specifies which number is allowed to
vary. If *numPos* is ``None``, all numbers may vary.
"""
# Turn the name into a SeqString
if not isinstance(name, SeqString):
name = SeqString(name)
if len(self._names)==0:
return True
else:
return self._names[0].match(name, numPos)
def append(self, name, obj=None):
"""Append a name/object to the end of the sequence.
*name* can be a :class:`SeqString` object or a regular string.
The name must match the names in the sequence, otherwise a
:exc:`ValueError` exception is thrown.
*obj* can be any Python object that is stored alongside the name
(this is supposed to be the actual object that has the given name).
In any sequence, either all or none of the names must be associated
with an object. An attempt to append a name without an object to a
sequence that has objects will trigger a :exc:`ValueError` exception.
Usually, you won't call this method manually to build a sequence
but instead use the :func:`buildSequences()` function which returns
initialized ``Sequence`` objects.
"""
# Turn the name into a SeqString
if not isinstance(name, SeqString):
name = SeqString(name)
if not self.match(name):
placeholder,_ranges = self.sequenceName()
raise ValueError("Cannot add '%s' to sequence %s. The name doesn't match the sequence."%(name, placeholder))
if obj is not None:
if self._objects is None:
if len(self._names)==0:
self._objects = []
else:
raise ValueError("objects must be given for all or none of the names")
self._objects.append(obj)
elif self._objects is not None:
raise ValueError("objects must be given for all or none of the names")
self._names.append(name)
def sequenceNumberIndex(self):
"""Return the index of the sequence number.
Returns the index of the number that has the most variation among its
values. If two number positions have the same variation, then the last
number is returned.
Returns ``None`` if there is no number at all.
"""
ranges = self.ranges()
# This will be the index of the number that varies most (i.e. the index of the sequence number)
seqNumIdx = None
maxValues = -1
for i,rng in enumerate(ranges):
lr = len(rng)
if lr>=maxValues:
maxValues = lr
seqNumIdx = i
return seqNumIdx
def ranges(self):
"""Returns a list of all the number ranges in the sequence.
The return value is a list of :class:`Range` objects. There are as many
ranges as there are separate numbers in the names. The ranges
are given in the same order as the corresponding number appears in
the names.
"""
_name,rangeStrs = self._nameAndRangeStrs()
return list(map(lambda x: Range(x), rangeStrs))
def sequenceName(self):
"""Return a sequence placeholder and range strings.
Returns a tuple (*placeholder*, *ranges*) where *placeholder* is the
name of a member of the sequence where all numbers have been replaced
by ``'#'`` (0-padded number with 4 digits) or one or more ``'@'`` (padded
number with as many digits as there are ``'@'`` characters. Just a single
``'@'`` represents an unpadded number). If the sequence contains inconsistent
padding, the number is replaced by ``'*'``.
The number is not replaced at all if there is only one single value
among all file names anyway.
*ranges* is a list of strings where each string describes the range
of values of the corresponding number in the placeholder string.
The returned information is meant to be displayed to the user as
information about the sequence. It is not possible to reconstruct
all original file names (unless the placeholder contains no more than
one substitution).
"""
name,rangeStrs = self._nameAndRangeStrs(ignoreSingleValues=True)
return name,rangeStrs
def _nameAndRangeStrs(self, ignoreSingleValues=False):
"""Helper method for sequenceName() and ranges().
Returns a tuple (placeholder, ranges). See sequenceName().
if ignoreSingleValues is True, any number in the sequence names
whose range only consists of a single value will not be replaced
by # or @ and will not appear in the "ranges" list.
"""
if len(self._names)==0:
return "", []
# How many numbers do we have in the string?
n = self._names[0].numCount()
if n==0:
return str(self._names[0]), []
# The minimum width of every number
minWidths = self._names[0].getNumWidths()
# The maximum width of every number
maxWidths = list(minWidths)
# A flag indicating whether the number is unpadded or not
unpadded = len(minWidths)*[True]
# A list of values
values = []
for i in range(n):
values.append([])
# Collect all required values from the names
for name in self._names:
for i in range(name.numCount()):
v = name.getNum(i)
w = name.getNumWidth(i)
# Update the minimum width
minWidths[i] = min(w, minWidths[i])
# Update the maximum width
maxWidths[i] = max(w, maxWidths[i])
# Update the unpadded flag
if len(str(v))<w:
unpadded[i] = False
# Update the value list (don't append if the last value is the same as v)
if len(values[i])==0 or values[i][-1]!=v:
values[i].append(v)
# Compute the sequence name that has the numbers replaced by placeholders
res = copy.deepcopy(self._names[0])
rangeStrs = []
for i in range(len(minWidths)):
# If there is only one single value anyway then just leave the number
if ignoreSingleValues and len(values[i])==1:
# The index is 0 because previous number have already been replaced by strings
s = res.getNumStr(0)
else:
rangeStrs.append(compactRange(values[i]))
if minWidths[i]==maxWidths[i]:
n = minWidths[i]
if n==4:
s = "#"
else:
s = n*"@"
elif unpadded[i]:
n = minWidths[i]
s = n*"@"
else:
s = "*"
# The number index is always 0 because we are replacing the numbers
# one by one (which reduces the numcount)
res.replaceNum(0, s)
return str(res), rangeStrs
class Range:
"""Range class.
This class represents a sorted sequence of integer values (frame numbers).
The sequence is composed of a number of sub-ranges which have a begin,
an optional end and an optional step number. If the end is omitted,
the sequence will be infinite.
Examples:
>>> list(Range("1,5,10"))
[1, 5, 10]
>>> list(Range("1-5"))
[1, 2, 3, 4, 5]
>>> list(Range("2-8x2"))
[2, 4, 6, 8]
>>> list(Range("1-3,10-13"))
[1, 2, 3, 10, 11, 12, 13]
The range object supports the :func:`len()` operator, comparison operators,
the :obj:`in` operator and iteration. Examples:
>>> rng = Range("1-2,5")
>>> len(rng)
3
>>> for i in rng: print i
...
1
2
5
>>> 3 in rng
False
>>> 5 in rng
True
>>> Range("1-3")==Range("1,2,3")
True
>>> Range("1-5")==Range("2-6")
False
"""
def __init__(self, rangeStr=None):
"""Constructor.
"""
# The individual sub-ranges.
# This is a list of tuples (begin,end,step) where each value is an integer.
# begin is the first value of the range, end the last value or None
# for an infinite sub-range. step is the difference between subsequent
# values.
# The following conditions must always be met by all items:
# - end>=begin (if end is not None)
# - (end-begin)%step == 0
self._ranges = []
# Set the initial range
self.setRange(rangeStr)
def __str__(self):
"""Return a string describing the range.
"""
rangeStrs = []
for begin,end,step in self._ranges:
if begin==end:
rangeStrs.append(str(begin))
else:
if step==1:
stepStr = ""
else:
stepStr = "x%s"%step
if end is None:
endStr = ""
else:
endStr = str(end)
rangeStrs.append("%s-%s%s"%(begin,endStr,stepStr))
return ",".join(rangeStrs)
__repr__ = __str__
def __eq__(self, other):
"""Equality operator
"""
if not isinstance(other, Range):
return False
return self._ranges==other._ranges
def __ne__(self, other):
"""Inequality operator
"""
if not isinstance(other, Range):
return True
return self._ranges!=other._ranges
def __len__(self):
"""Return the number of values in the sequence.
A ValueError exception is thrown if the sequence is infinite.
"""
res = 0
for begin,end,step in self._ranges:
if end is None:
raise ValueError("Cannot return length of infinite range")
res += ((end-begin)//step)+1
return res
def __iter__(self):
"""Iterate over all individual values in the range.
The values are reported in increasing order. No value is reported twice.
Note that the sequence will be infinite if isInfinite() returns True.
"""
# Copy the _ranges list and convert the tuples to lists.
# The "begin" value will be increased during the iteration.
currentValues = list(map(lambda x: list(x), self._ranges))