Best Python code snippet using keyboard
get_properties.py
Source:get_properties.py
1import os2import re3import sys4import argparse5import numpy as np6class Gaussian09:7 def __repr__(self):8 return "Extract information from Gaussian09 outputs"9 def __init__(self,output):10 self.out = open(output, 'r')11 self.lines = self.out.readlines()12 self.out.close()13 @property 14 def get_atom_labels(self):15 out_string = ''.join(self.lines)16 tmp = re.findall(r'^ [A-Z] ', out_string, flags=re.MULTILINE)17 labels = np.asarray([i.strip() for i in tmp])18 return labels19 @property20 def get_coords(self):21 xyz_list = list()22 match = False23 count = 024 for line in self.lines:25 if 'Input orientation' in line:26 match = True27 count += 128 continue29 elif match and (count >= 5):30 if len(line.split()) != 6:31 break32 xyz = np.array(line.split()[-3:], dtype=np.float64)33 xyz = xyz.reshape(-1,3)34 xyz_list.append(xyz) 35 elif match:36 count += 137 coords = np.vstack(xyz_list)38 coords = np.expand_dims(coords, axis=0)39 return coords40 @property41 def get_forces(self):42 ua_to_kcal = 1185.821214378384643 start_reading = False44 count = 045 F_list = list()46 for line in self.lines:47 if start_reading:48 count += 149 if 'Forces (Hartrees/Bohr)' in line:50 start_reading = True51 count += 152 continue53 elif start_reading and (count >= 4):54 if len(line.split()) != 5:55 break56 xyz = np.array(line.split()[-3:], dtype=np.float64)57 xyz = xyz.reshape(-1,3)58 F_list.append(xyz)59 forces = np.vstack(F_list)60 forces *= ua_to_kcal61 forces = np.expand_dims(forces, axis=0)62 return forces63 @property64 def get_total_energy(self):65 for line in self.lines:66 if 'SCF Done' in line:67 total_energy = np.array(line.split()[4], dtype=np.float64, ndmin=2)68 total_energy *= 627.509608030592769 return total_energy70 @property71 def get_homo_lumo(self):72 for line in self.lines:73 if ' occ. ' in line:74 e_homo = float(line.split()[-1])75 if ' virt. ' in line:76 e_lumo = float(line.split()[4])77 break78 e_homo_lumo = np.array([e_homo, e_lumo])79 e_homo_lumo = e_homo_lumo.reshape(-1,2)80 e_homo_lumo *= 27.211399 # convert from Hartree to eV81 return e_homo_lumo82 @property83 def get_dipole(self):84 # match_number = re.compile('-?\ *[0-9]+\.?[0-9]*(?:[D]\ *-?\ *[0-9]+)?')85 scinot = re.compile('[-+]?[\d]+\.?[\d]*[Dd](?:[-+]?[\d]+)?')86 for line in self.lines:87 if 'Dipole ' in line:88 dipole = [x.replace('D','E') for x in re.findall(scinot, line)]89 dipole = np.array(dipole, dtype=np.float64)90 dipole = dipole.reshape(1,3)91 return dipole92 @property93 def get_mulliken(self):94 count = -195 start_reading = False96 charges = list()97 pattern1 = 'Mulliken charges:'98 pattern2 = 'Mulliken atomic charges:'99 for line in self.lines:100 if pattern1 in line or pattern2 in line:101 start_reading = True102 continue103 if start_reading:104 count += 1105 if count >= 1:106 if len(line.split()) != 3:107 break108 charges.append(line.split()[-1])109 charges = np.array(charges, dtype=np.float64)110 n_atoms = len(charges)111 charges = charges.reshape(1, n_atoms, 1)112 return charges113 @property114 def get_zpve(self):115 start_reading = False116 for line in self.lines:117 if 'vibrational energy' in line:118 start_reading = True119 continue120 if start_reading:121 zpve = np.array(line.split()[0], dtype=np.float64, ndmin=2)122 return zpve123 @property124 def _get_exact_polar(self):125 for line in self.lines:126 if 'Exact polarizability' in line:127 polar = np.array(line.split()[-6:], dtype=np.float64)128 polar = polar.reshape(-1,6)129 return polar130 @property131 def get_polarizability(self):132 start_reading = False133 scinot = re.compile('[-+]?[\d]+\.?[\d]*[Dd](?:[-+]?[\d]+)?')134 for line in self.lines:135 if 'Polarizability' in line:136 start_reading = True137 p1 = [x.replace('D','E') for x in re.findall(scinot, line)]138 if start_reading:139 p2 = [x.replace('D','E') for x in re.findall(scinot, line)]140 polar = np.array((p1 + p2), dtype=np.float64)141 polar = polar.reshape(-1,6)142 return polar143 @property144 def get_rot_constants(self):145 for line in self.lines:146 if 'Rotational constants' in line:147 rot_const = np.array(line.split()[-3:], dtype=np.float64)148 rot_const = rot_const.reshape(1,3)149 return rot_const150 @property151 def get_elec_spatial_ext(self):152 for line in self.lines:153 if 'Electronic spatial extent' in line:154 r2 = np.array(line.split()[-1], dtype=np.float64, ndmin=2)155 return r2156 @property157 def get_thermal_energies(self):158 count = 0 159 thermal_energies = list()160 pattern = 'Sum of electronic and thermal'161 for line in self.lines:162 if pattern in line:163 thermal_energies.append(line.split()[-1])164 count += 1165 if count == 3:166 break167 thermal_energies = np.array(thermal_energies, dtype=np.float64)168 thermal_energies *= 627.5096080305927169 thermal_energies = thermal_energies.reshape(-1,3)170 return thermal_energies171 @property172 def get_frequencies(self):173 freq_list = list()174 pattern = "Frequencies "175 for line in self.lines:176 if pattern in line:177 f = line.split()[-3:]178 freq_list.append(f)179 freqs = np.array(freq_list, dtype=np.float64)180 freqs = freqs.flatten()181 freqs = np.expand_dims(freqs, axis=0)182 return freqs183if __name__ == "__main__":184 parser = argparse.ArgumentParser()185 parser.add_argument("-log", default=None, type=str, help = "full path to the output file")186 parser.add_argument("-prop", default=None, type=str, help = "property to be read from the output")187 if len(sys.argv) == 1:188 args = parser.parse_args(["--help"])189 else:190 args = parser.parse_args()191 log_file = args.log192 property = args.prop193 try:194 g09_output = Gaussian09(log_file)195 print(g09_output)196 print(" ")197 except:198 print("Oops! File not found. Try again.")199 sys.exit()200 all_properties = {'labels': g09_output.get_atom_labels,201 'coords': g09_output.get_coords,202 'Etot': g09_output.get_total_energy,203 'e_hl': g09_output.get_homo_lumo,204 'alpha': g09_output.get_polarizability,205 'dipole': g09_output.get_dipole,206 'e_vib': g09_output.get_zpve,207 'rot': g09_output.get_rot_constants,208 'r2': g09_output.get_elec_spatial_ext,209 'forces': g09_output.get_forces,210 'e_thermal': g09_output.get_thermal_energies,211 'freqs': g09_output.get_frequencies,212 'mulliken': g09_output.get_mulliken}213 if property is None or property == 'all':214 print('Reading all properties from file: {}'.format(log_file))215 print('-------------------------------------')216 for k, val in all_properties.items():217 print(k, val)218 else:219 if ',' in property:220 props = [p.strip() for p in property.split(',')]221 print('Reading {} properties from file: {}'.format(len(props),log_file))222 print('-------------------------------------')223 for p in props:224 try:225 print(p, all_properties[p])226 except:227 print(" ")228 print("Oops! Key not found in dictionary.\n")229 print("The available options are", list(all_properties.keys()))230 else:231 p = property.strip()232 print('Reading {} from file: {}'.format(p,log_file))233 print('-------------------------------')234 try:235 print(p, all_properties[p])236 except:237 print(" ")238 print("Oops! Key not found in dictionary.\n")...
read_xsf_example.py
Source:read_xsf_example.py
1from numpy import *2def read_example_xsf_density(filename):3 lattice=[]4 density=[]5 grid=[]6 shift=[]7 i=08 start_reading = False9 with open(filename, 'r') as f:10 for line in f:11 if "END_DATAGRID_3D" in line:12 start_reading = False13 if start_reading and i==1:14 grid=array(line.split(),dtype=int)15 if start_reading and i==2:16 shift.append(array(line.split(),dtype=float))17 if start_reading and i==3:18 lattice.append(array(line.split(),dtype=float))19 if start_reading and i==4:20 lattice.append(array(line.split(),dtype=float))21 if start_reading and i==5:22 lattice.append(array(line.split(),dtype=float))23 if start_reading and i>5: 24 density.extend(array(line.split(),dtype=float))25 if start_reading and i>0:26 i=i+127 if "DATAGRID_3D_UNKNOWN" in line:28 start_reading = True29 i=130 31 rho=zeros((grid[0],grid[1],grid[2]))32 ii=033 for k in range(grid[2]):34 for j in range(grid[1]): 35 for i in range(grid[0]):36 rho[i,j,k]=density[ii]37 ii+=138 # convert density to 1/Angstrom**3 from 1/Bohr**339 a0=0.5291772106740 a03=a0*a0*a041 rho/=a0342 # since in xsf format the lattice is given as A^T,43 # let's return A by taking the transpose, i.e., 44 # A = transpose(lattice)45 return rho, transpose(array(lattice)), grid, shift46def main():47 filename = 'dft_chargedensity1.xsf'48 rho, lattice, grid, shift = read_example_xsf_density(filename)49 50if __name__=="__main__":...
fragments.py
Source:fragments.py
1from typing import List, Set2from Bio.Seq import Seq3from Bio.SeqRecord import SeqRecord4from code.codon_group import Group, codon_group5def start_stop_fragments(6 seq_record: SeqRecord,7 minimum_fragment_length: int = 100,8 start_codons: Set[str] = {"ATG"},9 stop_codons: Set[str] = {"TAA", "TAG", "TGA"}10) -> List[Seq]:11 nucleotides: Seq = seq_record.seq12 start_stop_fragments: List[Seq] = []13 nucleotide_strand: Seq14 for nucleotide_strand in [nucleotides, nucleotides.reverse_complement()]:15 for frame in range(3):16 frame_codons: List[str] = codon_group(17 nucleotide_strand, Group.CODON, frame)18 fragment = Seq("")19 start_reading = False20 for codon in frame_codons:21 if codon in start_codons:22 start_reading = True23 fragment += codon24 elif start_reading:25 fragment += codon26 if codon in stop_codons:27 start_reading = False28 start_stop_fragments.append(fragment)29 fragment = Seq("")30 return [31 fragment for fragment in start_stop_fragments32 if len(fragment) > minimum_fragment_length...
shrinkVol.py
Source:shrinkVol.py
1from numpy import *2scale = 1000.3fin = open('PPM_ABAQUS.inp', 'r')4contents = fin.readlines()5fin.close()6fout = open('PPM_ABAQUS_shrunk.inp','w')7start_reading = False8for line in contents:9 if line[0:1] == '*' and line[0:5] != '*Node':10 start_reading = False11 if start_reading == True:12 n_id = int(line.split(',')[0])13 x = double(line.split(',')[1])/1000.14 y = double(line.split(',')[2])/1000.15 z = double(line.split(',')[3])/1000.16 fout.write('%d,%f,%f,%f\n'%(n_id,x,y,z))17 else:18 fout.write(line)19 if line[0:5] == '*Node' and len(line) <= 6:20 start_reading = True...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!