forked from jfsantos/seq2seq
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.lua
More file actions
72 lines (65 loc) · 1.99 KB
/
utils.lua
File metadata and controls
72 lines (65 loc) · 1.99 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
require 'nngraph';
function WagnerFischer(a,b)
assert(a:nDimension() == 1, 'a must be a 1D tensor')
assert(b:nDimension() == 1, 'b must be a 1D tensor')
m = a:size(1)+1
n = b:size(1)+1
d = torch.Tensor(m,n)
for i = 1, m do
d[{i,1}] = i-1
end
for j = 1, n do
d[{1,j}] = j-1
end
for j = 1, n-1 do
for i = 1, m-1 do
if a[i] == b[j] then
d[{i+1,j+1}] = d[{i,j}]
else
d[{i+1,j+1}] = math.min(d[{i,j+1}]+1,
d[{i+1,j}]+1,
d[{i,j}]+1)
end
end
end
return d[{m,n}]
end
function customToDot(graph, title, failedNode)
local str = graph:todot(title)
if not failedNode then
return str
end
local failedNodeId = nil
for i, node in ipairs(graph.nodes) do
if node.data == failedNode.data then
failedNodeId = node.id
break
end
end
if failedNodeId ~= nil then
-- The closing '}' is removed.
-- And red fillcolor is specified for the failedNode.
str = string.gsub(str, '}%s*$', '')
str = str .. string.format('n%s[style=filled, fillcolor=red];\n}',
failedNodeId)
end
return str
end
function saveSvg(svgPathPrefix, dotStr)
io.stderr:write(string.format("saving %s.svg\n", svgPathPrefix))
local dotPath = svgPathPrefix .. '.dot'
local dotFile = io.open(dotPath, 'w')
dotFile:write(dotStr)
dotFile:close()
local svgPath = svgPathPrefix .. '.svg'
local cmd = string.format('dot -Tsvg -o %s %s', svgPath, dotPath)
os.execute(cmd)
end
function outputGraphViz(gmodule, focusNode)
local focusNode = focusNode or gmodule.outnode
local nInputs = gmodule.nInputs or #gmodule.innode.children
local svgPathPrefix = gmodule.name or string.format(
'nngraph_%sin_%sout', nInputs, #gmodule.outnode.children)
local dotStr = customToDot(gmodule.fg, svgPathPrefix, focusNode)
saveSvg(svgPathPrefix, dotStr)
end