def get_intermolecular(self): line_16I5 = fortranformat.FortranRecordWriter('16I5') line_I5 = fortranformat.FortranRecordWriter('I5') _tmp_str = list() for mol_1, mol_2_list in zip(self._intermol1,\ self._intermol2): ### First, check if the molecule has more ### than one conformer. If not, continue with ### for-loop. N_mols = 1 for mol_2 in mol_2_list: if mol_2 != mol_1: N_mols += 1 if N_mols == 1: continue for atm_idx in range(self._mol_list[mol_1].GetNumAtoms()): _mols_list = list() _mols_list.append(mol_1 + 1) _mols_list.append(atm_idx + 1) for mol_2 in mol_2_list: if mol_2 != mol_1: _mols_list.append(mol_2 + 1) _mols_list.append(atm_idx + 1) if len(_mols_list) > 0: _tmp_str.append(line_I5.write([N_mols])) _tmp_str.append('\n') _tmp_str.append(line_16I5.write(_mols_list)) _tmp_str.append('\n') return ''.join(_tmp_str)
def write_file(name, data, box, weights=[], Format='config'): if Format == 'xyz' or Format == 'both': opf = open(name + ".xyz", "w") opf.write(str(len(elements)) + "\n\n") for t in range(len(data)): opf.write(data[t] + " " + str(data[t][1][0]) + " " + str(data[t][1][1]) + " " + str(data[t][1][2]) + "\n") opf.close() if Format == "config" or Format == 'both': opf = open(name, "w") line1 = ff.FortranRecordWriter('(I10, I10, I10, F20.10)') line_cell = ff.FortranRecordWriter('(3F20.10)') line_atom1 = ff.FortranRecordWriter('(A8, I10)') #, F20.10)') line_atom2 = ff.FortranRecordWriter('(3F20.10)') opf.write("\n" + line1.write([0, 3, len(data), 0.0]) + "\n") opf.write(line_cell.write([box, 0, 0]) + "\n") opf.write(line_cell.write([0, box, 0]) + "\n") opf.write(line_cell.write([0, 0, box]) + "\n") # print coords for t in range(len(data)): opf.write(line_atom1.write([data[t][0], t + 1]) + "\n") #, float(weights[data[t][0]])])+"\n") opf.write( line_atom2.write([data[t][1][0], data[t][1][1], data[t][1][2]]) + "\n") opf.close()
def write_ofile(ofile, energy, natoms, dipole=None, gradient=None, polarizability=None, dipole_derivative=None): # Define output formats headformat = ff.FortranRecordWriter("4D20.12") bodyformat = ff.FortranRecordWriter("3D20.12") # Print output header: if dipole is None: dipole = np.zeros((3)) head = [energy, dipole[0], dipole[1], dipole[2]] f = open(ofile, "w") # Write headers headstring = headformat.write(head) f.write(headstring + "\n") # Write gradient section if gradient is None: gradient = np.zeros((natoms, 3)) assert gradient.shape[ 0] == natoms, "ERROR: First dimension of gradient doesn't match natoms." assert gradient.shape[ 1] == 3, "ERROR: Second dimension of gradient is not 3." for i in range(natoms): output = bodyformat.write(gradient[i]) f.write(output + "\n") # Write polarization section if polarizability is None: polarizability = np.zeros((2, 3)) for i in range(2): output = bodyformat.write(polarizability[i]) f.write(output + "\n") # Write dipole derivative section if dipole_derivative is None: dipole_derivative = np.zeros((3 * natoms, 3)) for i in range(3 * natoms): output = bodyformat.write(dipole_derivative[i]) f.write(output + "\n") f.close()
def _add_electronic_distribution(self, input_lines: list) -> None: """ Add the lines showing the electronic distribution of the valence orbitals """ ## Formaters quantum_number_formater = ff.FortranRecordWriter('2i5') occupation_formater = ff.FortranRecordWriter('2f10.3') ## Append lines for orbital in self.valence_orbitals: quantum_numbers = quantum_number_formater.write( [orbital["n"], orbital["l"]]) occupation = occupation_formater.write(orbital["occupation"]) input_lines.append("{}{}\n".format(quantum_numbers, occupation))
def GetSubTableLines(self, prop): print("Making Subtable " + prop) d = { 'H': 1, 'A': 2, 'v': 3, 'CVMASS': 4, 'CPMASS': 5, 'dPdv': 6, 'S': 7, 'V': 8, 'L': 9 } nr = d[prop] lines = [] w = ff.FortranRecordWriter('(3ES17.7E3)') lines.append("$TABLE_" + str(nr)) lines.append("{:10d}".format(self.nT) + "{:10d}".format(self.nP)) lines.append(w.write(self.T_vec)) lines.append(w.write(self.P_vec)) print("writing properties") lines.append(w.write(self.GetPropArray(prop))) print("writing sat properties T") lines.append(w.write(self.GetSatPropertiesVec(self.P_vec, "T"))) print("writing properties " + prop) lines.append(w.write(self.GetSatPropertiesVec(self.P_vec, prop))) return lines
def write_value(self, formatt, value): header_line = ff.FortranRecordWriter(formatt) if isinstance(value, int) or isinstance(value, str): mane = header_line.write([value]) else: mane = header_line.write(value) return mane
def cubegen(xmin, ymin, zmin, dx, dy, dz, nx, ny, nz, filename, data, array_val): data = h5.File(dataloc, 'r') file = open(filename, "w") file.write("Cube file written using python density utility \n") file.write("LiH electronic density \n") file.write('{:5} {:11.6f} {:11.6f} {:11.6f} \n'.format( data['/nuclear_coord/num_of_nucl'][0], xmin, ymin, zmin)) file.write('{:5} {:11.6f} {:11.6f} {:11.6f} \n'.format( nx, dx, 0.000000, 0.000000)) file.write('{:5} {:11.6f} {:11.6f} {:11.6f} \n'.format( ny, 0.000000, dy, 0.000000)) file.write('{:5} {:11.6f} {:11.6f} {:11.6f} \n'.format( nz, 0.000000, 0.000000, dz)) for i in np.arange(0, data['/nuclear_coord/num_of_nucl'][0]): file.write('{:5} {:11.6f} {:11.6f} {:11.6f} {:11.6f} \n'.format( 1, 1.000000, data['/nuclear_coord/nucl_cartesian_array'][0][i][0], data['/nuclear_coord/nucl_cartesian_array'][0][i][1], data['/nuclear_coord/nucl_cartesian_array'][0][i][2])) data.close() lineformat = ff.FortranRecordWriter('(1E13.5)') for ix in np.arange(0, nx): for iy in np.arange(0, ny): for iz in np.arange(0, nz): # file.write('{:13.5E}'.format(array_val[ix][iy][iz])) file.write(lineformat.write([array_val[ix][iy][iz]])) if ((iz + 1) % 6 == 0 and iz != 0): file.write('\n') file.write('\n') file.close()
def to_stringlist(self) -> list: """ Returns: potcar_lines (list): List of the POTCAR lines """ fourier_coefficients_lines = [ "{:<3}{}{:<5}\n".format('', self.k_max_text, '') ] try: grouped_coefficients = self.potential.reshape((-1, 5)) except ValueError as bad_shape: raise ValueError( "Fourier coefficents not provided correctly") from bad_shape fortran_formater = ff.FortranRecordWriter('(1E26.8)') for group in grouped_coefficients: formated_numbers = [] for number in group: formated_numbers.append( fortran_formater.write([number]).strip()) line = "{:<2}{}\n".format('', " ".join(formated_numbers)) fourier_coefficients_lines.append(line) lines = [ self.psctr_parameters, fourier_coefficients_lines, self.last_lines ] return list(chain.from_iterable(lines))
def to_file_custom(self, name, ranges): logging.info(u'') logging.info(u'*********************************************') logging.info(u' Writing cube to %s' % name) logging.info(u'*********************************************') logging.info(u'') with open(name, 'w') as f: f.write("\n\n") f.write( "%5d%12.6f%12.6f%12.6f\n" % (len(self.atoms), self.origin.x, self.origin.y, self.origin.z)) for n, v in zip(self.size, self.vectors): f.write("%5d%12.6f%12.6f%12.6f\n" % (n, v.x, v.y, v.z)) for a in self.atoms: f.write("%5d%12.6f%12.6f%12.6f%12.6f\n" % (ELEMENTS[a.name()].number if a.name() != 'Q' else 0, a.data()[AtomKeys.FULL_VALENCE], a.position().x, a.position().y, a.position().z)) i = 0 lf = ff.FortranRecordWriter('(6e13.5)') size = (ranges[0][1] - ranges[0][0]) * ( ranges[1][1] - ranges[1][0]) * (ranges[2][1] - ranges[2][0]) for x in xrange(ranges[0][0], ranges[0][1]): for y in xrange(ranges[1][0], ranges[1][1]): for z in xrange(ranges[2][0], ranges[2][1]): f.write(lf.write([self.voxel_value([x, y, z])])) i += 1 if i % (size / 10) == 0: logging.debug(u' %d of %d' % (i, size)) if z % 6 == 5: f.write("\n") f.write("\n") f.write("\n")
def rewrite_turbomole_gradient(number_of_atoms, xyz, total_restraint_energy, total_restraint_gradients, restraint_gradient): """Rewrite new gradient file in turbomole format""" import re with open('gradient', 'r') as gradient_file: gradient_contents = gradient_file.read() gradients = re.split("cycle", gradient_contents) prelog = "cycle".join(gradients[:-1]) last_gradient = gradients[-1] list_from_last_gradient = last_gradient.split('\n') cycle_number = int(list_from_last_gradient[0].split()[1]) scf_energy = float(list_from_last_gradient[0].split()[5]) total_gradients = float(list_from_last_gradient[0].split()[8]) new_energy = scf_energy + total_restraint_energy new_total_gradients = total_gradients + total_restraint_gradients new_gradients = "cycle = %6d SCF energy =%20.10f |dE/dxyz| =%10.6f \n" \ % (cycle_number, new_energy, new_total_gradients) for line in list_from_last_gradient[1:number_of_atoms + 1]: new_gradients = new_gradients + line + "\n" i = 0 for line in list_from_last_gradient[number_of_atoms + 1:number_of_atoms * 2 + 1]: dx, dy, dz = line.split()[0], line.split()[1], line.split()[2] dx = float(re.sub('D', 'E', dx)) - restraint_gradient[i][0] dy = float(re.sub('D', 'E', dy)) - restraint_gradient[i][1] dz = float(re.sub('D', 'E', dz)) - restraint_gradient[i][2] formatted = ff.FortranRecordWriter('3D22.13') temp_line = formatted.write([dx, dy, dz]) new_gradients = new_gradients + str(temp_line) + "\n" i += 1 with open('gradient', 'w') as g: g.write(prelog + new_gradients + '$end')
def fcidump(self, filename="/tmp/hamiltonian.FCIDUMP", frozen_core=True, MS2=0, NROOT=1, ISYM=1, **kwds): """ save matrix elements of Hamiltonian in MO basis in the format understood by Knowles' and Handy's Full CI program. The structure of the input data is described in [FCI] Knowles, Peter J., and Nicholas C. Handy. "A new determinant-based full configuration interaction method." Chem. Phys. Lett. 111(4-5) (1984): 315-321. Parameters ---------- filename : str path to FCIDUMP output file frozen_core : bool If True, 1s core orbitals are replaced by an effective Hamiltonian Additional variables for the header of the FCI programm can be specified as keywords. See section 3.3.1 in [FCI] for a list of all variables. Keywords -------- MS2 : int total spin NROOT : int number of states in the given spin and symmetry space ISYM : int spatial symmetry of wavefunction ... """ import fortranformat formatter=fortranformat.FortranRecordWriter('(E24.16,I4,I4,I4,I4/)') h0, h1, h2 = self.hamiltonian_MO(frozen_core=frozen_core) with open(filename, "w") as f: # header f.write(f"$FCI NORB={self.nmo-self.ncore},NELEC={self.nelec-2*self.ncore},\n") f.write(f" MS2={MS2},ISYM={ISYM},NROOT={NROOT},\n") for key,value in kwds.items(): # additional keywords f.write(f" {key}={value},\n") f.write("$END\n") # number of valence orbitals nmo = self.nmo-self.ncore # enumerate two-electron integrals for i in range(0,nmo): for j in range(0, nmo): for k in range(0, nmo): for l in range(0, nmo): f.write(formatter.write([ h2[i,j,k,l], i+1,j+1,k+1,l+1 ])) # enumerate one-electron integrals for i in range(0, nmo): for j in range(0, nmo): f.write(formatter.write([ h1[i,j], i+1,j+1, 0, 0 ])) # core energy f.write(formatter.write([ h0, 0, 0, 0, 0 ]))
def _add_second_line(self, input_lines: list) -> None: """ Add the second line of the INP file """ ## Select formater if len(self.chemical_symbol) == 1: second_line_formater = ff.FortranRecordWriter('1x,a3,2x,a4,2x') else: second_line_formater = ff.FortranRecordWriter('1x,a4,1x,a4,2x') ## Construct line chemical_symbol_line = "n={}".format(self.chemical_symbol) exchange_correlation_line = "c={}".format( self.exchange_correlation_code) input_lines.append("{}\n".format( second_line_formater.write( [chemical_symbol_line, exchange_correlation_line])))
def write(var): var = np.atleast_1d(var) if isinstance(var[0], np.integer): fmt = '(%iI12)' % var.size elif isinstance(var[0], np.double): fmt = '(%iE24.15E3)' % var.size else: fmt = '(A)' writer = ff.FortranRecordWriter(fmt) f.write(writer.write(var) + '\n')
def _add_fourth_line(self, input_lines: list) -> None: """ Add the fourth line of the INP file """ ## Formater orbital_numbers_formater = ff.FortranRecordWriter('2i5') ## Add the number of core and valence orbitals orbital_numbers = orbital_numbers_formater.write( [self.number_core_orbitals, self.number_valence_orbitals]) input_lines.append("{}\n".format(orbital_numbers))
def get_group(self): line_I5_F105 = fortranformat.FortranRecordWriter('I5,F10.5') line_16I5 = fortranformat.FortranRecordWriter('16I5') _tmp_str = list() group_index_list = np.arange(len(self._group_atom_list)) for group_i in range(self._group_count): ### group_valids_bool is True whereever an atom is in ### the group with group id group_i. ### group_valids_int gives the list indices of every atom ### in self._group_atom_list that is in group group_i. group_valids_bool = np.isin(self._group_id_list, group_i) group_valids_int = group_index_list[group_valids_bool] group_size = group_valids_int.shape[0] group_charge = self._group_charge_list[group_i] _tmp_str.append(line_I5_F105.write([group_size, group_charge])) _tmp_str.append('\n') atom_list = list() for valids_i in group_valids_int: atom_i = self._group_atom_list[valids_i] mol_id = self._group_mol_list[valids_i] atom_list.append(mol_id + 1) atom_list.append(atom_i + 1) _tmp_str.append(line_16I5.write(atom_list)) _tmp_str.append('\n') _tmp_str.append('\n') return ''.join(_tmp_str)
def write(fp, derivative_requested: int, energy: float, number_of_atoms: int, dipole: np.ndarray = None, gradient: np.ndarray = None, polarizability: np.ndarray = None, dipole_derivatives: np.ndarray = None) -> None: """Write the *.EOu file""" # Define output formats head_format = ff.FortranRecordWriter('4D20.12') body_format = ff.FortranRecordWriter('3D20.12') if dipole is None: dipole = np.zeros(3) fp.write(head_format.write([energy, *dipole]) + '\n') # gradient if derivative_requested > 0: if gradient is None: gradient = np.zeros((number_of_atoms, 3)) for i in range(number_of_atoms): fp.write(body_format.write(gradient[i]) + '\n') # polarizability if polarizability is None: polarizability = np.zeros((2, 3)) for i in range(2): fp.write(body_format.write(polarizability[i]) + '\n') # dipole derivatives if dipole_derivatives is None: dipole_derivatives = np.zeros((3 * number_of_atoms, 3)) for i in range(3 * number_of_atoms): fp.write(body_format.write(dipole_derivatives[i]) + '\n')
def write_model_coefs(rem3d_file, pixel_width=1.0): line = ff.FortranRecordWriter('(6E12.4)') shape = (int(180.0 / pixel_width), int(360.0 / pixel_width)) for i in range(0, len(depths) - 1): print 'writing coefficients for layer ', i + 1 epixname = 's40rts_{:1.1f}_{:1.1f}.epix'.format( depths[i], depths[i + 1]) epixarr = np.loadtxt(epix_dir + '/' + epixname) coefs = epixarr[:, 3] coefs = np.reshape(coefs, shape, order='F') coefs_pts = coefs.flatten() rem3d_file.write('STRU {:3.0f}: {:1.0f}\n'.format( i + 1, pixel_width)) rem3d_file.write(line.write(coefs_pts) + '\n')
def write_syn_runlog(path, v0=4750, v1=8250, DELTA_NU=0.0111111111): ''' Input: - path : full path to an existing runlog - v0 : starting wavenumber (cm-1) - v1 : last wavenumber (cm-1) - delta_nu : wavenumber spacing (cm-1) This will write a new runlog that can be used to generate synthetic spectra. The new runlog will be saved in the same place but the filename will finish with "_syn.grl" ''' with open(path, 'r') as infile: content = infile.readlines() syn_dict = { 'BPW': 7, 'POINTER': 0, 'APF': 'N1', 'DELTA_NU': DELTA_NU, 'IFIRST': int(round(v0 / DELTA_NU)), 'ILAST': int(round(v1 / DELTA_NU)), 'SNR': 1000, } header = [' '] + content[3].split() ID_dict = {key: header.index(key) for key in syn_dict} fmt = list(parse.parse('format={}\n', content[2]))[0] reader = ff.FortranRecordReader(fmt) writer = ff.FortranRecordWriter(fmt) for i, line in enumerate(content): if i >= 4: data = reader.read(line) for key in syn_dict: data[ID_dict[key]] = syn_dict[key] new_line = writer.write(data) + '\n' content[i] = new_line new_path = path.replace('.grl', '_syn.grl') with open(new_path, 'w') as outfile: outfile.writelines(content)
def write_grad(x): newdata = '' atomnum = len(x) / 3 with open("control") as c: lines = c.read().splitlines() n = get_last_grad(lines) for k in range(0, n + atomnum + 1): newdata += lines[k] + "\n" for k in range(n + atomnum + 1, n + atomnum * 2 + 1): an = k - n - atomnum - 1 newdata += ff.FortranRecordWriter( "( 2X,D20.14,2X,D20.14,2X,D20.14 )").write( x[an * 3:an * 3 + 3]) + '\n' pass for k in range(n + atomnum * 2 + 1, len(lines)): newdata += lines[k] + "\n" with open("control", 'w') as c: c.write(newdata)
def run_symmol(mol, tolerance=0.1 * u.angstrom): import fortranformat line_writer = fortranformat.FortranRecordWriter('(a6,i2,6f9.5)') if mol.num_atoms == 2: return _get_twoatom_symmetry(mol) infile = [ '1.0 1.0 1.0 90.0 90.0 90.0', # line 1: indicates XYZ coordinates # line 2: numbers indicate: mass weighted moment of inertia, # tolerance interpretation, tolerance value, # larger tolerance value (not used) '1 0 %f 0.0' % tolerance.value_in(u.angstrom) ] for atom in mol.atoms: infile.append( line_writer.write((atom.element, 1, atom.x.value_in(u.angstrom), atom.y.value_in(u.angstrom), atom.z.value_in(u.angstrom), 0.0, 0.0, 0.0))) infile.append('') command = 'symmol < sym.in' inputs = {'sym.in': '\n'.join(infile)} job = packages.symmol.make_job(command=command, inputs=inputs, name="symmol, %s" % mol.name) job = mdt.compute.run_job(job) data = parse_output(mol, job.get_output('symmol.out')) _prune_symmetries(data) symm = mdt.geom.MolecularSymmetry(mol, data.symbol, data.rms, orientation=get_aligned_coords( mol, data), elems=data.elems, _job=job) return symm
def GetValues(self): w = ff.FortranRecordWriter('(3ES17.7E3)') lines = [] lines.append(w.write(self.Psat)) lines.append(w.write(self.T_vec)) lines.append(w.write([0] * len(self.T_vec))) lines.append(w.write([0] * len(self.T_vec))) lines.append(w.write(self.Hl)) lines.append(w.write(self.cpl)) lines.append(w.write(self.dDdPl)) lines.append(w.write(self.Sl)) lines.append(w.write(self.Cvl)) lines.append(w.write(self.Al)) lines.append(w.write(self.Vl)) lines.append(w.write(self.Ll)) lines.append(w.write(self.Hg)) lines.append(w.write(self.cpg)) lines.append(w.write(self.dDdPg)) lines.append(w.write(self.Sg)) lines.append(w.write(self.Cvg)) lines.append(w.write(self.Ag)) lines.append(w.write(self.Vg)) lines.append(w.write(self.Lg)) return lines
# # Convert an HDF-format file to a TXT-format file import gyre import sys import numpy as np import fortranformat as ff # Arguments in_file = sys.argv[1] out_file = sys.argv[2] # Formatted writers ind_form = ff.FortranRecordWriter('(I25)') name_form = ff.FortranRecordWriter('(A25)') int_form = ff.FortranRecordWriter('(I25)') float_form = ff.FortranRecordWriter('(E25.16E3)') # Read the GYRE data d, r = gyre.read_output(in_file) # Write the output data with open(out_file, 'w') as f: # Label
def writeEQDSK(eq, fname): """Write out the equilibrium in G-EQDSK format. Code courtesy of eq_JET.py from OMFIT""" import fortranformat as ff import numpy as np # Open file for writing f = open(fname, 'w') nr = eq['nW'] nz = eq['nH'] # Get eq at this timeslice rdim = eq['rdim'] zdim = eq['zdim'] rcentr = eq['rcentr'] rleft = eq['rleft'] zmid = eq['zmid'] rmaxis = eq['rmaxis'] zmaxis = eq['zmaxis'] simag = eq['simag'] sibry = eq['sibry'] bcentr = eq['bcentr'] current = eq['current'] xdum = 0.0 def GetSlice(data, N, ti): return data[ti * N:(ti + 1) * N] # FPOL eq fpol = eq['fpol'] # Pressure eq pressure = eq['pres'] # FFPRIM eq ffprim = eq['ffprim'] # PPRIME eq pprime = eq['pprime'] # PSI eq psi = np.transpose(eq['psizr']) # Q eq q = eq['qpsi'] # Plasma Boundary Rbnd = eq['rbbbs'] Zbnd = eq['zbbbs'] n_bnd = eq['nbbbs'] # Limiter eq Rlim = eq['rlim'] Zlim = eq['zlim'] limitr = len(Rlim) # Write Eqdsk from ----------------------------------- f2020 = ff.FortranRecordWriter('5e16.9') f2022 = ff.FortranRecordWriter('2i5') def writeVar(handle, varList): f.write(handle.write(varList)) f.write("\n") def writeOrderedPairs(handle, var1, var2): longArrayOfPairs = [] for pv, _ in enumerate(var1): longArrayOfPairs.append(var1[pv]) longArrayOfPairs.append(var2[pv]) writeVar(handle, longArrayOfPairs) A52 = 'plasma.py v1.0 : 01:01:17'.ljust(48) f.write(A52[0:48]) writeVar(ff.FortranRecordWriter('3i4'), [0, nr, nz]) writeVar(f2020, [rdim, zdim, rcentr, rleft, zmid]) writeVar(f2020, [rmaxis, zmaxis, simag, sibry, bcentr]) writeVar(f2020, [current, simag, xdum, rmaxis, xdum]) writeVar(f2020, [zmaxis, xdum, sibry, xdum, xdum]) writeVar(f2020, fpol) writeVar(f2020, pressure) writeVar(f2020, ffprim) writeVar(f2020, pprime) writeVar(f2020, psi.flatten()) writeVar(f2020, q) writeVar(f2022, [n_bnd, limitr]) writeOrderedPairs(f2020, Rbnd, Zbnd) writeOrderedPairs(f2020, Rlim, Zlim) f.close()
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import fortranformat as ff import numpy as np import moldesign as mdt from moldesign import units as u from moldesign import utils line_writer = ff.FortranRecordWriter('(a6,i2,6f9.5)') #@doi('10.1107/S0021889898002180') def run_symmol(mol, tolerance=0.1 * u.angstrom, image='symmol', engine=None): infile = [ '1.0 1.0 1.0 90.0 90.0 90.0', # line 1: indicates XYZ coordinates # line 2: numbers indicate: mass weighted moment of inertia, # tolerance interpretation, tolerance value, # larger tolerance value (not used) '1 0 %f 0.0' % tolerance.value_in(u.angstrom) ] for atom in mol.atoms: infile.append( line_writer.write((atom.element, 1, atom.x.value_in(u.angstrom), atom.y.value_in(u.angstrom),
ccc Number of valid fields in the report ccc Number of errors encountered during the decoding of the report ccc Number of warnings encountered during the decoding the report end_format = ' ( 3 ( i7 ) ) ' c ... End of writing formats ''' HEADER_FORMAT = '( 2f20.5 , 2a40 , 2a40 , 1f20.5 , 5i10 , 3L10 , 2i10 , a20 , 13( f13.5 , i7 ) )' DATA_FORMAT = '( 10( f13.5 , i7 ) )' END_FORMAT = '( 3 ( i7 ) )' UNDEFINED_VALUE = -888888 header_writer = ff.FortranRecordWriter(HEADER_FORMAT) data_writer = ff.FortranRecordWriter(DATA_FORMAT) end_writer = ff.FortranRecordWriter(END_FORMAT) def replace_undefined(data): return [UNDEFINED_VALUE if x is None else x for x in data] class Record: ''' Represents one record in the observation file The record is identified by name, lat, lon and time and can have several optional measurements. Multiple measurements allow to enter measurements in several heights.
def metar2little_r(METARdir, Destdir, ifecha,window_min,window_max,coos): ''' Input: METARdir = directorio de ubicacion de archivos METAR decodificados Destdir = directorio de destino para archivo little_r_obs_3dvar ifecha = datetime con la fecha de inicio de la corrida en UTC coos = diccionario con informacion de los aeropuertos que se desean asimilar nota: el diccionario coos debe contener la altura entre sus datos Output: archivo little_r_obs_3dvar en el directorio Destdir ''' from datetime import datetime print('metar2little_r',METARdir, Destdir, ifecha) little_r=open(Destdir+'/'+'little_r_obs_3dvar','w') # downmetar descraga archivos mensuales fecha_archivo=ifecha.strftime("%Y-%m") #Generar vacios Er=-777777 empty=-888888 #Ciclo sobre aeropuertos for apto in coos.keys(): #Extraer variables para el Header Lat=float(coos[apto][0]) #Extraer latitud Lon=float(coos[apto][1]) #Extraer longitud ID='ICAO '+apto ID=ID.ljust(40) #justificar a izquierda Name='Aeropuerto de '+coos[apto][2] Name=Name.ljust(40) #justificar a izquierda Platform=str('FM-15 METAR') Platform=Platform.ljust(40) #justificar a izquierda Source=str('proveniente de metar.py') Source=Source.ljust(40) #justificar a izquierda Elevation=float(coos[apto][3]) #Extraer altura ValidFields=int(11) # abrir archivo de METAR del aeropuerto apto loc=METARdir+'/'+apto+'_'+fecha_archivo+'.csv' print(loc) try: a=open(loc,'r') data_METAR=a.readlines() for x in range(0,len(data_METAR)): linea=data_METAR[x].rstrip('\n') linea=linea.split(';') sfecha=linea[0]+'0000' #Cambiar si se tiene la fecha con minutos y segundos fecha=datetime.strptime(sfecha,"%Y%m%d%H0000") if fecha > window_min and fecha< window_max: SeaLevelPressure=float(linea[2]) #Pa magnitudViento=float(linea[1]) #m/s PuntoDeRocio=float(linea[3])+273.15 #K Temperatura=float(linea[5])+273.15 #K # Varibles en el Header # Latitud, Longitud, ID, Name, Platform, Source, Elevation, # ValidFields, Intempty, Intempty, seq_num?, Intempty, is_sound, bogus, discard # #sut, #julian, date_char, SeaLevelPressure qc, #emptydata+qcflag * 12 Header = ff.FortranRecordWriter('(F20.5, F20.5, A40, A40, A40, A40, F20.5, I10, I10, I10, I10, I10, L10, L10, L10, I10, I10, A20, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7)') PrintHeader = Header.write([Lat,Lon,ID,Name,Platform,Source,Elevation,ValidFields,empty,empty,int(x),empty,0,0,0,empty,empty,sfecha,SeaLevelPressure,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0,empty,0]) little_r.writelines(PrintHeader+'\n') # Variables en la linea de datos # Presion [Pa], altura [m], temperatura [K], pto de rocio [K], magnitud Viento [m/s], direccion Viento [grados], 4*empty Data = ff.FortranRecordWriter('(F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7)') PrintData = Data.write([empty, 0, Elevation, 0, Temperatura, 0, PuntoDeRocio, 0, magnitudViento, 0, empty, 0, empty, 0, empty, 0, empty, 0, empty, 0]) little_r.writelines(PrintData+'\n') # Imprimir final de datos EndData = ff.FortranRecordWriter('(F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7, F13.5, I7)') PrintEndData = EndData.write([Er, 0, Er, 0, 1.00000, 0, empty, 0, empty, 0, empty, 0, empty, 0, empty, 0, empty, 0, empty, 0]) little_r.writelines(PrintEndData+'\n') # Imprimir final de reporte EndReport = ff.FortranRecordWriter('(I7, I7, I7)') PrintEndReport = EndReport.write([ValidFields, 0, 0]) little_r.writelines(PrintEndReport+'\n') print 'escribio',Destdir+'/'+'little_r_obs_3dvar' except: print "NO existe", loc continue little_r.close() return None
def make_experiment(all_files, tmpdir, verbose, verbose_logfile, method, path, mydirvariable): # Angular axis m01000.sax Datafile m21000.sub 21-Jun-2001 # .0162755E+00 0.644075E+03 0.293106E+02 with open(tmpdir + '/method/curve_gajoe.dat', 'w') as file_gajoe: file_gajoe.write(' Angular axis m01000.sax Datafile m21000.sub 21-Jun-2001\n') lineformat = ff.FortranRecordWriter('(1E12.6)') with open(tmpdir + '/method/curve.modified.dat') as file1: for line in file1: if not line.strip(): break data1 = float(line.split()[0]) data2 = float(line.split()[1]) data3 = float(line.split()[2]) a = lineformat.write([data1]) x = a[1:] b = lineformat.write([data2]) c = lineformat.write([data3]) file_gajoe.write(f' {x} {b} {c}\n') # S values num_lines # 0.000000E+00 # ------ # Curve no. 1 # 0.309279E+08 num_lines = sum(1 for line in open(mydirvariable + all_files[0] + ".dat")) - 2 with open(tmpdir + '/method/juneom.eom', 'w') as file1: file1.write(f' S values {num_lines} \n') with open(mydirvariable + all_files[0] + ".dat") as file2: for line in file2: if line.startswith('#'): continue data = float(line.split()[0]) lineformat = ff.FortranRecordWriter('(1E14.6)') b = lineformat.write([data]) file1.write(f'{b}\n') for i, filename in enumerate(all_files, start=1): with open(mydirvariable + filename + ".dat") as file2: file1.write(f'Curve no. {i} \n') for line in file2: if line.startswith('#'): continue data1 = float(line.split()[1]) lineformat = ff.FortranRecordWriter('(1E14.6)') b = lineformat.write([data1]) file1.write(f'{b}\n') if verbose_logfile: logpipe = LogPipe(logging.DEBUG) logpipe_err = LogPipe(logging.ERROR) p1 = subprocess.Popen(['yes'], stdout=subprocess.PIPE) call = subprocess.Popen([path, f'{tmpdir}/method/curve_gajoe.dat', f'-i={tmpdir}/method/juneom.eom', '-t=5'], cwd=f'{tmpdir}/results/', stdin=p1.stdout, stdout=logpipe, stderr=logpipe_err) call.communicate() logpipe.close() logpipe_err.close() else: p1 = subprocess.Popen(['yes'], stdout=subprocess.PIPE) call = subprocess.Popen([path, f'{tmpdir}/method/curve_gajoe.dat', f'-i={tmpdir}/method/juneom.eom', '-t=5'], cwd=f'{tmpdir}/results/', stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) call.communicate() if call.returncode: print(f'ERROR: GAJOE failed', file=sys.stderr) logging.error(f'GAJOE failed.') sys.exit(1)
def convert_bbox_annotation(xml_file, sets='TRAIN'): filename = os.path.join(sets, 'ANNOTATIONS_'+sets, xml_file) tree = ET.parse(filename) subs = tree.findall('subcomponent') new_fmt_annos = [] img_infos = [] for idx, sub in enumerate(subs): if sub.find('name').text == 'bag': cls = 'bag' for id_num in list(sub)[1:]: category_text = id_num.find('category').text color_text = id_num.find('color').text if category_text != 'NULL': fine_cls = sub.find('name').text + \ ' ' + category_text + \ ' ' + color_text img_infos.append(fine_cls) bbox = id_num.find('bndbox') x1 = float(bbox.find('xmin').text) y1 = float(bbox.find('ymin').text) x2 = float(bbox.find('xmax').text) y2 = float(bbox.find('ymax').text) if x1 < x2 and y1 < y2: new_fmt_annos.append([x1, y1, x2, y2, cls]) else: if sub.find('category') is not None and \ sub.find('category').text != 'NULL': fine_cls = sub.find('name').text + \ ' ' + sub.find('category').text + \ ' ' + sub.find('color').text else: fine_cls = sub.find('name').text cls = sub.find('name').text img_infos.append(fine_cls) bbox = sub.find('bndbox') if bbox is not None: if bbox.find('xmin').text != 'NULL': x1 = float(bbox.find('xmin').text) y1 = float(bbox.find('ymin').text) x2 = float(bbox.find('xmax').text) y2 = float(bbox.find('ymax').text) if x1 < x2 and y1 < y2: new_fmt_annos.append([x1, y1, x2, y2, cls]) if sub.find('name').text == 'shoes': if sub.find('xmin_l').text != 'NULL': x1_l = float(sub.find('xmin_l').text) y1_l = float(sub.find('ymin_l').text) x2_l = float(sub.find('xmax_l').text) y2_l = float(sub.find('ymax_l').text) if x1_l < x2_l and y1_l < y2_l: new_fmt_annos.append([x1_l, y1_l, x2_l, y2_l, cls]) if sub.find('xmin_r').text != 'NULL': x1_r = float(sub.find('xmin_r').text) y1_r = float(sub.find('ymin_r').text) x2_r = float(sub.find('xmax_r').text) y2_r = float(sub.find('ymax_r').text) if x1_r < x2_r and y1_r < y2_r: new_fmt_annos.append([x1_r, y1_r, x2_r, y2_r, cls]) out_format = ff.FortranRecordWriter('(4(I5, 1X), A11)') if not os.path.exists(sets+'/bndboxes'): os.mkdir(sets+'/bndboxes') if not os.path.exists(sets+'/infos'): os.mkdir(sets+'/infos') label_file = open(os.path.join(sets, 'bndboxes', xml_file.split('.')[0]+'.txt'), 'w') info_file = open(os.path.join(sets, 'infos', xml_file.split('.')[0]+'.info'), 'w') for label in new_fmt_annos: out_string = out_format.write(label) print>>label_file, out_string for info in img_infos: print>>info_file, info label_file.close() info_file.close()
def get_atom_equiv(self): line_16I5 = fortranformat.FortranRecordWriter('16I5') line_I5 = fortranformat.FortranRecordWriter('I5') _tmp_str = list() mol_atom_i = [ x for x in zip(self._mol_equiv_mol_i, self._atom_equiv_list_i) ] mol_atom_j = [ x for x in zip(self._mol_equiv_mol_j, self._atom_equiv_list_j) ] exclude = list() for i in range(self._atom_equiv_count): if i in exclude: continue N_mols = 0 _mols_list = list() _mols_list.append(mol_atom_i[i][0] + 1) ## 9 1 _mols_list.append(mol_atom_i[i][1] + 1) _mols_list.append(mol_atom_j[i][0] + 1) ## 4 7 _mols_list.append(mol_atom_j[i][1] + 1) N_mols += 2 exclude.append(i) for j in range(self._atom_equiv_count): if j in exclude: continue if mol_atom_j[j] == mol_atom_i[i] \ and mol_atom_i[j] != mol_atom_i[i]: _mols_list.append(mol_atom_i[j][0] + 1) _mols_list.append(mol_atom_i[j][1] + 1) N_mols += 1 exclude.append(j) if mol_atom_i[j] == mol_atom_i[i] \ and mol_atom_j[j] != mol_atom_i[i]: _mols_list.append(mol_atom_j[j][0] + 1) _mols_list.append(mol_atom_j[j][1] + 1) N_mols += 1 exclude.append(j) if len(_mols_list) > 0: _tmp_str.append(line_I5.write([N_mols])) _tmp_str.append('\n') _tmp_str.append(line_16I5.write(_mols_list)) _tmp_str.append('\n') return ''.join(_tmp_str)
def get_mol(self): """ Return section containing element types, fitting weight, molecule title, number of atoms and atom equivalencing. groups_frozen: Freeze charges in groups to the values in qin file, typcially obtained from previous resp run. h_equiv : Fit charges of degenerate hydrogen atoms together all_equiv : Freeze charges of all degenerate atoms together. If this is activated, and h_equiv is deactivated, only heavy-atom atomic centers will be fitted together. """ line_2I5 = fortranformat.FortranRecordWriter('2I5') _tmp_str = list() for mol_i in range(self._mol_count): mol = self._mol_list[mol_i] _tmp_str.append(' %f\n' % self._mol_weight_list[mol_i]) _tmp_str.append(' %s\n' % self._mol_name_list[mol_i]) _charge = float(self._mol_charge_list[mol_i]) _charge = round(_charge) _charge = int(_charge) _natoms = mol.GetNumAtoms() _tmp_str.append(line_2I5.write([_charge, _natoms])) _tmp_str.append('\n') canonical_rank = list() string_rank = list(Chem.CanonicalRankAtoms(mol, breakTies=False)) for rank in string_rank: canonical_rank.append(int(rank)) del string_rank ### This really never worked perfectly... canonicalize_tautomers(canonical_rank, mol) index_list = np.arange(_natoms) if mol_i not in self._intermol1: for atom_i in index_list: atom = mol.GetAtomWithIdx(int(atom_i)) at_num = atom.GetAtomicNum() _tmp_str.append(line_2I5.write([at_num, 0])) _tmp_str.append('\n') else: for atom_i in index_list: atom = mol.GetAtomWithIdx(int(atom_i)) at_num = atom.GetAtomicNum() if mol_i in self._free_list_mol: mol_i_idx = self._free_list_mol.index(mol_i) if atom_i in self._free_list[mol_i_idx]: _tmp_str.append(line_2I5.write([at_num, 0])) _tmp_str.append('\n') continue placed_frozen = False if self.unfreeze_all: _tmp_str.append(line_2I5.write([at_num, 0])) elif self.groups_frozen: ### Check if atom itself is in group for index, atom_j in enumerate(self._group_atom_list): if atom_j==atom_i \ and self._group_mol_list[index] == mol_i: if self.noh_frozen and at_num != 1: _tmp_str.append( line_2I5.write([at_num, -1])) elif not self.h_groups_frozen and at_num == 1: if self.h_equiv: canon_eq_bool = np.isin( canonical_rank, canonical_rank[atom_i]) canon_eq_int = index_list[ canon_eq_bool] if atom_i == canon_eq_int[0]: _tmp_str.append( line_2I5.write([at_num, 0])) else: _tmp_str.append( line_2I5.write([ at_num, canon_eq_int[0] + 1 ])) else: _tmp_str.append( line_2I5.write([at_num, 0])) else: _tmp_str.append(line_2I5.write([at_num, 0])) placed_frozen = True break if not placed_frozen: if self.noh_frozen and at_num != 1: _tmp_str.append(line_2I5.write([at_num, -1])) elif (self.h_equiv and at_num == 1) \ or (self.all_equiv and not self.h_equiv and at_num != 1): ### canon_eq_bool is True for all atoms that are canonically ### equal to atom_i (including atom_i itself). ### canon_eq_int holds atom indices of all atoms that are ### canonically equal to atom_i (including atom_i itself). canon_eq_bool = np.isin(canonical_rank, canonical_rank[atom_i]) canon_eq_int = index_list[canon_eq_bool] ### This is fulfilled only when we encounter this canoncial ### rank (stored in canonical_rank[atom_i]) for the first ### time in this molecule. It will tell resp to let that ### atom center vary independly. if atom_i == canon_eq_int[0]: _tmp_str.append(line_2I5.write([at_num, 0])) ### If current atom atom_i is equivalent to another atom ### which is present in a different group than atom_i, then ### we should not equivalence constraints on these two atoms. ### If we already have encountered this canoncial rank before ### freeze atom_i to the atom that was our first encounter with ### this canonical rank. Note, that resp expects atom counting ### to start at 1, *not* 0. else: _tmp_str.append( line_2I5.write( [at_num, canon_eq_int[0] + 1])) # else: # found_in_group = False # for index2, atom_j in enumerate(self._group_atom_list): # if canon_eq_int[0]==atom_j \ # and self._group_mol_list[index2]==mol_i: # for index, atom_k in enumerate(self._group_atom_list): # if atom_i==atom_k \ # and self._group_mol_list[index]==mol_i: # if index2 == index: # _tmp_str.append(line_2I5.write([at_num, canon_eq_int[0]+1])) # else: # _tmp_str.append(line_2I5.write([at_num, 0])) # found_in_group = True # if found_in_group: # break # if found_in_group: # break # # if not found_in_group: # _tmp_str.append(line_2I5.write([at_num, 0])) else: _tmp_str.append(line_2I5.write([at_num, 0])) _tmp_str.append('\n') if self._mol_count > 1: _tmp_str.append('\n') return ''.join(_tmp_str)