Converts a basis set to Molpro format
163243
def write_molpro(basis):
    '''
    '''

    # Uncontract all, and make as generally-contracted as possible
    basis = manip.uncontract_spdf(basis, 0, True)
    basis = manip.make_general(basis, False)
    basis = sort.sort_basis(basis, True)

    s = ''

    # Elements for which we have electron basis
    electron_elements = [k for k, v in basis['elements'].items() if 'electron_shells' in v]

    # Elements for which we have ECP
    ecp_elements = [k for k, v in basis['elements'].items() if 'ecp_potentials' in v]

    if len(electron_elements) > 0:
        # basis set starts with a string
        s += 'basis={\n'

        # Electron Basis
        for z in electron_elements:
            data = basis['elements'][z]
            sym = lut.element_sym_from_Z(z).upper()
            s += '!\n'
            s += '! {:20} {}\n'.format(lut.element_name_from_Z(z), misc.contraction_string(data))

            for shell in data['electron_shells']:
                exponents = shell['exponents']
                coefficients = shell['coefficients']

                am = shell['angular_momentum']
                amchar = lut.amint_to_char(am).lower()
                s += '{}, {} , {}\n'.format(amchar, sym, ', '.join(exponents))
                for c in coefficients:
                    first, last = find_range(c)
                    s += 'c, {}.{}, {}\n'.format(first + 1, last + 1, ', '.join(c[first:last + 1]))
        s += '}\n'

    # Write out ECP
    if len(ecp_elements) > 0:
        s += '\n\n! Effective core Potentials\n'

        for z in ecp_elements:
            data = basis['elements'][z]
            sym = lut.element_sym_from_Z(z).lower()
            max_ecp_am = max([x['angular_momentum'][0] for x in data['ecp_potentials']])

            # Sort lowest->highest, then put the highest at the beginning
            ecp_list = sorted(data['ecp_potentials'], key=lambda x: x['angular_momentum'])
            ecp_list.insert(0, ecp_list.pop())

            s += 'ECP, {}, {}, {} ;\n'.format(sym, data['ecp_electrons'], max_ecp_am)

            for pot in ecp_list:
                rexponents = pot['r_exponents']
                gexponents = pot['gaussian_exponents']
                coefficients = pot['coefficients']

                am = pot['angular_momentum']
                amchar = lut.amint_to_char(am).lower()
                s += '{};'.format(len(rexponents))

                if am[0] == max_ecp_am:
                    s += ' !  ul potential\n'
                else:
                    s += ' !  {}-ul potential\n'.format(amchar)

                for p in range(len(rexponents)):
                    s += '{},{},{};\n'.format(rexponents[p], gexponents[p], coefficients[0][p])
    return s
1068281
def as_dict(self):
        
        structure = self.final_structure
        d = {"has_gaussian_completed": self.properly_terminated,
             "nsites": len(structure)}
        comp = structure.composition
        d["unit_cell_formula"] = comp.as_dict()
        d["reduced_cell_formula"] = Composition(comp.reduced_formula).as_dict()
        d["pretty_formula"] = comp.reduced_formula
        d["is_pcm"] = self.is_pcm
        d["errors"] = self.errors
        d["Mulliken_charges"] = self.Mulliken_charges

        unique_symbols = sorted(list(d["unit_cell_formula"].keys()))
        d["elements"] = unique_symbols
        d["nelements"] = len(unique_symbols)
        d["charge"] = self.charge
        d["spin_multiplicity"] = self.spin_multiplicity

        vin = {"route": self.route_parameters, "functional": self.functional,
               "basis_set": self.basis_set,
               "nbasisfunctions": self.num_basis_func,
               "pcm_parameters": self.pcm}

        d["input"] = vin

        nsites = len(self.final_structure)

        vout = {
            "energies": self.energies,
            "final_energy": self.final_energy,
            "final_energy_per_atom": self.final_energy / nsites,
            "molecule": structure.as_dict(),
            "stationary_type": self.stationary_type,
            "corrections": self.corrections
        }

        d['output'] = vout
        d["@module"] = self.__class__.__module__
        d["@class"] = self.__class__.__name__

        return d
522550
def kron_bases(*bases: Dict[str, np.ndarray],
               repeat: int = 1) -> Dict[str, np.ndarray]:
    """"""
    product_basis = {'': 1}
    for basis in bases * repeat:
        product_basis = {
            name1 + name2: np.kron(matrix1, matrix2)
            for name1, matrix1 in product_basis.items()
            for name2, matrix2 in basis.items()
        }
    return product_basis
1056713
def _convert_eq(self, eq):
        
        rename = dict(enumerate(self.index))
        eq['eq_sets'] = {rename[k]: {rename[x] for x in v}
                         for k, v in eq['eq_sets'].items()}
        eq['sym_ops'] = {rename[k]: {rename[x]: v[x] for x in v}
                         for k, v in eq['sym_ops'].items()}
        try:
            sym_mol = self.from_pymatgen_molecule(eq['sym_mol'])
            sym_mol.index = self.index
            eq['sym_mol'] = sym_mol._to_numeric()
        except KeyError:
            pass
929538
def _get_atomsection(mol2_lst):
        """"""
        started = False
        for idx, s in enumerate(mol2_lst):
            if s.startswith('@<TRIPOS>ATOM'):
                first_idx = idx + 1
                started = True
            elif started and s.startswith('@<TRIPOS>'):
                last_idx_plus1 = idx
                break
        return mol2_lst[first_idx:last_idx_plus1]
1003465
def infos_on_basis_set(self):
        
        o = []
        o.append("=========================================")
        o.append("Reading basis set:")
        o.append("")
        o.append(" Basis set for {} atom ".format(str(self.filename)))
        o.append(" Maximum angular momentum = {}".format(self.data['lmax']))
        o.append(" Number of atomics orbitals = {}".format(self.data['n_nlo']))
        o.append(" Number of nlm orbitals = {}".format(self.data['n_nlmo']))
        o.append("=========================================")

        return str(0)
1374150
def get_zmatrix(self):
        
        output = []
        outputvar = []
        for i, site in enumerate(self._mol):
            if i == 0:
                output.append("{}".format(site.specie))
            elif i == 1:
                nn = self._find_nn_pos_before_site(i)
                bondlength = self._mol.get_distance(i, nn[0])
                output.append("{} {} B{}".format(self._mol[i].specie,
                                                 nn[0] + 1, i))
                outputvar.append("B{}={:.6f}".format(i, bondlength))
            elif i == 2:
                nn = self._find_nn_pos_before_site(i)
                bondlength = self._mol.get_distance(i, nn[0])
                angle = self._mol.get_angle(i, nn[0], nn[1])
                output.append("{} {} B{} {} A{}".format(self._mol[i].specie,
                                                        nn[0] + 1, i,
                                                        nn[1] + 1, i))
                outputvar.append("B{}={:.6f}".format(i, bondlength))
                outputvar.append("A{}={:.6f}".format(i, angle))
            else:
                nn = self._find_nn_pos_before_site(i)
                bondlength = self._mol.get_distance(i, nn[0])
                angle = self._mol.get_angle(i, nn[0], nn[1])
                dih = self._mol.get_dihedral(i, nn[0], nn[1], nn[2])
                output.append("{} {} B{} {} A{} {} D{}"
                              .format(self._mol[i].specie, nn[0] + 1, i,
                                      nn[1] + 1, i, nn[2] + 1, i))
                outputvar.append("B{}={:.6f}".format(i, bondlength))
                outputvar.append("A{}={:.6f}".format(i, angle))
                outputvar.append("D{}={:.6f}".format(i, dih))
        return "\n".join(output) + "\n\n" + "\n".join(outputvar)
819910
def from_dict(cls, d):
        
        m = Molecule.from_dict(d['molecule'])
        return cls(m, d['graphs'])
1301571
def calcuate_bboxes(im_shape, patch_size):
    """"""
    h, w = im_shape
    ph, pw = patch_size

    steps_h = chain(range(0, h - ph, ph), [h - ph])
    steps_w = chain(range(0, w - pw, pw), [w - pw])

    return product(steps_h, steps_w)
1100766
def formula(mol):
    
    mol.require("Valence")
    mol.require("Topology")
    total_cntr = Counter()
    for m in sorted(mols_iter(mol), key=len, reverse=True):
        cntr = Counter()
        for i in m:
            cntr += mol.atom(i).composition()
        text = []
        Cs = cntr.pop("C", 0)
        if Cs:
            text.append("C")
            if Cs > 1:
                text.append(str(Cs))
        Hs = cntr.pop("H", 0)
        if Hs:
            text.append("H")
            if Hs > 1:
                text.append(str(Hs))
        heteros = sorted(cntr.items(), key=lambda x: atom_number(x[0]))
        for k, v in heteros:
            text.append(k)
            if v > 1:
                text.append(str(v))
        total_cntr["".join(text)] += 1
    total = sorted(total_cntr.items(), key=lambda x: len(x[0]), reverse=True)
    total_text = []
    for k, v in total:
        if v > 1:
            total_text.append(str(v) + k)
        else:
            total_text.append(k)
    return ".".join(total_text)
719343
def basis_state(i, n):
    """"""
    v = sympy.zeros(n, 1)
    v[i] = 1
    return v
1175133
def from_rdkit_molecule(data):
    
    m = MoleculeContainer()
    atoms, mapping = [], []
    for a in data.GetAtoms():
        atom = {'element': a.GetSymbol(), 'charge': a.GetFormalCharge()}
        atoms.append(atom)
        mapping.append(a.GetAtomMapNum())

        isotope = a.GetIsotope()
        if isotope:
            atom['isotope'] = isotope
        radical = a.GetNumRadicalElectrons()
        if radical:
            atom['multiplicity'] = radical + 1

    conformers = data.GetConformers()
    if conformers:
        for atom, (x, y, z) in zip(atoms, conformers[0].GetPositions()):
            atom['x'] = x
            atom['y'] = y
            atom['z'] = z

    for atom, mapping in zip(atoms, mapping):
        a = m.add_atom(atom)
        if mapping:
            m.atom(a)._parsed_mapping = mapping

    for bond in data.GetBonds():
        m.add_bond(bond.GetBeginAtomIdx() + 1, bond.GetEndAtomIdx() + 1, _rdkit_bond_map[bond.GetBondType()])

    return m
1133360
def basis(self):
        
        precision_adj = self.dt / 100
        return np.arange(self.start, self.stop - precision_adj, self.dt)
1014186
def to_rdkit_molecule(data):
    
    mol = RWMol()
    conf = Conformer()
    mapping = {}
    is_3d = False
    for n, a in data.atoms():
        ra = Atom(a.number)
        ra.SetAtomMapNum(n)
        if a.charge:
            ra.SetFormalCharge(a.charge)
        if a.isotope != a.common_isotope:
            ra.SetIsotope(a.isotope)
        if a.radical:
            ra.SetNumRadicalElectrons(a.radical)
        mapping[n] = m = mol.AddAtom(ra)
        conf.SetAtomPosition(m, (a.x, a.y, a.z))
        if a.z:
            is_3d = True
    if not is_3d:
        conf.Set3D(False)

    for n, m, b in data.bonds():
        mol.AddBond(mapping[n], mapping[m], _bond_map[b.order])

    mol.AddConformer(conf)
    SanitizeMol(mol)
    return mol
1328630
def _assemble_conversion(self, stmt):
        """"""
        pybel_lists = ([], [])
        for pybel_list, agent_list in \
                            zip(pybel_lists, (stmt.obj_from, stmt.obj_to)):
            for agent in agent_list:
                node = _get_agent_grounding(agent)
                # TODO check for missing grounding?
                pybel_list.append(node)

        rxn_node_data = reaction(
            reactants=pybel_lists[0],
            products=pybel_lists[1],
        )
        obj_node = self.model.add_node_from_data(rxn_node_data)
        obj_edge = None  # TODO: Any edge information possible here?
        # Add node for controller, if there is one
        if stmt.subj is not None:
            subj_attr, subj_edge = _get_agent_node(stmt.subj)
            subj_node = self.model.add_node_from_data(subj_attr)
            edge_data_list = _combine_edge_data(pc.DIRECTLY_INCREASES,
                                           subj_edge, obj_edge, stmt.evidence)
            for edge_data in edge_data_list:
                self.model.add_edge(subj_node, obj_node, **edge_data)
1372706
private List<List<Integer>> calcOrbits() {
		int n = subunits.getSubunitCount();
		int fold = rotationGroup.getRotation(0).getFold();

		List<List<Integer>> orbits = new ArrayList<List<Integer>>();
		boolean[] used = new boolean[n];
		Arrays.fill(used, false);

		for (int i = 0; i < n; i++) {
			if (! used[i]) {
				// determine the equivalent subunits
				List<Integer> orbit = new ArrayList<Integer>(fold);
				for (int j = 0; j < fold; j++) {
					List<Integer> permutation = rotationGroup.getRotation(j).getPermutation();
					orbit.add(permutation.get(i));
					used[permutation.get(i)] = true;
				}
				orbits.add(deconvolute(orbit));
			}
		}
		return orbits;
	}
644270
def msh_to_cielab (msh):
    
    cielab = np.empty_like (msh)
    cielab[...,L] = msh[...,M] * np.cos (msh[...,S])
    cielab[...,A] = msh[...,M] * np.sin (msh[...,S]) * np.cos (msh[...,H])
    cielab[...,B] = msh[...,M] * np.sin (msh[...,S]) * np.sin (msh[...,H])
    return cielab