Construct a numpy array with Wilson coefficient values from a
    dictionary of label-value pairs corresponding to the non-redundant
    elements.
496685
def smeft_toarray(wc_name, wc_dict):
    """"""
    shape = smeftutil.C_keys_shape[wc_name]
    C = np.zeros(shape, dtype=complex)
    for k, v in wc_dict.items():
        if k.split('_')[0] != wc_name:
            continue
        indices = k.split('_')[-1]  # e.g. '1213'
        indices = tuple(int(s) - 1 for s in indices)  # e.g. (1, 2, 1, 3)
        C[indices] = v
    C = smeftutil.symmetrize({wc_name: C})[wc_name]
    return C
1188969
def network_from_array(self, array):
        
        if len(array.shape) == 2:
            array = np.array(array, ndmin=3).transpose([1, 2, 0])
        teneto.utils.check_TemporalNetwork_input(array, 'array')
        uvals = np.unique(array)
        if len(uvals) == 2 and 1 in uvals and 0 in uvals:
            i, j, t = np.where(array == 1)
            self.network = pd.DataFrame(data={'i': i, 'j': j, 't': t})
        else:
            i, j, t = np.where(array != 0)
            w = array[array != 0]
            self.network = pd.DataFrame(
                data={'i': i, 'j': j, 't': t, 'weight': w})
        self.N = int(array.shape[0])
        self.T = int(array.shape[-1])
        self._update_network()
1000011
def dict_to_numpy_dict(obj_dict):
    
    return {key: np.asarray(value) if value is not None else None for key, value in obj_dict.items()}
631635
def _to_array(self, itaper, normalization='4pi', csphase=1):
        
        if self.coeffs is None:
            coeffs = _np.copy(self._taper2coeffs(itaper))
        else:
            if itaper > self.nwinrot - 1:
                raise ValueError('itaper must be less than or equal to ' +
                                 'nwinrot - 1. itaper = {:d}, nwinrot = {:d}'
                                 .format(itaper, self.nwinrot))
            coeffs = _shtools.SHVectorToCilm(self.coeffs[:, itaper])

        if normalization == 'schmidt':
            for l in range(self.lwin + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lwin + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
1173447
def gtlike_spectrum_to_dict(spectrum):
    
    parameters = pyLike.ParameterVector()
    spectrum.getParams(parameters)
    d = dict(spectrum_type=spectrum.genericName())
    for p in parameters:

        pname = p.getName()
        pval = p.getTrueValue()
        perr = abs(p.error() * p.getScale()) if p.isFree() else np.nan
        d[pname] = np.array([pval, perr])

        if d['spectrum_type'] == 'FileFunction':
            ff = pyLike.FileFunction_cast(spectrum)
            d['file'] = ff.filename()
    return d
874865
def build_plane_arrays(x, y, qlist):
    
    if type(qlist) is not list:
        return_list = False
        qlist = [qlist]
    else:
        return_list = True
    xv = x[np.where(y==y[0])[0]]
    yv = y[np.where(x==x[0])[0]]
    qlistp = []
    for n in range(len(qlist)):
        qlistp.append(np.zeros((len(yv), len(xv))))
    for j in range(len(qlist)):
        for n in range(len(yv)):
            i = np.where(y==yv[n])[0]
            qlistp[j][n,:] = qlist[j][i]
    if not return_list:
        qlistp = qlistp[0]
    return xv, yv, qlistp
789345
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['label'] = u(array.get('label'))
        data['amount'] = int(array.get('amount'))
        
        instance = LabeledPrice(**data)
        instance._raw = array
        return instance
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)
717785
def from_dict(cls, d):
        
        cohp_dict = {}
        efermi = d["efermi"]
        energies = d["energies"]
        structure = Structure.from_dict(d["structure"])
        if "bonds" in d.keys():
            bonds = {bond: {"length": d["bonds"][bond]["length"],
                            "sites": tuple(PeriodicSite.from_dict(site)
                                           for site in d["bonds"][bond]["sites"])}
                     for bond in d["bonds"]}
        else:
            bonds = None
        for label in d["COHP"]:
            cohp = {Spin(int(spin)): np.array(d["COHP"][label][spin])
                    for spin in d["COHP"][label]}
            try:
                icohp = {Spin(int(spin)): np.array(d["ICOHP"][label][spin])
                         for spin in d["ICOHP"][label]}
            except KeyError:
                icohp = None
            if label == "average":
                avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)
            else:
                cohp_dict[label] = Cohp(efermi, energies, cohp, icohp=icohp)

        if "orb_res_cohp" in d.keys():
            orb_cohp = {}
            for label in d["orb_res_cohp"]:
                orb_cohp[label] = {}
                for orb in d["orb_res_cohp"][label]:
                    cohp = {Spin(int(s)): np.array(
                        d["orb_res_cohp"][label][orb]["COHP"][s],
                        dtype=float)
                        for s in d["orb_res_cohp"][label][orb]["COHP"]}
                    try:
                        icohp = {Spin(int(s)): np.array(
                            d["orb_res_cohp"][label][orb]["ICOHP"][s],
                            dtype=float)
                            for s in d["orb_res_cohp"][label][orb]["ICOHP"]}
                    except KeyError:
                        icohp = None
                    orbitals = [tuple((int(o[0]), Orbital[o[1]])) for o in
                                d["orb_res_cohp"][label][orb]["orbitals"]]
                    orb_cohp[label][orb] = {"COHP": cohp, "ICOHP": icohp,
                                            "orbitals": orbitals}
                # If no total COHPs are present, calculate the total
                # COHPs from the single-orbital populations. Total COHPs
                # may not be present when the cohpgenerator keyword is used
                # in LOBSTER versions 2.2.0 and earlier.
                if label not in d["COHP"] or d["COHP"][label] is None:
                    cohp = {Spin.up: np.sum(np.array(
                        [orb_cohp[label][orb]["COHP"][Spin.up]
                         for orb in orb_cohp[label]]), axis=0)}
                    try:
                        cohp[Spin.down] = np.sum(np.array(
                            [orb_cohp[label][orb]["COHP"][Spin.down]
                             for orb in orb_cohp[label]]), axis=0)
                    except KeyError:
                        pass

                orb_res_icohp = None in [orb_cohp[label][orb]["ICOHP"]
                                         for orb in orb_cohp[label]]
                if (label not in d["ICOHP"] or
                    d["ICOHP"][label] is None) and orb_res_icohp:
                    icohp = {Spin.up: np.sum(np.array(
                        [orb_cohp[label][orb]["ICOHP"][Spin.up]
                         for orb in orb_cohp[label]]), axis=0)}
                    try:
                        icohp[Spin.down] = np.sum(np.array(
                            [orb_cohp[label][orb]["ICOHP"][Spin.down]
                             for orb in orb_cohp[label]]), axis=0)
                    except KeyError:
                        pass
        else:
            orb_cohp = None

        if "average" not in d["COHP"].keys():
            # calculate average
            cohp = np.array([np.array(c)
                             for c in d["COHP"].values()]).mean(axis=0)
            try:
                icohp = np.array([np.array(c)
                                  for c in d["ICOHP"].values()]).mean(axis=0)
            except KeyError:
                icohp = None
            avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)

        return CompleteCohp(structure, avg_cohp, cohp_dict, bonds=bonds,
                            are_coops=d["are_coops"], orb_res_cohp=orb_cohp)
729034
def getSparseTensor(numNonzeros, inputSize, outputSize,
                    onlyPositive=False,
                    fixedRange=1.0/24):
  
  # Initialize weights in the typical fashion.
  w = torch.Tensor(outputSize, inputSize, )

  if onlyPositive:
    w.data.uniform_(0, fixedRange)
  else:
    w.data.uniform_(-fixedRange, fixedRange)

  # Zero out weights for sparse weight matrices
  if numNonzeros < inputSize:
    numZeros = inputSize - numNonzeros

    outputIndices = np.arange(outputSize)
    inputIndices = np.array([np.random.permutation(inputSize)[:numZeros]
                             for _ in outputIndices], dtype=np.long)

    # Create tensor indices for all non-zero weights
    zeroIndices = np.empty((outputSize, numZeros, 2), dtype=np.long)
    zeroIndices[:, :, 0] = outputIndices[:, None]
    zeroIndices[:, :, 1] = inputIndices
    zeroIndices = torch.LongTensor(zeroIndices.reshape(-1, 2))

    zeroWts = (zeroIndices[:, 0], zeroIndices[:, 1])
    w.data[zeroWts] = 0.0

  return w
705231
def arrays_to_mgr(arrays, arr_names, index, columns, dtype=None):
    
    # figure out the index, if necessary
    if index is None:
        index = extract_index(arrays)
    else:
        index = ensure_index(index)

    # don't force copy because getting jammed in an ndarray anyway
    arrays = _homogenize(arrays, index, dtype)

    # from BlockManager perspective
    axes = [ensure_index(columns), index]

    return create_block_manager_from_arrays(arrays, arr_names, axes)
991814
def _to_array(self, itaper, normalization='4pi', csphase=1):
        
        coeffs = _shtools.SHVectorToCilm(self.tapers[:, itaper])

        if normalization == 'schmidt':
            for l in range(self.lwin + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lwin + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
23801
def wrap_in_ndarray(value):
    

    if hasattr(value, "__len__"):
        return np.array(value)
    else:
        return np.array([value])
925196
def index_labels_to_array(labels, dtype=None):
    
    if isinstance(labels, (str, tuple)):
        labels = [labels]

    if not isinstance(labels, (list, np.ndarray)):
        try:
            labels = list(labels)
        except TypeError:  # non-iterable
            labels = [labels]

    labels = asarray_tuplesafe(labels, dtype=dtype)

    return labels
743028
def _to_integral(self, output_array):
        
        if self.dtype == int64_dtype:
            group_labels = output_array
            null_label = self.missing_value
        elif self.dtype == categorical_dtype:
            # Coerce LabelArray into an isomorphic array of ints.  This is
            # necessary because np.where doesn't know about LabelArrays or the
            # void dtype.
            group_labels = output_array.as_int_array()
            null_label = output_array.missing_value_code
        else:
            raise AssertionError(
                "Unexpected Classifier dtype: %s." % self.dtype
            )
        return group_labels, null_label
124766
def from_dict(cls, d):
        
        try:
            # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
            labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
            projections = {}
            structure = None
            if d.get('projections'):
                if isinstance(d["projections"]['1'][0][0], dict):
                    raise ValueError("Old band structure dict format detected!")
                structure = Structure.from_dict(d['structure'])
                projections = {Spin(int(spin)): np.array(v)
                               for spin, v in d["projections"].items()}

            return BandStructureSymmLine(
                d['kpoints'], {Spin(int(k)): d['bands'][k]
                               for k in d['bands']},
                Lattice(d['lattice_rec']['matrix']), d['efermi'],
                labels_dict, structure=structure, projections=projections)
        except:
            warnings.warn("Trying from_dict failed. Now we are trying the old "
                          "format. Please convert your BS dicts to the new "
                          "format. The old format will be retired in pymatgen "
                          "5.0.")
            return BandStructureSymmLine.from_old_dict(d)
9950
def _samples_dicts_to_array(samples_dicts, labels):
    
    itersamples = iter(samples_dicts)

    first_sample = next(itersamples)

    if labels is None:
        labels = list(first_sample)

    num_variables = len(labels)

    def _iter_samples():
        yield np.fromiter((first_sample[v] for v in labels),
                          count=num_variables, dtype=np.int8)

        try:
            for sample in itersamples:
                yield np.fromiter((sample[v] for v in labels),
                                  count=num_variables, dtype=np.int8)
        except KeyError:
            msg = ("Each dict in 'samples' must have the same keys.")
            raise ValueError(msg)

    return np.stack(list(_iter_samples())), labels