+ assert(nl < #self.modules, 'Cycle detected in the graph.')
+ nl = nl + 1
+ until nc == 0
+
+ for _, nnm in pairs(self.modules) do
+ assert(distance[nnm], 'Some modules are not connected to inputs')
+ end
+
+ self.sorted = {}
+ for m, d in pairs(distance) do
+ table.insert(self.sorted, { distance = d, nnm = m })
+ end
+
+ 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
+
+-- This accumulates x in a, where they are both nested tables of
+-- tensors with same structures / keys. If first is true, set a = x
+-- (in which case a can be nil) otherwise a = a + x. The behavior is
+-- undefined if a and x do not have the exact same structure.
+function DAG:nestedAccTensor(a, x, first)
+ if torch.type(x) == 'table' then
+ local b = {}
+ for i in pairs(x) do
+ b[i] = self:nestedAccTensor(a[i], x[i], first)
+ end
+ a = b