+ table.sort(self.sorted, function(a, b) return a.distance < b.distance end)
+
+ for i, a in ipairs(self.sorted) do self.sorted[i] = a.nnm end
+end
+
+function DAG:updateGradOutput(node)
+ local gradInputSucc = node.gradInputSucc
+ if #gradInputSucc == 1 then
+ node.gradOutput = gradInputSucc[1]
+ elseif #gradInputSucc > 1 then
+ if node.gradOutput then
+ node.gradOutput:resize(gradInputSucc[1]):copy(gradInputSucc[1])
+ else
+ node.gradOutput = gradInputSucc[1]:clone()
+ end
+ for k = 2, #gradInputSucc do
+ node.gradOutput:add(gradInputSucc[k])
+ end
+ end
+end
+
+----------------------------------------------------------------------
+
+-- Connect a sequence of modules
+function DAG:connect(...)
+ self.sorted = nil
+ local prev
+ for _, nnm in pairs({...}) do
+ self:createNode(nnm)
+ if prev then
+ table.insert(self.node[nnm].pred, prev)
+ table.insert(self.node[prev].succ, nnm)
+ end
+ prev = nnm
+ end
+end
+
+function DAG:setInput(i)
+ self.sorted = nil
+ self.inputModules = i
+ self:nestedApply(
+ function(nnm)
+ if #self.node[nnm].succ == 0 then
+ error('Input modules must have outgoing edges.')
+ end
+ if #self.node[nnm].pred > 0 then
+ error('Input modules cannog have incoming edges.')
+ end
+ end,
+ self.inputModules
+ )
+end
+
+function DAG:setOutput(o)
+ self.sorted = nil
+ self.outputModules = o
+ self:nestedApply(
+ function(nnm)
+ if #self.node[nnm].pred == 0 then
+ error('Output module must have incoming edges.')
+ end
+ if #self.node[nnm].succ > 0 then
+ error('Output module cannot have outgoing edges.')
+ end
+ end,
+ self.outputModules
+ )