-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkwopt.py
94 lines (83 loc) · 2.47 KB
/
kwopt.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
import scipy.optimize
from scipy.special import logit, expit
import numpy as np
class logbarrier:
@classmethod
def mangle(cls, x):
return np.log(x)
@classmethod
def unmangle(cls, X):
return np.exp(X)
class logitbarrier:
@classmethod
def mangle(cls, x):
return logit(x)
@classmethod
def unmangle(cls, X):
return expit(X)
class fixed: pass
def mangle(spec, xs):
Xs = []
for key, x in xs.items():
if fixed in spec[key]:
continue
for mangler in spec[key]:
if hasattr(mangler, 'mangle'):
x = mangler.mangle(x)
Xs.append(x)
return Xs
def unmangle(spec, Xs):
xs = {}
Xs = list(np.atleast_1d(Xs))
for name, s in spec.items():
if fixed in s:
xs[name] = s[0]
continue
x = Xs.pop(0)
for mangler in s:
if hasattr(mangler, 'unmangle'):
x = mangler.unmangle(x)
xs[name] = x
return xs
def minimizer(f, opt_f=scipy.optimize.minimize, *oargs, **okwargs):
def minimize(**spec):
#keys, spec = ikwargs.keys(), ikwargs.values()
#spec = [spec if isinstance(spec, tuple) else (spec,)]
for k, s in spec.items():
if not isinstance(s, tuple):
spec[k] = (s,)
"""
def mangle(xs):
Xs = []
for key, x in xs.items():
if fixed in spec[key]:
continue
for mangler in spec[key]:
if hasattr(mangler, 'mangle'):
x = mangler.mangle(x)
Xs.append(x)
return Xs
def unmangle(Xs):
xs = {}
Xs = list(np.atleast_1d(Xs))
for name, s in spec.items():
if fixed in s:
xs[name] = s[0]
continue
x = Xs.pop(0)
for mangler in s:
if hasattr(mangler, 'unmangle'):
x = mangler.unmangle(x)
xs[name] = x
return xs
"""
def wrapper(x):
k = unmangle(spec, x)
return f(**k)
initial = {k: v[0] for k, v in spec.items()}
result = opt_f(wrapper, mangle(spec, initial), *oargs, **okwargs)
result.kwargs = unmangle(spec, result.x)
return result
minimize.mangle = mangle
minimize.unmangle = unmangle
return minimize