-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdotio.py
executable file
·222 lines (181 loc) · 7.74 KB
/
dotio.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
#-------------------------------------------------------------------------------------
# Copyright 2014 Michael Peeri
#
# This file is part of hmmdsl.
# hmmdsl is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# hmmdsl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with hmmdsl. If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------------
from math import exp, sqrt
import re
import hmmdsl_py
import pickle
def WriteGraphToDOT( graph, filename ):
f = open( filename, 'w')
f.write('digraph hmm {\n')
f.write('//plot using: dot -Tpng {0} >{0}.png\n'.format( filename ) )
f.write('\trankdir=LR;\n')
for s in graph.keys():
targets = graph[s]
p = 1. / len(targets)
for t in targets:
f.write( '\tS{0} -> S{1} [penwidth={2}, label=\"{3:1.3f}\"];\n'.format( s, t, p*10.0, p ) );
f.write('}')
def AddAlphabet(model, alphabet):
for symbol in alphabet:
model.AddAlphabetSymbol( symbol )
class StorableModel:
def __init__(self, model):
self.symbols = []
for c in range(model.num_symbols()):
self.symbols.append( model.get_symbol(c) )
self.states = []
for s in range(model.num_states()):
self.states.append( model.GetStateName(s) )
# Initialize 'a'
self.a = []
for k in range(model.num_states()):
row = []
for l in range(model.num_states()):
row.append( model.a(k, l) )
self.a.append(row)
# Initialize 'e'
self.e = []
for k in range(model.num_states()):
row = []
for s in range(model.num_symbols()):
row.append( model.e(k, model.get_symbol(s) ) )
self.e.append(row)
if isinstance(model, hmmdsl_py.Model):
# Initialize 'eta'
self.eta = []
for k in range(model.num_states()):
self.eta.append( model.GetEta(k) )
# Initialize 'mu'
self.mu = []
for k in range(model.num_states()):
self.mu.append( model.GetMu(k) )
self.model_type = type(model)
# Return an equivalent model to the pickled one
def convert(self):
try:
model_type = self.model_type
except AttributeError as err:
self.model_type = hmmdsl_py.Model
if self.model_type == hmmdsl_py.Model:
model = hmmdsl_py.Model()
else:
model = hmmdsl_py.HMMModel()
AddAlphabet( model, self.symbols );
for s in range( 2, len(self.states ) ):
model.AddState( s, self.states[s] )
for k in range(len(self.states)):
#if( k == model.GetTerminalState() ): continue
for l in range(len(self.states)):
#if( l == model.GetInitialState() ): continue
model.SetTransitionLogspace(k, l, self.a[k][l] )
if isinstance(model, hmmdsl_py.Model):
model.SetEta( k, self.eta[k] )
model.SetMu( k, self.mu[k] )
for k in range(len(self.states)):
if( model.is_silent(k) ): continue
for s in range(len(self.symbols)):
model.SetEmissionProbabilityLogspace( k, self.symbols[s], self.e[k][s] )
return model
def store(model, path):
with open(path, "wb") as f:
pickle.dump( StorableModel(model), f, -1 )
def load(path):
with open(path, "rb") as f:
sm = pickle.load( f )
return sm.convert()
def GetStateLabel( model, state ):
label = '<<table border="0" cellborder="0" cellpadding="0" cellspacing="0">'
if isinstance(model, hmmdsl_py.Model):
mu = model.GetMu(state)
eta = model.GetEta(state)
mean = mu/eta
variance = mu/(eta**2)
stddev = sqrt(variance)
label += '<tr><td colspan="2">τ={:.3g}±{:.2g}</td></tr>'.format(mean, 2*stddev)
label += '<tr><td colspan="2">μ={:.3g}</td></tr>'.format(mu)
label += '<tr><td colspan="2">η={:.3g}</td></tr>'.format(eta)
entropy = model.emissions_entropy(state)
for c in range(model.num_symbols()):
symbol = model.get_symbol(c);
e = exp(model.e( state, symbol ))
if( e >= 0.01 ):
label += '<tr><td width="{:.3g}" height="5" fixedsize="true" bgcolor="black" align="left"></td><td width="20" height="10">{}</td></tr>'.format( e*80, symbol )
label += '<tr><td colspan="2">H(e)={:.2g}b</td></tr>'.format(entropy)
label += '</table>>'
return label
def WriteDOT( model, filename ):
f = open( filename, 'w')
f.write('//plot using: dot -Tpng {0} >{0}.png\n'.format( filename ) )
f.write('digraph hmm {\n')
f.write('\trankdir=LR;\n')
# Write the state definitions
# Note: The initial state is included in these states
for s in range(model.num_states()):
if( not model.is_silent(s) ):
f.write( '\tS{0} [shape=Mrecord label={1}];\n'.format( s, GetStateLabel( model, s) ) );
else:
f.write( '\tS{0} [shape=Mrecord label={1}];\n'.format( s, s) ); # Don't write emission probs for silent states
# Write the transitions
for s in range(model.num_states()):
for t in range(model.num_states()):
p = exp(model.a(s, t));
if( p >= 5.e-3 ): # Only include transitions with probability >= 0.005 (this should exclude pseudocounts)
f.write( '\tS{0} -> S{1} [penwidth={2}, label=\"{3:1.3f}\"];\n'.format( s, t, p*10.0, p ) );
f.write('}')
def WriteHaskellTextFormat( model, sequence, filename ):
def write_matrix(io, func, range1, range2 ):
for x in range1:
io.write( " ".join( map( str, [ func(x,y) for y in range2 ] ) ) )
io.write("\n")
with open( filename, 'w') as f:
alphabet = model.GetAlphabet()
f.write("[alphabet]\n")
f.write(alphabet)
f.write("\n")
f.write("[sequence]\n")
f.write(sequence)
f.write("\n")
N = model.num_states()
f.write("[a:{0} {1}]\n".format( N, N ))
write_matrix( f, lambda x, y: model.a(x,y), range(0,N), range(0,N) )
f.write("[e:{0} {1}]\n".format( N, len(alphabet)))
write_matrix( f, lambda x, y: model.e(x,alphabet[y]), range(0,N), range(0,len(alphabet)) )
f.write("[d:{0} {1}]\n".format( N, 2 ) )
d1 = map( lambda x: model.GetMu(x), range(0,N) )
d2 = map( lambda x: model.GetEta(x), range(0,N) )
d = tuple(zip(d1,d2))
write_matrix( f, lambda x, y: d[x][y], range(0,N), range(0,2) )
_hs_text_heading = re.compile("[[](\w+)[:](\d+) (\d+)[]]")
def ReadHaskellTextFormat( filename ):
out = {}
with open( filename, 'r') as f:
while( f.readable() ):
heading_text = f.readline()
m = _hs_text_heading.match(heading_text)
if( m == None ): break
identifier = m.groups()[0]
rows = int(m.groups()[1])
cols = int(m.groups()[2])
mat = []
for i in range(rows):
values_text = f.readline()
values = list(map(float, values_text.split(" ")))
assert(len(values)==cols)
mat.append(values)
out[identifier] = mat
return out