makes input for running clearcut on a matrix from a dict2D object
506424
def _matrix_input_from_dict2d(matrix):
    """"""
    #clearcut truncates names to 10 char- need to rename before and
    #reassign after

    #make a dict of env_index:full name
    int_keys = dict([('env_' + str(i), k) for i,k in \
            enumerate(sorted(matrix.keys()))])
    #invert the dict
    int_map = {}
    for i in int_keys:
        int_map[int_keys[i]] = i

    #make a new dict2D object with the integer keys mapped to values instead of
    #the original names
    new_dists = []
    for env1 in matrix:
        for env2 in matrix[env1]:
            new_dists.append((int_map[env1], int_map[env2], matrix[env1][env2]))
    int_map_dists = Dict2D(new_dists)

    #names will be fed into the phylipTable function - it is the int map names
    names = sorted(int_map_dists.keys())
    rows = []
    #populated rows with values based on the order of names
    #the following code will work for a square matrix only
    for index, key1 in enumerate(names):
        row = []
        for key2 in names:
            row.append(str(int_map_dists[key1][key2]))
        rows.append(row)
    input_matrix = phylipMatrix(rows, names)
    #input needs a trailing whitespace or it will fail!
    input_matrix += '\n'

    return input_matrix, int_keys
1287793
def _mat2dict(obj): 
    '''
    
    '''
    import scipy.io as spio
    import numpy as np

    if isinstance(obj, dict):
        out = {}
        for key in obj:
            if isinstance(obj[key], spio.matlab.mio5_params.mat_struct):
                if key in ['conns', 'stims', 'synMechs']:
                    out[key] = [_mat2dict(obj[key])]  # convert to 1-element list
                else:
                    out[key] = _mat2dict(obj[key])
            elif isinstance(obj[key], np.ndarray):
                out[key] = _mat2dict(obj[key])
            else:
                out[key] = obj[key]

    elif isinstance(obj, spio.matlab.mio5_params.mat_struct):
        out = {}
        for key in obj._fieldnames:
            val = obj.__dict__[key]
            if isinstance(val, spio.matlab.mio5_params.mat_struct):
                if key in ['conns', 'stims', 'synMechs']:
                    out[key] = [_mat2dict(val)]  # convert to 1-element list
                else:
                    out[key] = _mat2dict(val)
            elif isinstance(val, np.ndarray):
                out[key] = _mat2dict(val)
            else:
                out[key] = val

    elif isinstance(obj, np.ndarray):
        out = []
        for item in obj:
            if isinstance(item, spio.matlab.mio5_params.mat_struct) or isinstance(item, np.ndarray):
                out.append(_mat2dict(item))
            else:
                out.append(item)

    else:
        out = obj

    return out
916154
def choi(self) -> bk.BKTensor:
        """"""
        # Put superop axes in [ok, ib, ob, ik] and reshape to matrix
        N = self.qubit_nb
        return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2)
477359
def outdict(self, ndigits=3):
        """"""

        output = self.__dict__.copy()
        for item in output:
            output[item] = round(output[item], ndigits)
        return output
1269564
def scrub_dict(d):
    
    if type(d) is dict:
        return dict(
            (k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v)
        )
    elif type(d) is list:
        return [
            scrub_dict(v) for v in d if v and scrub_dict(v)
        ]
    else:
        return d
456184
def outdict(self, ndigits=3):
        """"""

        outdict = {}
        for i in range(EMIR_NBARS):
            ibar = i + 1
            cbar = 'slitlet' + str(ibar).zfill(2)
            outdict[cbar] = {}
            outdict[cbar]['_csu_bar_left'] = \
                round(self._csu_bar_left[i], ndigits)
            outdict[cbar]['_csu_bar_right'] = \
                round(self._csu_bar_right[i], ndigits)
            outdict[cbar]['_csu_bar_slit_center'] = \
                round(self._csu_bar_slit_center[i], ndigits)
            outdict[cbar]['_csu_bar_slit_width'] = \
                round(self._csu_bar_slit_width[i], ndigits)

        return outdict
1228852
def clear_input(self):
        """"""
        for item in listdir(self.input_dir):
            item_path = path.join(self.input_dir, item)
            if path.isfile(item_path):
                remove(item_path)
                logger.debug('Removed input %s.' % item_path)
        return
1278105
def from_dict(cls, d):
        
        makepred, charspan = Pred.surface_or_abstract, Lnk.charspan
        top = d.get('top')
        nodes, edges = [], []
        for nid, node in d.get('nodes', {}).items():
            props = node.get('properties', {})
            if 'type' in node:
                props[CVARSORT] = node['type']
            if not props:
                props = None
            lnk = None
            if 'lnk' in node:
                lnk = charspan(node['lnk']['from'], node['lnk']['to'])
            nodes.append(
                Node(
                    nodeid=nid,
                    pred=makepred(node['label']),
                    sortinfo=props,
                    lnk=lnk,
                    carg=node.get('carg')
                )
            )
            edges.extend(
                (nid, rargname, tgtnid)
                for rargname, tgtnid in node.get('edges', {}).items()
            )
        nodes.sort(key=lambda n: (n.cfrom, -n.cto))
        return cls(top, nodes=nodes, edges=edges)
883959
def make2d(array, cols=None, dtype=None):
    '''
    

    '''
    if not len(array):
        if cols is None or dtype is None:
            raise RuntimeError(
                "cols and dtype must be specified for empty array"
            )
        return _np.empty((0, cols), dtype=dtype)
    return _np.vstack(array)
944432
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['point'] = u(array.get('point'))
        data['x_shift'] = float(array.get('x_shift'))
        data['y_shift'] = float(array.get('y_shift'))
        data['scale'] = float(array.get('scale'))
        data['_raw'] = array
        return MaskPosition(**data)
210279
def conv2d(x_input, w_matrix):
    """"""
    return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
762924
def get_map_matrix(inputfile):
    
    matrix = read_input_file(inputfile)
    output = []
    for row in matrix:
        if row[3]:
            output.append([row[3], row[1], row[2]])
    return output
122453
def purge_dict(idict):
    
    odict = {}
    for key, val in idict.items():
        if is_null(val):
            continue
        odict[key] = val
    return odict
170252
def _prune_3d_body(self, res, transforms):
        
        mask = np.zeros(res.shape)
        mr_dim_idxs = self.mr_dim_ind

        for i, prune_inds in enumerate(self.prune_indices(transforms)):
            rows_pruned = prune_inds[0]
            cols_pruned = prune_inds[1]
            rows_pruned = np.repeat(rows_pruned[:, None], len(cols_pruned), axis=1)
            cols_pruned = np.repeat(cols_pruned[None, :], len(rows_pruned), axis=0)
            slice_mask = np.logical_or(rows_pruned, cols_pruned)

            # In case of MRs we need to "inflate" mask
            if mr_dim_idxs == (1, 2):
                slice_mask = slice_mask[:, np.newaxis, :, np.newaxis]
            elif mr_dim_idxs == (0, 1):
                slice_mask = slice_mask[np.newaxis, :, np.newaxis, :]
            elif mr_dim_idxs == (0, 2):
                slice_mask = slice_mask[np.newaxis, :, :, np.newaxis]
            elif mr_dim_idxs == 1 and self.ndim == 3:
                slice_mask = slice_mask[:, np.newaxis, :]
            elif mr_dim_idxs == 2 and self.ndim == 3:
                slice_mask = slice_mask[:, :, np.newaxis]

            mask[i] = slice_mask

        res = np.ma.masked_array(res, mask=mask)
        return res
1115010
def deep_copy(numpy_dict):
  
  out = {}
  for key in numpy_dict:
    out[key] = numpy_dict[key].copy()
  return out
919107
def clean_dict_keys(d):
    
    new_d = {}
    for (k, v) in d.iteritems():
        new_d[str(k)] = v
    return new_d
600320
def _preprocess_input(self):
    """"""
    # Compute the sets of MTF dimensions used in operations/tensors.

    # a {string: frozenset(string)}, mapping operation name to MTF dimension
    # names.
    self._operation_name_to_mtf_dimension_set = {}
    # a {string: frozenset(string)}, mapping tensor name to MTF dimension names.
    self._tensor_name_to_mtf_dimension_set = {}

    for operation_name in self._graph.get_all_operation_names():
      self._operation_name_to_mtf_dimension_set[operation_name] = frozenset(
          set(self._graph.get_operation_mtf_dimension_names(
              operation_name)).intersection(
                  self._layout_validator.splittable_mtf_dimension_names))
    for tensor_name in self._graph.get_all_tensor_names():
      self._tensor_name_to_mtf_dimension_set[tensor_name] = frozenset(
          set(self._graph.get_tensor_mtf_dimension_names(tensor_name))
          .intersection(self._layout_validator.splittable_mtf_dimension_names))

    self._operation_mtf_dimension_sets = set(
        self._operation_name_to_mtf_dimension_set.values())
    self._mtf_dimension_sets = self._operation_mtf_dimension_sets | set(
        self._tensor_name_to_mtf_dimension_set.values())

    # Compute possible assignments for each set of MTF dimensions.
    self._assignments = {}  # indexed by MTF dimension set
    for mtf_dimension_set in self._mtf_dimension_sets:
      self._assignments[mtf_dimension_set] = _generate_assignments(
          mtf_dimension_set, self._layout_validator.mesh_dimension_name_to_size)