forked from ryanGT/krauss_misc
/
rwkmisc.py
executable file
·708 lines (583 loc) · 19.4 KB
/
rwkmisc.py
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
# rwk misc module
import scipy, numpy
import time
import os, glob, re, sys
from numpy import *
import copy
#from IPython.core.debugger import Pdb
#mytrace=Pdb().set_trace
import pickle
def get_date_str():
date_str = time.strftime('%m_%d_%y')
return date_str
def clean_list(listin):
"""Remove blank entries from the start and end of the list."""
listout = copy.copy(listin)
while not listout[0]:
listout.pop(0)
while not listout[-1]:
listout.pop()
return listout
def clean_list_regexp(listin, pat='^[ ,]*$'):
listout = copy.copy(listin)
p = re.compile(pat)
while p.match(listout[0]):
listout.pop(0)
while p.match(listout[-1]):
listout.pop()
return listout
def RegExpPop(listin, pat, returnq=False, multiline=False):
if multiline:
mystr = '\n'.join(listin)
p = re.compile(pat, flags=re.DOTALL)
q = p.search(mystr)
if q:
out = q.group()
newstr = p.sub('',mystr)
listin = newstr.split('\n')
else:
p = re.compile(pat)
out = None
for n, item in enumerate(listin):
q = p.search(item)
if q:
out = listin.pop(n)
break
if returnq:
return q
else:
return out
def PrintToScreen(listin, globals):
if type(listin)==str:
listin=[listin]
for item in listin:
print(item+'=%s'%eval(item, globals))
def SavePickle(mydict, filepath, protocol=2):
"""Dump dictionary mydict to a Pickle file filepath using pickle,
protocol=2."""
mypkl = open(filepath,'wb')
pickle.dump(mydict, mypkl, protocol=protocol)
mypkl.close()
def LoadPickle(filepath):
mypkl = open(filepath,'rb')
mydict = pickle.load(mypkl)
mypkl.close()
return mydict
class object_that_saves(object):
"""This is a mixin class for saving and loading objects using
SavePickle and LoadPickle. The object must have saveattrs
defined; it is a list of strings that refer to the attributes to
save and/or load."""
def build_dict(self):
mydict = {}
for attr in self.saveattrs:
val = getattr(self, attr)
mydict[attr] = val
return mydict
def set_attrs(self, mydict):
for attr, val in mydict.iteritems():
setattr(self, attr, val)
def save(self, filepath, protocol=2):
mydict = self.build_dict()
SavePickle(mydict, filepath, \
protocol=protocol)
def load(self, filepath):
mydict = LoadPickle(filepath)
self.set_attrs(mydict)
class gui_that_saves(object_that_saves):
"""This class suplements object_that_saves by appyling it to guis
where there will be different methods associated with getting and
setting each parameter in the dictionary of saved properties."""
def _initialize_saving(self):
"""Because this is intended to be a mixin class, it doesn't
really have a true __init__ method. This method serves that
purposed by creating the empty dictionaries for get and set
methods."""
self.get_dict = {}
self.set_dict = {}
self.saveattrs = []
def append_item(self, key, get_method, set_method):
self.get_dict[key] = get_method
self.set_dict[key] = set_method
self.saveattrs.append(key)
def build_dict(self):
mydict = {}
for attr in self.saveattrs:
get_method = self.get_dict[attr]
val = get_method()
mydict[attr] = val
return mydict
def set_attrs(self, mydict):
for attr, val in mydict.iteritems():
set_method = self.set_dict[attr]
set_method(val)
def load_from_pickle(filename, key):
mydict = LoadPickle(filename)
return mydict[key]
def myglob(pattern, folder=None):
if folder is not None:
totalpattern = os.path.join(folder, pattern)
else:
totalpattern = pattern
myfiles = glob.glob(totalpattern)
if folder is not None:
outnames = []
for item in myfiles:
fout, name = os.path.split(item)
outnames.append(name)
else:
outnames = myfiles
return outnames
class rwkstr(str):
def findall(self, pattern):
inds=[]
remainingstr=copy.deepcopy(self)
donestr=''
while remainingstr.find(pattern)>-1:
nextind=remainingstr.find(pattern)
absind=nextind+len(donestr)
inds.append(absind)
donestr+=remainingstr[0:nextind+1]
remainingstr=remainingstr[nextind+1:]
return inds
def replace(self,old,new,startind=0,maxreplace=-1):
# print('in rwk replace')
if old==new:
return rwkstr(self)
else:
if startind>0:
prestr=self[0:startind]
rest=self[startind:]
outstr=rest.replace(old,new,maxreplace=maxreplace)
outstr=prestr+outstr
return rwkstr(outstr)
else:
return rwkstr(str.replace(self,old,new,maxreplace))
def __getslice__(self,si,ei):
# print('in rwkstr getslice')
return rwkstr(str.__getslice__(self,si,ei))
def afterlast(self,pattern):
ind=self.rfind(pattern)
if ind>-1:
firstpart=self[0:ind]
lastpart=self[ind+len(pattern):]
return firstpart,lastpart
else:
return self, ''
def beforefirst(self,pattern,startind=0):
ind=self.find(pattern,startind)
if ind>-1:
firstpart=self[0:ind]
lastpart=self[ind+len(pattern):]
return rwkstr(firstpart), rwkstr(lastpart)
else:
return self,''
def contains(self,substr):
return self.find(substr)!=-1
class symstr(rwkstr):
def containsoperators(self,oplist=['*','+','-','/','**']):
for co in oplist:
if self.find(co)>-1:
return True
break
else:
return False
def __addparen__(self,oplist=['*','+','-','/','**']):
if self.containsoperators(oplist):
return '('+self.__str__()+')'
else:
return self.__str__()
def __add__(self,other):
return symstr(self.__str__()+'+'+str(other))
def __sub__(self,other):
myops=['+','-']
if not type(other)==symstr:
other=symstr(other)
return symstr(self.__str__()+'-'+other.__addparen__(myops))
def __mul__(self,other):
myops=['+','-']
if not type(other)==symstr:
other=symstr(other)
return symstr(self.__addparen__(myops)+'*'+other.__addparen__(myops))
# def __pow__(self,other):
# return symstr(self+'^'+symstr(other).__addparen__())
def __rmul__(self,other):
myops=['+','-']
if not type(other)==symstr:
other=symstr(other)
return symstr(other.__addparen__(myops)+'*'+self.__addparen__(myops))
def __div__(self,other):
# Pdb().set_trace()
myops=['+','-']
if not type(other)==symstr:
other=symstr(other)
return symstr(self.__addparen__(myops)+'/'+other.__addparen__())
def __rdiv__(self,other):
return symstr(other).__div__(self)
def __rtruediv__(self,other):
return self.__rdiv__(other)
def __truediv__(self,other):
return self.__div__(other)
def __pow__(self,other):
if not type(other)==symstr:
other=symstr(other)
return symstr(self.__addparen__()+'**'+other.__addparen__())
def __neg__(self):
return symstr('-'+self)
class dictobject:
def __init__(self,**kwargs):
for key,value in kwargs.iteritems():
setattr(self,key,value)
def SortLists(sortbylist,otherlists,reverse=False):
"""This function sorts lists similar to each list being a column
of data in a spreadsheet program and choosing one column to sort
by.
The sortbylist is the column or list that you wish to sort by and
otherlists is a list of the other lists or columns to sort.
Reverse is passed to the sort method of sortbylist."""
newlist=sortbylist[:]
newlist.sort(reverse=reverse)
bigoutlist=[]
for list in otherlists:
curlist=[]
for curitem in newlist:
ind=sortbylist.index(curitem)
curlist.append(list[ind])
bigoutlist.append(curlist)
return (newlist,)+tuple(bigoutlist)
def transposed(lists):
if not lists: return []
return map(lambda *row: list(row), *lists)
def rwkWriteArray(file, array, append=0): #open or create file and append or write array to it
if append:
f=open(file,'a')
else:
f=open(file,'w')
for curline in array:
f.write(curline)
f.close()
def mydirfilter(pathin,ignoredirs):
"""pathin is assumed to be a path to a directory
this function returns true if the last folder
is not in the list of ignoredirs"""
temproot, curdir=os.path.split(pathin)
return curdir not in ignoredirs
def rwkFileSearchRecursive(pattern,root,outpath="",ignoredirs=[]):
"""Starting in root, walk down through the
file structure searching for pattern. The
results are returned as a list of full paths.
If outpath is specified, the output is also
written to it as an ASCII text file."""
topdirs=glob.glob(os.path.join(root,'*'))
topdirs=[item for item in topdirs if os.path.isdir(item)]
topdirs=[item for item in topdirs if mydirfilter(item,ignoredirs)]
allpaths=[]
rootpat=os.path.join(root,pattern)
rootfiles=glob.glob(rootpat)
allpaths.extend(rootfiles)
for curroot in topdirs:
rootpat=os.path.join(curroot,pattern)
rootfiles=glob.glob(rootpat)
allpaths.extend(rootfiles)
for root, dirs, files in os.walk(curroot):
for name in dirs:
curpath=os.path.join(root,name)
print('searching:'+curpath)
curpat=os.path.join(curpath,pattern)
curfiles=glob.glob(curpat)
allpaths.extend(curfiles)
if outpath:
rwkWriteArray(outpath,allpaths)
return allpaths
def rwkFileSearch(pattern,searchdir="",outfile="",append=0):
"""Search for pattern in searchdir without recursing into
the directory (does not walk the directory tree).
Returns files found as a list of filenames (not full paths).
If outfile is specified, the results are also written to
it (or appended) as a text file."""
# import glob
# import os
# curdir=os.getcwd()
# if len(searchdir)>0:
# os.chdir(searchdir)
#--------------------------------------------------
# print 'pattern='+pattern
# print 'curdir='+os.getcwd()
#--------------------------------------------------
curpat=os.path.join(searchdir,pattern)
texfiles=glob.glob(curpat)
#--------------------------------------------------
# print 'filelist:'
#--------------------------------------------------
if len(outfile)>0:
filestoprint=[]
for k,curfile in enumerate(texfiles):
filestoprint.append(curfile + '\n')
rwkWriteArray(outfile,filestoprint,append)
# os.chdir(curdir)
return texfiles
def mycomp(strin, pattern, exact=False):
"""check pattern against strin. If exact, then retrun
pattern==strin, else return strin.find(pattern)>-1."""
if exact:
return bool(strin==pattern)
else:
return bool(strin.find(pattern)>-1)
def searchlist(listin, str2find, exact=False, casesense=False):
"""search for str2find in listin, return first index containing
str2find, or -1 if it is not found.
If exact is False, return the first index that contains str2find,
otherwise require item == str2find for item in listin.
casesense calls lower() on str2find and the items of listin."""
indout=-1
if not casesense:
str2find=str2find.lower()
for k, curstr in enumerate(listin):
if not casesense:
curstr=curstr.lower()
if mycomp(curstr, str2find, exact=exact):
indout=k
break
return indout
def my_import(name):
folder, modname = os.path.split(name)
if folder:
if folder not in sys.path:
sys.path.append(folder)
mod = __import__(modname)
components = modname.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def reverse( x ):
# Pdb().set_trace()
if hasattr(x,'tolist'):
return scipy.array(reverse(x.tolist()))
l2 = len(x)/2
if l2:
return reverse(x[l2:]) + reverse(x[:l2])
else:
return x
def null(A, eps=1e-10):
u, s, vh = scipy.linalg.svd(A)
null_mask = (s <= eps)
null_space = scipy.compress(null_mask, vh, axis=0)
return scipy.transpose(scipy.conj(null_space))
def colwise(matin,makecopy=1):
# t1=time.time()
if makecopy:
tempmat=copy.deepcopy(matin)
else:
tempmat=matin
# t2=time.time()
# print('copy time='+str(t2-t1))
matout=scipy.atleast_2d(tempmat)
myshape=scipy.shape(matout)
if myshape[0]<myshape[1]:
matout=scipy.transpose(matout)
return matout
def rowwise(matin,makecopy=1):
# t1=time.time()
if makecopy:
tempmat=copy.deepcopy(matin)
else:
tempmat=matin
# t2=time.time()
# print('copy time='+str(t2-t1))
matout=scipy.atleast_2d(tempmat)
myshape=scipy.shape(matout)
if myshape[0]>myshape[1]:
matout=scipy.transpose(matout)
return matout
#def __printent(ent, eps=1e-14,bigthresh=10000,littlethresh=1e-5,width=8):
# """Assumes only real input and is meant to be called by other functions like printent."""
# if abs(ent)>bigthresh or ans(ent)<littlethresh:
# fmt='%0.'+str(width-4)+'e'
# else:
# fmt='%'+str(width)+'g'
# if eps is not None and abs(ent)<eps:
# return '0'
# else:
# return fmt%ent
#def PrettyMat(mat,eps=1e-14):
# imat=imag(mat)
# rmat=real(mat)
# if rmat.any() and imat.any():
# width=6
# else:
# width=8
# for row in mat:
# rowstr='['
# for ent in row:
# if imag(ent):
# rstr=__printent(real(ent),width=width)
def cleannum(value, eps=1e-14):
if numpy.abs(value) < eps:
return 0
elif abs(numpy.real(value)) < eps:
return 1.0j*imag(value)
elif abs(numpy.imag(value)) < eps:
return numpy.real(value)
def prettyvect(vect,fmt='%0.5g',eps=1e-14):
filtvect = [cleannum(item,eps) for item in vect]
strlist = [fmt % item for item in filtvect]
str1 = ', '.join(strlist)
str2 = '[' + str1 + ']'
return str2
def prettymat(mat,fmt='%0.5g',eps=1e-14):
# pdb.set_trace()
if fmt[0]=='%':
ifmt='%+'+fmt[1:]
else:
ifmt='%+'+fmt
fmt='%'+fmt
nc=scipy.shape(mat)[1]
# print('[')
outstr='['
# fmtstr=fmt +(nc-1)*(' & ' +fmt)+'\\\\'
for currow in mat.tolist():
# curtuple=tuple(currow)
# rowstr=fmtstr%curtuple
rowstr='['
for x,ent in enumerate(currow):
if abs(scipy.real(ent))>eps:
realstr=fmt%scipy.real(ent)
else:
realstr='0'
if abs(scipy.imag(ent))>eps:
imagstr=ifmt%scipy.imag(ent)+'j'
else:
imagstr=''
rowstr+=realstr+imagstr
if x<(len(currow)-1):
rowstr+=', '
if x==(len(currow)-1):
rowstr+='],\n'
outstr+=rowstr
if outstr[-1]=='\n':
outstr=outstr[0:-1]
outstr+=']'
print(outstr)
# return outstr
def RREFscaled(mymat):
# Pdb().set_trace()
scalevect=scipy.amax(abs(mymat),1)
scaledrows=[]
for sf,row in zip(scalevect,mymat):
row=row/sf
scaledrows.append(row)
scaledmat=scipy.vstack(scaledrows)
# scaledmat=mymat
nc=scipy.shape(scaledmat)[1]
nr=scipy.shape(scaledmat)[0]
for j in range(nr-1):
# print('=====================')
# print('j='+str(j))
pivrow=scipy.argmax(abs(scaledmat[j:-1,j]))
pivrow=pivrow+j
# print('pivrow='+str(pivrow))
if pivrow!=j:
temprow=copy.copy(scaledmat[j,:])
scaledmat[j,:]=scaledmat[pivrow,:]
scaledmat[pivrow,:]=temprow
# Pdb().set_trace()
for i in range(j+1,nr):
# print('i='+str(i))
scaledmat[i,:]-=scaledmat[j,:]*(scaledmat[i,j]/scaledmat[j,j])
return scaledmat, scalevect
def ColSwap(matin,c1,c2):
tempcol=copy.deepcopy(matin[:,c1])
matin[:,c1]=matin[:,c2]
matin[:,c2]=tempcol
return matin
def RowSwap(matin,r1,r2):
# pdb.set_trace()
temprow=scipy.zeros((1,scipy.shape(matin)[1]),'d')
temprow=copy.deepcopy(matin[r1,:])
# temprow=matin[r1,:]
matin[r1,:]=matin[r2,:]
matin[r2,:]=temprow
return matin
def minindex(listin):
mymin=min(listin)
for x, ent in enumerate(listin):
if ent==mymin:
return x
def maxindex(listin):
mymax=max(listin)
for x, ent in enumerate(listin):
if ent==mymax:
return x
def ToLatexString(strin,appenddol=1):
outstr=strin.lower()
latexlist=['theta','alpha','beta','gamma','delta']
ind=outstr.find('_')
if ind>-1:
checkstr=outstr[0:ind]
if checkstr in latexlist:
outstr='\\'+outstr
if appenddol:
outstr='$'+outstr+'$'
return outstr
def isfloat(objin):
return isinstance(objin,float)
def SymstrMattoMaxima(matin, symname):
matstr=''
for currow in matin.tolist():
tempstr=str(currow)
rowstr=tempstr.replace("'","")
if matstr:
matstr+=','
matstr+=rowstr
return symname+':matrix('+matstr+')'
def rflat(seq2):
seq = []
for entry in seq2:
if seqin([entry]):
seq.extend([i for i in entry])
else:
seq.append(entry)
return seq
def seqin(sequence):
for i in sequence:
#if ('__contains__' in dir(i) and ## all sequences have '__contains__' in their dir()
# type(i) != str and type(i) != dict and type(i) != symstr): ## parentheses present to aid commenting mid-condition
if type(i)==list or type(i)==tuple:
return True
return False
def flatten(seq):
# Pdb().set_trace()
while seqin(seq):
seq = rflat(seq)
return seq
def find_unique(listin):
temp = [1]*len(listin)
mydict = dict(zip(listin, temp))
return mydict.keys()
def clean_latex(strin):
badlist = ['$','{','}','\\']
strout = copy.copy(strin)
for item in badlist:
strout = strout.replace(item, '')
return strout
def texify_path(pathin):
pathout = pathin.replace('\\','/')
return pathout
def print_list_of_variables(listin, namespace, fmt='%s'):
fmt2 = '%s = ' + fmt
for var in listin:
num = eval(var, namespace)
print(fmt2 % (var, num))
def get_first_key_that_exists(dictin, keylist):
"""Try the keys in keylist in order and return the value for the
first key that exists."""
found_key = 0
for key in keylist:
if dictin.has_key(key):
found_key = 1
return dictin[key]
#we should never reach this point if any key in keylist is found
valid_keys = dictin.keys()
msg = "Did not find a match for any key in keylist: %s. \n Valid keys: %s" % \
(keylist, valid_keys)
assert found_key == 1, msg