a method for reconstructing a dictionary from the values along dot paths
188677
def reconstruct_dict(dot_paths, values):
    
    '''  '''
    
    output_dict = {}
    
    for i in range(len(dot_paths)):
        if i + 1 <= len(values):
            path_segments = segment_path(dot_paths[i])
            current_nest = output_dict
            for j in range(len(path_segments)):
                key_name = path_segments[j]
                try:
                    key_name = int(key_name)
                except:
                    pass
                if j + 1 == len(path_segments):
                    if isinstance(key_name, int):
                        current_nest.append(values[i])
                    else:
                        current_nest[key_name] = values[i]
                else:
                    next_key = path_segments[j+1]
                    try:
                        next_key = int(next_key)
                    except:
                        pass
                    if isinstance(next_key, int):
                        if not key_name in current_nest.keys():
                            current_nest[key_name] = []
                        current_nest = current_nest[key_name]
                    else:
                        if isinstance(key_name, int):
                            current_nest.append({})
                            current_nest = current_nest[len(current_nest) - 1]
                        else:
                            if not key_name in current_nest.keys():
                                current_nest[key_name] = {}
                            current_nest = current_nest[key_name]
    
    return output_dict
719226
def map_values(f, D):
    ''''''
    return { key:f(val) for key,val in D.iteritems() }
653610
function reconstructRoute(parents, points, tailPoint, from, to, grid, opt) {

        var route = [];

        var prevDiff = normalizePoint(to.difference(tailPoint));

        // tailPoint is assumed to be aligned already
        var currentKey = getKey(tailPoint);
        var parent = parents[currentKey];

        var point;
        while (parent) {

            // point is assumed to be aligned already
            point = points[currentKey];

            var diff = normalizePoint(point.difference(parent));
            if (!diff.equals(prevDiff)) {
                route.unshift(point);
                prevDiff = diff;
            }

            // parent is assumed to be aligned already
            currentKey = getKey(parent);
            parent = parents[currentKey];
        }

        // leadPoint is assumed to be aligned already
        var leadPoint = points[currentKey];

        var fromDiff = normalizePoint(leadPoint.difference(from));
        if (!fromDiff.equals(prevDiff)) {
            route.unshift(leadPoint);
        }

        return route;
    }
1233903
def _single_tree_paths(self, tree):
    """"""
    skel = tree.consolidate()

    tree = defaultdict(list)

    for edge in skel.edges:
      svert = edge[0]
      evert = edge[1]
      tree[svert].append(evert)
      tree[evert].append(svert)

    def dfs(path, visited):
      paths = []
      stack = [ (path, visited) ]
      
      while stack:
        path, visited = stack.pop(0)

        vertex = path[-1]
        children = tree[vertex]
        
        visited[vertex] = True

        children = [ child for child in children if not visited[child] ]

        if len(children) == 0:
          paths.append(path)

        for child in children:
          stack.append( 
            (path + [child], copy.deepcopy(visited))
          )

      return paths
      
    root = skel.edges[0,0]
    paths = dfs([root], defaultdict(bool))

    root = np.argmax([ len(_) for _ in paths ])
    root = paths[root][-1]
  
    paths = dfs([ root ], defaultdict(bool))
    
    return [ np.flip(skel.vertices[path], axis=0) for path in paths ]
1211159
def graph_from_dot_file(path):
    
    
    fd = file(path, 'rb')
    data = fd.read()
    fd.close()
    
    return graph_from_dot_data(data)
87082
def dict_strip(d):
    
    _d = deepcopy(d)
    for k, v in iteritems(d):
        if isinstance(v, str):
            _d[k] = v.strip()
        elif isinstance(v, dict):
            _d[k] = dict_strip(v)

    return _d
388428
def from_dict(cls, d):
        
        s = Structure.from_dict(d['structure'])
        return cls(s, d['graphs'])
1329667
def clean_dict(d, test=lambda v: v):
    
    return {k: v for k, v in d.items() if test(v)}
249075
def _dict_value_to_pairs(d):
    
    d = d[tz.first(d)]

    for k, v in d.items():
        yield {k: v}
657036
def gather_indices_2d(x, block_shape, block_stride):
  """"""
  # making an identity matrix kernel
  kernel = tf.eye(block_shape[0] * block_shape[1])
  kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1])
  # making indices [1, h, w, 1] to appy convs
  x_shape = common_layers.shape_list(x)
  indices = tf.range(x_shape[2] * x_shape[3])
  indices = tf.reshape(indices, [1, x_shape[2], x_shape[3], 1])
  indices = tf.nn.conv2d(
      tf.cast(indices, tf.float32),
      kernel,
      strides=[1, block_stride[0], block_stride[1], 1],
      padding="VALID")
  # making indices [num_blocks, dim] to gather
  dims = common_layers.shape_list(indices)[:3]
  if all([isinstance(dim, int) for dim in dims]):
    num_blocks = functools.reduce(operator.mul, dims, 1)
  else:
    num_blocks = tf.reduce_prod(dims)
  indices = tf.reshape(indices, [num_blocks, -1])
  return tf.cast(indices, tf.int32)
118107
def _key_dot_replace(self, rdict):
        """"""
        temp_dict = {}
        for key, value in iteritems(rdict):
            if isinstance(value, dict):
                value = self._key_dot_replace(value)
            temp_dict[key.replace('.', '_')] = value
        return temp_dict
477359
def outdict(self, ndigits=3):
        """"""

        output = self.__dict__.copy()
        for item in output:
            output[item] = round(output[item], ndigits)
        return output
739306
def sample_from_prior(self):
        

        # simple_path_dict caches the results of the graph traversal that finds
        # simple paths between pairs of nodes, so that it doesn't have to be
        # executed for every sampled transition matrix.

        node_pairs = list(permutations(self.nodes(), 2))
        simple_path_dict = {
            node_pair: [
                list(pairwise(path))
                for path in nx.all_simple_paths(self, *node_pair)
            ]
            for node_pair in node_pairs
        }

        self.transition_matrix_collection = []

        elements = self.get_latent_state_components()

        for i in range(self.res):
            A = pd.DataFrame(
                np.identity(2 * len(self)), index=elements, columns=elements
            )

            for node in self.nodes:
                A[f"∂({node})/∂t"][node] = self.Δt

            for node_pair in node_pairs:
                A[f"∂({node_pair[0]})/∂t"][node_pair[1]] = sum(
                    np.prod(
                        [
                            self.edges[edge[0], edge[1]]["βs"][i]
                            for edge in simple_path_edge_list
                        ]
                    )
                    * self.Δt
                    for simple_path_edge_list in simple_path_dict[node_pair]
                )
            self.transition_matrix_collection.append(A)
168903
def _identify_dict(core):
    """"""
    if not core:
        return {}, 1, (), int

    core = core.copy()
    key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0]
    shape = numpy.array(core[key]).shape
    dtype = numpy.array(core[key]).dtype
    dim = len(key)
    return core, dim, shape, dtype
68052
def toSparse(self):
        """"""
        if self.isTransposed:
            values = np.ravel(self.toArray(), order='F')
        else:
            values = self.values
        indices = np.nonzero(values)[0]
        colCounts = np.bincount(indices // self.numRows)
        colPtrs = np.cumsum(np.hstack(
            (0, colCounts, np.zeros(self.numCols - colCounts.size))))
        values = values[indices]
        rowIndices = indices % self.numRows

        return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values)
189750
def dot(v1, v2):
    '''
    '''
    x1, y1, z1 = v1
    x2, y2, z2 = v2
    return x1 * x2 + y1 * y2 + z1 * z2
989368
def from_dict(dct):
    
    def inner(d):
        results = []
        for name, v in d.items():
            if isinstance(v, dict):
                results.append(Section(name=name, children=from_dict(v)))
            elif isinstance(v, list):
                if not any(isinstance(i, dict) for i in v):
                    results.append(Directive(name=name, attrs=v))
                else:
                    for i in v:
                        if isinstance(i, dict):
                            results.append(Section(name=name, children=from_dict(i)))
                        elif isinstance(i, list):
                            results.append(Directive(name=name, attrs=i))
                        else:
                            results.append(Directive(name=name, attrs=[i]))
            else:
                results.append(Directive(name, attrs=[v]))
        return results
    return Root(children=inner(dct))