5 from os
.path
import abspath
, exists
13 from colors
import BlackWhite
16 VIEWER_LIST
=['qgo', 'kombilo']
18 def viewer_open(sgf_filename
, executable
=VIEWER_LIST
[1]):
19 p
= subprocess
.Popen([executable
, sgf_filename
])
23 subprocess
.call('bark', shell
=True)
25 def check_output(*args
, **kwargs
):
26 if hasattr(subprocess
, 'check_output'):
27 return subprocess
.check_output(*args
, **kwargs
)
29 if 'stdout' in kwargs
:
30 raise ValueError('stdout argument not allowed, it will be overridden.')
31 process
= subprocess
.Popen(stdout
=subprocess
.PIPE
, *args
, **kwargs
)
32 output
, unused_err
= process
.communicate()
33 retcode
= process
.poll()
35 cmd
= kwargs
.get("args")
38 raise subprocess
.CalledProcessError(retcode
, cmd
, output
=output
)
41 def get_year(datestr
, match_century
=True):
42 """Function trying to extract date from a string - usually a DT field of a sgf_file.
43 First, look for the first year string in the @datestr.
44 if not found and the @match_century is true, we look for strings like
45 "18th century", which results in year 1750 (the mean of years in 18th century)
47 Returns None if no year found.
50 # note the non-greedy .*? expansion => the first date string in the result gets matched
51 # that is get_year("1982 1999") = 1982
52 match
= re
.match( '.*?([0-9]{4}).*', datestr
)
54 return int(match
.group(1))
57 # 17th century, 18th c.
58 match
= re
.match( '.*[^0-9]?([0-9]{2}th c).*', datestr
)
60 century
= int(match
.group(1)[:2])
61 # returns "mean" year of the century:
62 # 17th century -> 1650
63 return century
* 100 - 50
67 def get_poly_s(coefs
):
68 """Returns a string with polynomial equation; e.g.:
70 >>> from utils import get_poly_s
71 >>> get_poly_s([0.5,0,4])
73 >>> get_poly_s([1,2,3,4])
74 'y = 1.00x^3 + 2.00x^2 + 3.00x + 4.00'
77 for pw
, co
in enumerate(reversed(coefs
)):
85 return 'y = ' + ' + '.join(reversed(C
))
90 class ReprWrapper(object):
91 def __init__(self, repr_f, f):
94 functools.update_wrapper(self, f)
95 def __call__(self, *args, **kwargs):
96 return self.f(*args, **kwargs)
98 return self.repr_f(self.f)
102 if hasattr(f
, 'im_class'):
105 prefix
= f
.__module
__
106 return "%s.%s"%(prefix
, f
.__name
__)
110 with
open(f
.filename
, 'r') as fin
:
111 for line
in itertools
.islice(fin
, n
):
114 def iter_splits(l
, parts
=None, max_size
=None, min_size
=None):
115 """Will yield consequent sublist of the @l list, trying to result
116 evenly sized sublists. Exactly one of the parameters @parts or
117 @max_size or @min_size must be specified.
119 specifiing parts = N will yield N sublists of (almost) even size. The
120 list size difference is guaranted to be at most 1.
122 >>> list(iter_splits(range(5), parts=2))
124 >>> list(iter_splits(range(5), parts=4))
125 [[0, 1], [2], [3], [4]]
129 specifiing max_size = N returns the smallest possible number of
130 consequent sublists so that whole list is divided and size of each
133 >>> list(iter_splits(range(5), max_size=3))
135 >>> list(iter_splits(range(5), max_size=10))
138 Calling iter_splits(l, max_size=N) is just a shorthand for calling
139 iter_splits(l, parts=len(l) / N + bool(len(l)% N) )
143 Similarly min_size = N returns the largest possible number of
144 consequent sublists so that whole list is divided and size of each
147 Calling iter_splits(l, min_size=N) is just a shorthand for calling
148 iter_splits(l, parts=len(l) / N )
150 if bool(parts
) + bool(max_size
) + bool( min_size
) != 1:
151 raise TypeError('Exactly one of parts, max_size or exact_size arguments must be specified (and nonzero)')
155 pn
, rest
= len(l
) / parts
, len(l
) % parts
157 raise ValueError("Number of parts to split must not be larger than the number of elements.")
160 for i
in xrange(parts
):
168 for size
in sizes(pn
, rest
):
169 start
, stop
= stop
, stop
+ size
173 pn
, rest
= len(l
) / max_size
, len(l
) % max_size
176 for split
in iter_splits(l
, parts
=pn
):
180 for split
in iter_splits(l
, parts
=len(l
)/min_size
):
183 def iter_exact_splits(l
, split_size
):
187 head
, tail
= tail
[:split_size
], tail
[split_size
:]
188 # the last head could be shorter
189 if len(head
) == split_size
:
192 def pearson_coef(vec1
, vec2
):
193 assert vec1
.shape
== vec2
.shape
195 return numpy
.sqrt((vec
*vec
).sum())
197 return vec
- vec
.mean()
198 vec1
, vec2
= center(vec1
), center(vec2
)
199 return (vec1
* vec2
).sum() / (norm(vec1
) * norm(vec2
))
202 if __name__
== '__main__':
206 for kw
in ['parts', 'max_size', 'min_size']:
207 for val
in range(10, 20):
208 print "iter_splits(%s, **{%s : %s}))" % (l
, kw
, val
)
209 res
= list(iter_splits(l
, **{kw
: val
}))
211 print " len = ", len(res
), ", max(size) = ", max(map(len, res
)), ", min(size) = ", min(map(len, res
))
214 assert list(itertools
.chain
.from_iterable(res
)) == l
216 assert len(res
) == val
218 assert max(map(len, res
)) <= val
220 assert min(map(len, res
)) >= val
225 get_random_output_base(0, 1)