Follow links to add evaluation to evaluate
T = 0.2
Prompt Override = insert
Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
---|---|---|---|---|---|
aa_polarity | Fail | Fail | Pass | Pass | Fail |
adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
alignment | Pass | Pass | Pass | Pass | Pass |
angle | Pass | Pass | Pass | Pass | Pass |
aromatic_aa | Pass | Pass | Pass | Pass | Pass |
arrhenius | Pass | Pass | Pass | Fail | Fail |
bimolecular | Pass | Pass | Pass | Pass | Pass |
bb_rad | Pass | Pass | Pass | Pass | Pass |
blast | Fail | Fail | Fail | Fail | Fail |
braggant | Pass | Pass | Pass | Pass | Pass |
bravais | Pass | Pass | Pass | Pass | Pass |
canonicalize | Pass | Pass | Pass | Pass | Pass |
carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
claussius | Fail | Pass | Fail | Pass | Pass |
compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
condiff_1d | Pass | Pass | Pass | Pass | Pass |
cubes | Pass | Pass | Fail | Pass | Pass |
de_broglie | Pass | Pass | Pass | Pass | Pass |
derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
derivative_2deg | Pass | Pass | Pass | Pass | Pass |
descriptors | Pass | Fail | Pass | Pass | Pass |
dipole | Pass | Pass | Pass | Pass | Pass |
dou | Fail | Fail | Fail | Fail | Fail |
eigen-ch | Pass | Pass | Pass | Pass | Pass |
eigen | Pass | Pass | Pass | Pass | Pass |
element_mass | Pass | Pass | Fail | Fail | Fail |
element_name | Pass | Pass | Pass | Pass | Pass |
energy_of_e | Pass | Pass | Pass | Pass | Pass |
find_indices | Fail | Fail | Fail | Fail | Fail |
force_constant | Fail | Fail | Fail | Fail | Fail |
fourier_1d | Pass | Pass | Pass | Pass | Pass |
freezing_depression | Pass | Pass | Pass | Pass | Pass |
genpos | Fail | Fail | Fail | Fail | Fail |
heating_water | Fail | Fail | Fail | Fail | Fail |
hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
ideal_gas | Pass | Pass | Pass | Pass | Pass |
integral | Fail | Fail | Fail | Fail | Fail |
trap | Pass | Pass | Pass | Pass | Pass |
invert_matrix | Pass | Pass | Pass | Pass | Pass |
iupac2smiles | Fail | Fail | Fail | Fail | Fail |
karplusant | Fail | Fail | Fail | Fail | Fail |
kld | Pass | Pass | Pass | Pass | Pass |
langevin_dynamics | Pass | Fail | Fail | Fail | Fail |
weighted-least-squares | Fail | Fail | Fail | Fail | Fail |
lipinski_rule_of_five | Pass | Pass | Pass | Pass | Pass |
mape | Fail | Fail | Fail | Fail | Fail |
mapping_operator | Fail | Fail | Fail | Fail | Fail |
matpow | Pass | Pass | Pass | Pass | Pass |
matrix_factorial | Fail | Pass | Pass | Pass | Pass |
max-boltz | Pass | Pass | Pass | Pass | Pass |
michaelis | Pass | Pass | Pass | Pass | Pass |
mol_charge | Fail | Pass | Pass | Fail | Pass |
net_charge | Pass | Pass | Pass | Pass | Pass |
solve_ode | Fail | Fail | Fail | Fail | Fail |
ohe | Fail | Fail | Fail | Fail | Fail |
osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
pair_wise | Fail | Fail | Fail | Fail | Fail |
pauli_matrices | Pass | Pass | Pass | Pass | Pass |
pi | Pass | Pass | Pass | Pass | Pass |
pib_1d | Pass | Pass | Pass | Pass | Pass |
pred_interval | Pass | Fail | Pass | Pass | Pass |
pubchem | Fail | Fail | Fail | Fail | Fail |
pyscf_energy | Fail | Fail | Fail | Fail | Fail |
qed | Fail | Fail | Fail | Fail | Fail |
quantile | Fail | Fail | Fail | Fail | Pass |
random_walk | Pass | Pass | Fail | Pass | Fail |
rank | Pass | Pass | Pass | Pass | Pass |
remove-water | Pass | Pass | Pass | Pass | Pass |
rms_velocity | Fail | Fail | Fail | Pass | Fail |
rmse | Pass | Pass | Pass | Pass | Pass |
rog | Pass | Pass | Pass | Pass | Pass |
rotationant | Pass | Pass | Pass | Pass | Pass |
rotation_higherant | Fail | Pass | Pass | Fail | Fail |
sasa | Fail | Fail | Fail | Fail | Fail |
scaffold | Fail | Fail | Fail | Fail | Fail |
seq-align | Fail | Fail | Fail | Fail | Fail |
seq-trans | Pass | Pass | Pass | Pass | Pass |
sequence | Pass | Pass | Pass | Pass | Pass |
sle | Fail | Fail | Fail | Fail | Fail |
spectral_r | Pass | Pass | Pass | Pass | Pass |
find_peaks | Fail | Fail | Fail | Pass | Fail |
speed_of_sound | Fail | Fail | Fail | Fail | Fail |
substructure | Fail | Fail | Fail | Fail | Fail |
tanimoto | Pass | Pass | Pass | Pass | Pass |
unbdistance | Fail | Fail | Fail | Fail | Fail |
velocity_verlet_integration | Pass | Pass | Pass | Pass | Pass |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return count
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == "R" or i == "K" or i == "H" or i == "D" or i == "E" or i == "S" or i == "T" or i == "N" or i == "Q" or i == "C" or i == "Y" or i == "W":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'K' or i == 'R' or i == 'H':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in range(len(sequence)):
if sequence[i] in ['S', 'T', 'N', 'Q']:
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i in "STNQ":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'R' or i == 'K' or i == 'D' or i == 'E' or i == 'Q' or i == 'N' or i == 'H' or i == 'S' or i == 'T' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return traj
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1 = np.array(v1)
v2 = np.array(v2)
angle = np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return count
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == "F" or i == "Y" or i == "W":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == 'F' or i == 'Y' or i == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == 'F' or i == 'Y' or i == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rate
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return B
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34
c = 299792458
k = 1.38064852e-23
B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34
c = 299792458
k = 1.38064852e-23
B = (2*h*c**2)/(lam**5*(np.exp((h*c)/(lam*k*T))-1))
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = 2*h*c**2/lam**5 * 1/(np.exp(h*c/(lam*k*T)) - 1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
B = 2.0*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1.0)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
B = 2*h*c**2/lam**5*1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, id
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'PAGE': 'Nucleotides', 'PROGRAM': 'blastn', 'DATABASE': 'nr', 'QUERY': seq}
r = requests.get(url, params=params)
# 3.
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre').text
# 4.
lines = result.split('\n')
msa = []
for line in lines:
if line.startswith('Query='):
msa.append(line.split()[1])
elif line.startswith('>'):
msa.append(line.split()[0][1:])
elif line.startswith(' Score'):
e = float(line.split()[2])
elif line.startswith('Query:'):
msa.append(line.split()[1])
elif line.startswith('Sbjct:'):
msa.append(line.split()[1])
msa = np.array(msa).reshape(-1, 4)
# 5.
id = msa[0, 1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
# 2. Submit BLAST search with sequences
r = requests.post('https://blast.ncbi.nlm.nih.gov/Blast.cgi',
data={'QUERY': seq,
'DATABASE': 'nr',
'PROGRAM': 'blastp',
'CMD': 'Put'})
# 3. Get result
r = requests.get('https://blast.ncbi.nlm.nih.gov/Blast.cgi',
params={'RID': r.text.split('\n')[-2].split('=')[-1],
'CMD': 'Get'})
# 4. Parse MSA
soup = BeautifulSoup(r.text, 'html.parser')
msa = soup.find_all('pre')[-1].text
# 5. Return a tuple of e score, id of top match
e = float(msa.split('\n')[1].split()[-2])
id = msa.split('\n')[1].split()[1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'PROGRAM': 'blastn', 'DATABASE': 'nt'}
r = requests.post(url, data=params)
# 3.
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', {'class': 'alignments'})
rows = table.find_all('tr')
alignments = []
for row in rows:
alignments.append(row.find_all('td'))
# 4.
alignments = np.array(alignments)
alignments = alignments[:, 1:]
alignments = alignments.reshape(alignments.shape[0], 3, -1)
alignments = alignments[:, :, :-1]
alignments = alignments.reshape(alignments.shape[0], -1)
alignments = alignments[:, :-1]
alignments = alignments.reshape(alignments.shape[0], 3, -1)
# 5.
e = alignments[0, 0, 0]
id = alignments[0, 1, 0]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq,
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'CMD': 'Put'}
r = requests.get(url, params=params)
# 3.
r = requests.get(r.url, stream=True)
soup = BeautifulSoup(r.text, 'html.parser')
# 4.
msa = soup.find_all('pre')[-1].text
msa = msa.split('\n')[3:-1]
msa = [i.split()[1] for i in msa]
msa = np.array(msa)
# 5.
e = soup.find_all('td')[-1].text
id = soup.find_all('td')[-2].text
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
from bs4 import BeautifulSoup
import requests
import numpy as np
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'PAGE': 'Nucleotides',
'PROGRAM': 'blastn',
'DATABASE': 'nr',
'QUERY': seq,
'CMD': 'Put'}
response = requests.get(url, params=params)
# 3.
soup = BeautifulSoup(response.text, 'html.parser')
result = soup.find('pre').text
# 4.
result = result.split('\n')
result = [line for line in result if line.startswith('>')]
result = [line.split('|')[3] for line in result]
result = [line.split(' ')[0] for line in result]
# 5.
e = float(result[0].split('e')[1])
id = result[0].split('e')[0]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
'NoneType' object has no attribute 'text'
braggant
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
[insert]
return theta
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arcsin(wavelength/(2*d))
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arcsin(wavelength/(2*d))
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arcsin(wavelength / (2 * d))
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arcsin(wavelength/(2*d))
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arcsin(wavelength / (2.0 * d))
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return name
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number < 3:
name = 'triclinic'
elif group_number < 16:
name = 'monoclinic'
elif group_number < 75:
name = 'orthorhombic'
elif group_number < 143:
name = 'tetragonal'
elif group_number < 168:
name = 'trigonal'
elif group_number < 195:
name = 'hexagonal'
elif group_number < 231:
name = 'cubic'
else:
print('Invalid space group number')
sys.exit()
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 3:
name = "triclinic"
elif group_number < 16:
name = "monoclinic"
elif group_number < 75:
name = "orthorhombic"
elif group_number < 143:
name = "tetragonal"
elif group_number < 168:
name = "trigonal"
elif group_number < 195:
name = "hexagonal"
elif group_number < 231:
name = "cubic"
else:
print("Unknown space group number")
sys.exit()
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number in range(1, 3):
name = 'triclinic'
elif group_number in range(3, 16):
name = 'monoclinic'
elif group_number in range(16, 75):
name = 'orthorhombic'
elif group_number in range(75, 143):
name = 'tetragonal'
elif group_number in range(143, 168):
name = 'trigonal'
elif group_number in range(168, 195):
name = 'hexagonal'
elif group_number in range(195, 231):
name = 'cubic'
else:
print('Space group number not in range')
sys.exit()
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 3:
name = 'triclinic'
elif group_number < 16:
name = 'monoclinic'
elif group_number < 75:
name = 'orthorhombic'
elif group_number < 143:
name = 'tetragonal'
elif group_number < 168:
name = 'trigonal'
elif group_number < 195:
name = 'hexagonal'
else:
name = 'cubic'
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number in range(1, 3):
name = "triclinic"
elif group_number in range(3, 16):
name = "monoclinic"
elif group_number in range(16, 75):
name = "orthorhombic"
elif group_number in range(75, 143):
name = "tetragonal"
elif group_number in range(143, 168):
name = "trigonal"
elif group_number in range(168, 195):
name = "hexagonal"
elif group_number in range(195, 231):
name = "cubic"
else:
sys.exit("Space group number not in range")
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_list
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - T_cold/T_hot
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp(HVap*(1/T1-1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap*(1/T1 - 1/T2))/(8.314*(1/T2 - 1/T1)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return result
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).pauling > mendeleev.element(element2).pauling:
result = True
return result
result = True if compare_electronegativity("O","C") else False
Output:
'Element' object has no attribute 'pauling'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).pauling_en > mendeleev.element(element2).pauling_en:
result = True
return result
result = True if compare_electronegativity("O","C") else False
Output:
'Element' object has no attribute 'pauling_en'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else False
Output:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).pauling_electronegativity > mendeleev.element(element2).pauling_electronegativity:
result = True
return result
result = True if compare_electronegativity("O","C") else False
Output:
'Element' object has no attribute 'pauling_electronegativity'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else False
Output:
'>' not supported between instances of 'method' and 'method'
condiff_1d
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diff
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return s
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(n):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return l
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
l = h / (m * v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return d
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
derivative_2deg
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return deriv
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([Descriptors.MolWt(mol),
Descriptors.MolLogP(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.NumRotatableBonds(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.TPSA(mol),
Descriptors.LabuteASA(mol)])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(np.array(MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList]).CalcDescriptors(mol)))
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.NumHeteroatoms(mol),
Descriptors.NumRotatableBonds(mol),
Descriptors.NumAromaticRings(mol),
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
rdMolDescriptors.CalcExactMolWt(mol),
rdMolDescriptors.CalcTPSA(mol),
rdMolDescriptors.CalcNumRotatableBonds(mol),
rdMolDescriptors.CalcNumHBD(mol),
rdMolDescriptors.CalcNumHBA(mol),
rdMolDescriptors.CalcNumHeteroatoms(mol),
rdMolDescriptors.CalcNumAmideBonds(mol),
rdMolDescriptors.CalcNumRings(mol)
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.MolLogP(mol),
Descriptors.TPSA(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.NumRotatableBonds(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol)
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
dipole
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_moment
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.dot(coordinates.T, charges)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.dot(coordinates.T, charges)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros([3])
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return d
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
d = Descriptors.NumRadicalElectrons(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.NumRadicalElectrons(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
c = Descriptors.NumHAcceptors(mol)
n = Descriptors.NumHDonors(mol)
h = Descriptors.NumHs(mol)
hal = Descriptors.NumHalogenAtoms(mol)
d = (2*c + 2 - h + hal)/2
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
module 'rdkit.Chem.Descriptors' has no attribute 'NumHs'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
m = Chem.MolFromSmiles(smiles)
return rdMolDescriptors.CalcNumRotatableBonds(m)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
h = Descriptors.NumHAcceptors(mol)
c = Descriptors.NumHDonors(mol)
n = Descriptors.NumHeteroatoms(mol)
f = Descriptors.NumHalogenAtoms(mol)
d = (2*h + 2 - c + n + f)/2
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
module 'rdkit.Chem.Descriptors' has no attribute 'NumHalogenAtoms'
eigen-ch
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
eigen
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,v
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print("ERROR: Element symbol '" + element_symbol + "' not found")
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
mass = element.mass
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
try:
mass = mendeleev.element(element_symbol).mass
except:
print "Error: element symbol not found"
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Missing parentheses in call to 'print'. Did you mean print("Error: element symbol not found")? (<string>, line 13)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element mass not found for element", element_symbol
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Missing parentheses in call to 'print'. Did you mean print("Error: element mass not found for element", element_symbol)? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: Element symbol not found"
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Missing parentheses in call to 'print'. Did you mean print("Error: Element symbol not found")? (<string>, line 12)
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return s
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else False
Output:
Success
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energy
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idx
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
top = traj.topology
idx = top.select('name CA')
idx = idx[:2]
print(idx)
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
top = traj.topology
idx = top.select('name CA')[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select('name CA')[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = []
for i in range(2):
idx.append(np.where(traj.top.atom_name == 'CA')[0][i])
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Topology' object has no attribute 'atom_name'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
atom_indices = topology.select('name CA')
idx = atom_indices[0:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return k
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/2.0)*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/2.0)*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
fourier_1d
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return w
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
w[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaT
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf * m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf * m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generators
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'https://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum={}'.format(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table')
table_rows = table.find_all('tr')
generators = []
for tr in table_rows:
td = tr.find_all('td')
row = [i.text for i in td]
if len(row) > 0:
generators.append(np.array([[float(i) for i in row[0:3]],
[float(i) for i in row[3:6]],
[float(i) for i in row[6:9]]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_gen?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = np.array(generators)
generators = generators[1:,1:]
generators = np.array([np.array(g) for g in generators])
generators = np.array([np.array(g, dtype=float) for g in generators])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum='+str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr'):
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([float(ele) for ele in cols])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-genmat?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr')[1:]:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append(np.array([[float(cols[0]), float(cols[1]), float(cols[2])],
[float(cols[3]), float(cols[4]), float(cols[5])],
[float(cols[6]), float(cols[7]), float(cols[8])]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (4.184e3) * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return resids
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.top.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = np.unique(traj.topology.select('name CA'))
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Residue' object has no attribute 'is_hydrophobic'
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return P
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08206 # atm L / mol K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 # atm L / mol K
P = (n * R * T) / V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm*L/(mol*K)
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08206 # atm L / mol K
P = n*R*T/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08206 # L atm / mol K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a*(b**2)/2 + b*c + c*d + d**2/2
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) - (b*c/3)*(b**3) + (c**2/2)*(b**2) - d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a*(b**2)/2 + b*c + c*d + d**2/2
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
trap
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integral
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
x = np.linspace(a, b, n + 1)
integral = h * (0.5 * f(x[0]) + 0.5 * f(x[-1]) + np.sum(f(x[1:-1])))
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
integral = 0.5 * h * (f(a) + f(b))
for i in range(1, n):
integral += h * f(a + i * h)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
x = np.linspace(a, b, n + 1)
integral = 0.5 * h * (f(x[0]) + f(x[n]))
for i in range(1, n):
integral += h * f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
x = np.linspace(a, b, n+1)
h = (b - a) / n
integral = 0.5 * h * (f(x[0]) + f(x[-1]))
for i in range(1, n):
integral += h * f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
integral = 0.5*h*(f(x[0]) + f(x[n]))
for i in range(1, n):
integral += h*f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
invert_matrix
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainv
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILES
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
m = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(m)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(IUPAC)
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
karplusant
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
[insert]
return J
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = (A*np.cos(phi)**2 + B*np.sin(phi)**2 + C*np.sin(phi)*np.cos(phi))/2
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = (3/2) * A * (np.cos(phi)**2 - 1/3) + (1/2) * B * (np.sin(phi)**2 - 1/3) + C * np.sin(phi) * np.cos(phi)
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = np.cos(phi) * A + np.sin(phi) * B + C
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = (A*np.cos(phi)**2 + B*np.sin(phi)**2 + C*np.sin(phi)*np.cos(phi))/2
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = np.dot(A, np.dot(np.cos(phi), B)) + np.dot(A, np.dot(np.sin(phi), C))
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
kld
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return loss
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(true_data * np.log(true_data / predicted_data))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
langevin_dynamics
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_traj
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T/m)*np.random.normal()*np.sqrt(dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - dt*F(x_traj[i])/m - gamma*v_traj[i]*dt + np.sqrt(2*gamma*T*dt)*np.random.normal())/(1+gamma*dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] + (-gamma*v_traj[i] + F(x_traj[i]) - np.sqrt(2*gamma*T)*np.random.normal())/m*dt
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2/m
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i])/m + F(x_traj[i+1])/m)*dt - gamma*v_traj[i]*dt + np.sqrt(2*gamma*T*dt)*np.random.normal()
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - F(x_traj[i])/m*dt - gamma/m*v_traj[i]*dt + np.sqrt(2*gamma*T/m)*np.sqrt(dt)*np.random.normal())/(1+gamma*dt/m)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
weighted-least-squares
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return beta
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T*w*x).I*x.T*w*y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = np.linalg.inv(x.T*w*x)*x.T*w*y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return result
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if Descriptors.NumHDonors(mol) > 5:
result = False
if Descriptors.NumHAcceptors(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if Descriptors.NumHDonors(mol) > 5:
result = False
if Descriptors.NumHAcceptors(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
result = True
if hbd > 5:
result = False
if hba > 10:
result = False
if mw > 500:
result = False
if logp > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
result = True
if hbd > 5:
result = False
if hba > 10:
result = False
if mw > 500:
result = False
if logp > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return e
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y_hat)):
e += abs(y_hat[i]-y[i])/y[i]
e = e/len(y_hat)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y_hat)):
e += abs(y_hat[i]-y[i])/y[i]
e /= len(y_hat)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs((y_hat[i]-y[i])/y[i])
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y_hat)):
e += abs(y_hat[i] - y[i]) / y[i]
e /= len(y_hat)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
n = len(y)
for i in range(n):
e += abs(y_hat[i]-y[i])/y[i]
e = e/n
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return M
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, len(beads_mappings)))
for i, beads in enumerate(beads_mappings):
M[beads.indices, i] = 1.0
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, bead in enumerate(beads_mappings):
M[i, bead.indices] = bead.masses / bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, len(beads_mappings)))
for i, beads in enumerate(beads_mappings):
M[beads.indices, i] = 1.0
M = M / np.sum(M, axis=0)
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, len(beads_mappings)))
for i, beads_mapping in enumerate(beads_mappings):
M[beads_mapping.indices, i] = beads_mapping.masses / beads_mapping.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, bead in enumerate(beads_mappings):
M[i, bead.indices] = bead.masses/bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'masses'
matpow
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return r
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.identity(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = r.dot(x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
matrix_factorial
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return f
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.ones(n.shape)
for i in range(1,n.shape[0]):
for j in range(1,n.shape[1]):
f[i,j] = f[i,j-1]*n[i,j]
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros((n.shape[0],n.shape[1]))
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return s
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = 0
for atom in mol.GetAtoms():
charge += atom.GetFormalCharge()
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = 0
for atom in mol.GetAtoms():
charge += atom.GetFormalCharge()
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = 0
for atom in mol.GetAtoms():
charge += atom.GetFormalCharge()
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'K' or i == 'R':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == "R" or i == "K":
charge += 1
elif i == "D" or i == "E":
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == "R" or i == "K":
charge += 1
elif i == "D" or i == "E":
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
solve_ode
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return sol
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h*k1/4)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h*k1/32 + 9*h*k2/32)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h*k1/2197 - 7200*h*k2/2197 + 7296*h*k3/2197)
k5 = fn(t[i] + h, y[i] + 439*h*k1/216 - 8*h*k2 + 3680*h*k3/513 - 845*h*k4/4104)
k6 = fn(t[i] + h/2, y[i] - 8*h*k1/27 + 2*h*k2 - 3544*h*k3/2565 + 1859*h*k4/4104 - 11*h*k5/40)
y[i+1] = y[i] + h*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
sol = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
sol = y[:,0]
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h*k1/4)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h*k1/32 + 9*h*k2/32)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h*k1/2197 - 7200*h*k2/2197 + 7296*h*k3/2197)
k5 = fn(t[i] + h, y[i] + 439*h*k1/216 - 8*h*k2 + 3680*h*k3/513 - 845*h*k4/4104)
k6 = fn(t[i] + h/2, y[i] - 8*h*k1/27 + 2*h*k2 - 3544*h*k3/2565 + 1859*h*k4/4104 - 11*h*k5/40)
y[i+1] = y[i] + h*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
sol = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = fn(t[i], sol[i])
k2 = fn(t[i] + h/4, sol[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, sol[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, sol[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, sol[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, sol[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
sol[i+1] = sol[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = fn(t[i], sol[i])
k2 = fn(t[i] + h/4, sol[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, sol[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, sol[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, sol[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, sol[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
sol[i+1] = sol[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return v
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(a)))
for i in range(len(a)):
v[i, i] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
operands could not be broadcast together with shapes (10,10) (10,5)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(a)))
for i in range(len(a)):
v[i, i] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
operands could not be broadcast together with shapes (10,10) (10,5)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, x in enumerate(a):
v[i, x] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(a)))
for i in range(len(a)):
v[i, i] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
operands could not be broadcast together with shapes (10,10) (10,5)
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return p
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distances
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = np.unique(distances)
distances = distances[1:]
distances = distances.tolist()
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.tril(distances)
distances = distances[distances != 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = np.unique(distances)
distances = distances[1:]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.triu(distances)
distances = distances[np.nonzero(distances)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.tril(distances)
distances = distances[distances != 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
pauli_matrices
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
[insert]
return sigma_x, sigma_y, sigma_z
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0, 1], [1, 0]])
sigma_y = np.array([[0, -1j], [1j, 0]])
sigma_z = np.array([[1, 0], [0, -1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0, 1], [1, 0]])
sigma_y = np.array([[0, -1j], [1j, 0]])
sigma_z = np.array([[1, 0], [0, -1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0, 1], [1, 0]])
sigma_y = np.array([[0, -1j], [1j, 0]])
sigma_z = np.array([[1, 0], [0, -1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0, 1], [1, 0]])
sigma_y = np.array([[0, -1j], [1j, 0]])
sigma_z = np.array([[1, 0], [0, -1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0, 1], [1, 0]])
sigma_y = np.array([[0, -1j], [1j, 0]])
sigma_z = np.array([[1, 0], [0, -1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
pi
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_est
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4.0*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4.0*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.rand(nsamples)
y = np.random.rand(nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(-1,1,nsamples)
y = np.random.uniform(-1,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return e
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return n
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 1
while np.prod(1 - p * (1 - p) ** np.arange(n)) > pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return mols
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
mols = set()
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/'
params = {'smiles': smiles, 'threshold': 0.8, 'sids': 'all', 'format': 'json'}
r = requests.get(url, params=params)
if r.status_code != 200:
print(r.status_code)
print(r.text)
return mols
for result in r.json()['PC_Compounds']:
for cid in result['cids']:
mols.add(result['props']['CanonicalSMILES'][cid])
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
response = requests.get(url)
cids = response.text.split()
mols = set()
for cid in cids:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cid
response = requests.get(url)
mols.add(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/'
url += smiles
url += '/cids/TXT?Threshold=80'
r = requests.get(url)
cids = r.text.split()
mols = set()
for cid in cids:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/'
url += cid
url += '/property/CanonicalSMILES/TXT'
r = requests.get(url)
mols.add(r.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
('Connection aborted.', TimeoutError('Timeout'))
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# Get the CID for the input SMILES
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles)
cid = r.text.split()[0]
# Get the CIDs of similar molecules
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/similarity/XML' % cid)
cids = [int(x.text) for x in r.xml.findAll('CID')]
# Get the SMILES for the similar molecules
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % ','.join(map(str, cids)))
mols = r.text.split()
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
'Response' object has no attribute 'xml'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
cid = requests.get("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{}/cids/TXT".format(smiles)).text
cid = cid.split("\n")[0]
mols = requests.get("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/similarity/XML?Threshold=80".format(cid)).text
mols = mols.split("\n")
mols = [m for m in mols if "CID" in m]
mols = [m.split("<CID>")[1].split("</CID>")[0] for m in mols]
mols = [requests.get("https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(m)).text for m in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.scf()
ground_energy = mf.e_tot
return ground_energy
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print("Ground state energy of {} in {} basis: {}".format(atom,basis,ground_energy))
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print(ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
return ground_energy
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return result
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
qed_score = Crippen.MolLogP(mol) + Descriptors.MolWt(mol)
return qed_score
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
quantile
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return result
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
result = np.percentile(a, q * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.sort(a)
n = len(a)
result = []
for qq in q:
idx = (n - 1) * qq
if idx % 1 == 0:
result.append(a[int(idx)])
else:
result.append((a[int(idx)] + a[int(idx) + 1]) / 2)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
Success
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
result = np.empty(len(q))
for i, qi in enumerate(q):
result[i] = np.percentile(a, qi * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
Success
random_walk
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return traj
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*(2*np.random.randint(0,2)-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*(np.random.randint(2)*2-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0 + a*np.random.choice([-1,1])
x0 = traj[i]
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Timeout
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*(np.random.randint(2)*2-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
traj[0] = x0
for i in range(1,N):
traj[i] = traj[i-1] + a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Timeout
rank
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return r
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
u, s, vh = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_traj
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select("not water"))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
water = top.select('water')
new_traj = traj.atom_slice(np.setdiff1d(np.arange(top.n_atoms),water))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m*1.660539040e-27 # mass in kg
v_rms = math.sqrt(3*k*T/m)
v_rms = v_rms*1e-3 # in km/s
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant
m = m*1.66054e-24 # mass in g
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m*1.66054e-24 # mass in g
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant
m = m*1.6605e-27 # mass in kg
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23
m = m*1.66054e-24
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
rmse
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return e
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rg
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
rotationant
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
[insert]
return E_rot
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J*(J+1)
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J*(J+1)
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J*(J+1)
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J*(J+1)
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J*(J+1)
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
rotation_higherant
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
[insert]
return E_rot
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)/(2*B)
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*(J+1) - D*J*(J+1)*(J*(J+1))
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*(J+1) - D*J*(J+1)*(J*(J+1))
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)/(2*B)
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.mean(sasa, axis=0)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.mean(sasa, axis=0)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.mean(sasa, axis=0)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.mean(sasa, axis=0)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
axis 1 is out of bounds for array of dimension 1
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return aligned
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seq
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
sequence
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return x
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s), np.log10(e), l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return x
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradius
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.max(np.abs(np.linalg.eigvals(a)))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eig_val = np.linalg.eigvals(a)
sradius = np.max(np.abs(eig_val))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigvals))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigval = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigval))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigval = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigval))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbers
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
max_index = np.argmax(abs_spectrum[:,1])
wavenumbers.append(abs_spectrum[max_index, 0])
abs_spectrum[max_index, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
wavenumbers = abs_spectrum[peaks, 0]
if len(wavenumbers) > npeaks:
wavenumbers = wavenumbers[:npeaks]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])][-npeaks:]
wavenumbers = abs_spectrum[peaks, 0]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0, distance=50)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
wavenumbers = abs_spectrum[peaks, 0][:npeaks]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
max_index = np.argmax(abs_spectrum[:,1])
wavenumbers.append(abs_spectrum[max_index, 0])
abs_spectrum[max_index, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
print "Speed of sound is %.2f m/s" % s
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Missing parentheses in call to 'print'. Did you mean print("Speed of sound is %.2f m/s" % s)? (<string>, line 12)
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idx
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i, mol in enumerate(mol_list):
if mol.HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return s
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(s) for s in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(s) for s in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.FingerprintSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(s) for s in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
s = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
s[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return result
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_res = traj.topology.select('resname '+lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
result = np.linalg.norm(lig_com-prot_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
protein_ind = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
protein_com = md.compute_center_of_mass(traj.atom_slice(protein_ind))
result = []
for i in range(len(traj)):
result.append(np.linalg.norm(lig_com[i]-protein_com[i]))
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_sel = traj.topology.select('resname ' + lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_sel))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
result = np.linalg.norm(lig_com - prot_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_sel = traj.top.select('resname '+lig_str)
protein_sel = traj.top.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_sel))
protein_com = md.compute_center_of_mass(traj.atom_slice(protein_sel))
result = np.sqrt(np.sum((lig_com-protein_com)**2,axis=1))
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_com = md.compute_center_of_mass(traj.atom_slice(traj.top.select(lig_str)))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.top.select("protein")))
result = np.linalg.norm(lig_com - prot_com, axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
velocity_verlet_integration
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
[insert]
return x_traj, v_traj
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v_traj[i+1] = v_traj[i] + 0.5*dt*F(x_traj[i])
x_traj[i+1] = x_traj[i] + dt*v_traj[i+1]
v_traj[i+1] = v_traj[i+1] + 0.5*dt*F(x_traj[i+1])
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
---|---|---|---|---|---|
aa_polarity | Pass | Pass | Fail | Pass | Pass |
adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
alignment | Pass | Fail | Fail | Pass | Fail |
angle | Pass | Pass | Pass | Pass | Pass |
aromatic_aa | Pass | Pass | Pass | Pass | Pass |
arrhenius | Fail | Pass | Fail | Pass | Fail |
bimolecular | Pass | Pass | Pass | Pass | Pass |
bb_rad | Pass | Pass | Pass | Pass | Pass |
blast | Fail | Fail | Fail | Fail | Fail |
braggant | Pass | Pass | Pass | Pass | Pass |
bravais | Fail | Pass | Pass | Fail | Fail |
canonicalize | Pass | Pass | Pass | Pass | Pass |
carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
claussius | Pass | Fail | Pass | Pass | Pass |
compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
condiff_1d | Pass | Pass | Pass | Pass | Pass |
cubes | Fail | Fail | Pass | Fail | Fail |
de_broglie | Pass | Pass | Pass | Pass | Pass |
derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
derivative_2deg | Pass | Pass | Pass | Pass | Pass |
descriptors | Fail | Fail | Fail | Fail | Fail |
dipole | Fail | Fail | Pass | Pass | Pass |
dou | Fail | Fail | Fail | Fail | Fail |
eigen-ch | Pass | Pass | Pass | Pass | Pass |
eigen | Pass | Pass | Pass | Pass | Pass |
element_mass | Pass | Pass | Pass | Pass | Pass |
element_name | Pass | Pass | Pass | Pass | Pass |
energy_of_e | Fail | Pass | Pass | Pass | Pass |
find_indices | Fail | Fail | Fail | Pass | Fail |
force_constant | Fail | Fail | Fail | Fail | Fail |
fourier_1d | Pass | Fail | Pass | Fail | Pass |
freezing_depression | Pass | Pass | Pass | Pass | Pass |
genpos | Fail | Fail | Fail | Fail | Fail |
heating_water | Fail | Fail | Fail | Fail | Fail |
hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
ideal_gas | Pass | Pass | Pass | Pass | Pass |
integral | Fail | Fail | Fail | Fail | Fail |
trap | Pass | Pass | Pass | Pass | Pass |
invert_matrix | Fail | Pass | Pass | Pass | Fail |
iupac2smiles | Fail | Fail | Fail | Fail | Fail |
karplusant | Pass | Pass | Fail | Pass | Fail |
kld | Fail | Fail | Fail | Fail | Fail |
langevin_dynamics | Pass | Fail | Fail | Fail | Fail |
weighted-least-squares | Fail | Fail | Fail | Pass | Fail |
lipinski_rule_of_five | Pass | Pass | Pass | Pass | Pass |
mape | Fail | Pass | Fail | Fail | Fail |
mapping_operator | Fail | Fail | Fail | Fail | Fail |
matpow | Pass | Pass | Fail | Pass | Pass |
matrix_factorial | Fail | Fail | Fail | Fail | Fail |
max-boltz | Fail | Fail | Fail | Fail | Pass |
michaelis | Pass | Pass | Pass | Pass | Pass |
mol_charge | Fail | Pass | Pass | Fail | Pass |
net_charge | Pass | Pass | Pass | Pass | Pass |
solve_ode | Fail | Fail | Fail | Fail | Fail |
ohe | Fail | Fail | Fail | Fail | Fail |
osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
pair_wise | Fail | Fail | Fail | Fail | Fail |
pauli_matrices | Pass | Pass | Pass | Pass | Pass |
pi | Pass | Pass | Pass | Pass | Pass |
pib_1d | Pass | Pass | Pass | Pass | Pass |
pred_interval | Pass | Pass | Pass | Pass | Pass |
pubchem | Fail | Fail | Fail | Fail | Fail |
pyscf_energy | Fail | Fail | Fail | Fail | Fail |
qed | Pass | Pass | Pass | Fail | Fail |
quantile | Fail | Fail | Fail | Fail | Fail |
random_walk | Pass | Fail | Pass | Pass | Pass |
rank | Pass | Pass | Pass | Pass | Pass |
remove-water | Fail | Fail | Pass | Pass | Pass |
rms_velocity | Fail | Fail | Fail | Fail | Fail |
rmse | Pass | Pass | Pass | Pass | Pass |
rog | Pass | Pass | Pass | Pass | Pass |
rotationant | Pass | Pass | Pass | Pass | Pass |
rotation_higherant | Fail | Fail | Fail | Fail | Fail |
sasa | Pass | Fail | Fail | Pass | Fail |
scaffold | Fail | Fail | Fail | Fail | Fail |
seq-align | Fail | Fail | Pass | Pass | Pass |
seq-trans | Pass | Pass | Pass | Pass | Pass |
sequence | Pass | Pass | Pass | Pass | Fail |
sle | Fail | Fail | Fail | Fail | Fail |
spectral_r | Pass | Fail | Fail | Pass | Pass |
find_peaks | Fail | Fail | Fail | Fail | Fail |
speed_of_sound | Fail | Fail | Fail | Fail | Fail |
substructure | Fail | Fail | Fail | Fail | Fail |
tanimoto | Pass | Pass | Fail | Pass | Pass |
unbdistance | Fail | Fail | Fail | Fail | Fail |
velocity_verlet_integration | Pass | Pass | Pass | Pass | Pass |
aa_polarity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['S', 'T', 'N', 'Q']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['Q', 'N', 'S', 'T', 'Y', 'C']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ["G", "A", "S", "T", "C", "V", "I", "L", "M", "F", "Y", "W"]:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['S', 'T', 'N', 'Q', 'Y', 'C']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['S', 'T', 'N', 'Q']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
adiabatic_expansion
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
alignment
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# get the reference frame
reference_frame = traj.slice(frame_index)
# align the trajectory to the reference frame
aligned_traj = traj.superpose(reference_frame)
# return the aligned trajectory
return aligned_traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# get the frame
frame = traj.slice(frame_index)
# align to the frame
traj.superpose(frame)
# return the aligned trajectory
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to a specific frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
'NoneType' object has no attribute 'xyz'
angle
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
cos_angle = np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
angle = np.arccos(cos_angle)
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
cos_theta = np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
theta = np.arccos(cos_theta)
return theta
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
return np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1 = np.array(v1)
v2 = np.array(v2)
return np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
aromatic_aa
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for residue in sequence:
if residue in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa_list = ['F', 'Y', 'W']
aromatic_aa_count = 0
for aa in sequence:
if aa in aromatic_aa_list:
aromatic_aa_count += 1
return aromatic_aa_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for residue in sequence:
if residue in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_aa:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for residue in sequence:
if residue in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea/R)*(1/T2 - 1/T1))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea/R)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((-Ea/8.314)*(1/T1-1/T2))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
return k2 * math.exp((Ea/R) * (1/T1 - 1/T2))
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34 # Planck's constant in SI unit
c = 299792458 # speed of light in SI unit
k = 1.38064852e-23 # Boltzmann constant in SI unit
return 2*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1))
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
return (2*h*c**2/lam**5)*(1/(np.exp(h*c/(lam*k*T))-1))
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = "https://blast.ncbi.nlm.nih.gov/Blast.cgi"
params = {
'QUERY': seq,
'DATABASE': 'nr',
'PROGRAM': 'blastp',
'CMD': 'Put',
'HITLIST_SIZE': '1',
'FILTER': 'L',
'EXPECT': '1e-10',
'FORMAT_TYPE': 'HTML'
}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
#print(soup.prettify())
# 4. Parse MSA
msa = soup.find('pre').text
#print(msa)
# 5. Return a tuple of e score, id of top match
e_score = soup.find('td', attrs={'class': 'blast_hspscore'}).text
e_score = float(e_score.split('=')[1].strip())
#print(e_score)
top_match = soup.find('td', attrs={'class': 'blast_
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
EOL while scanning string literal (<string>, line 55)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
blast_url = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi'
blast_params = {'QUERY': seq,
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'FILTER': 'L',
'EXPECT': '1e-10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'ALIGNMENT_VIEW': 'Tabular',
'DESCRIPTIONS': '1',
'FORMAT_OBJECT': 'Alignment',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'CMD': 'Put'}
r = requests.post(blast_url, data=blast_params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
msa = soup.find_all('pre')[0].text
msa = msa.split('\n')
msa = [x for x in msa if x != '']
msa = [x for x in msa if x[0] != '#']
# 5. Return a tuple of e score, id of top match
return msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://www.uniprot.org/blast/?about=1'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'}
data = {'query': seq, 'database': 'uniprotkb', 'format': 'html'}
r = requests.post(url, data=data, headers=headers)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre', {'class': 'result'})
# 4. Parse MSA
if result is None:
return None, None
else:
result = result.text.split('\n')
# 4.1. Get e-value
e_value = result[0].split(' ')[-1]
# 4.2. Get top match
top_match = result[1].split(' ')[-1]
return e_value, top_match
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
float() argument must be a string or a number, not 'NoneType'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://www.uniprot.org/blast/'
params = {'query': seq}
r = requests.get(url, params=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre')
# 4. Parse MSA
msa = result.text.split('\n')
msa = [i for i in msa if i]
# 5. Return a tuple of e score, id of top match
return (msa[1].split()[-1], msa[2].split()[0])
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
# 2. Submit BLAST search with sequences
url = 'http://www.uniprot.org/blast/'
params = {'query': seq, 'database': 'swissprot', 'format': 'html'}
r = requests.get(url, params=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
msa = soup.find_all('pre')[0].text
# 5. Return a tuple of e score, id of top match
return msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
list index out of range
braggant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
return np.arcsin(wavelength/(2*d))
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
return np.arcsin(wavelength / (2 * d))
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
return np.arcsin(wavelength/(2*d))
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
return np.arcsin(wavelength/(2*d))
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
return np.arcsin(wavelength / (2 * d))
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
bravais
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in range(1, 3):
return "triclinic"
elif group_number in range(3, 16):
return "monoclinic"
elif group_number in range(16, 75):
return "orthorhombic"
elif group_number in range(75, 143):
return "tetragonal"
elif group_number in range(143, 168):
return "trigonal"
elif group_number in range(168, 195):
return "hexagonal"
elif group_number in range(195, 231):
return "cubic"
else:
return "unknown"
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 3:
return "triclinic"
elif group_number < 16:
return "monoclinic"
elif group_number < 75:
return "orthorhombic"
elif group_number < 143:
return "tetragonal"
elif group_number < 168:
return "trigonal"
elif group_number < 195:
return "hexagonal"
else:
return "cubic"
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
invalid syntax (<string>, line 17)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
return [Chem.MolToSmiles(Chem.MolFromSmiles(smiles)) for smiles in smiles_list]
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
can_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return can_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
carnot_efficiency
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
claussius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
R = 8.314 #J/mol/K
return P1 * math.exp((HVap * 1000) / (R * T1) * (1 - (T2 / T1)))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * ((1 / T1) - (1 / T2)))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
compare_electronegativity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
# start
if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
return True
else:
return False
result = True if compare_electronegativity("O","C") else False
Output:
'>' not supported between instances of 'method' and 'method'
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if mendeleev.element(element1).pauling_electronegativity > mendeleev.element(element2).pauling_electronegativity:
return True
else:
return False
result = True if compare_electronegativity("O","C") else False
Output:
'Element' object has no attribute 'pauling_electronegativity'
condiff_1d
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
cubes
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i * i * i
return sum
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += (i + 1) ** 3
return sum
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
de_broglie
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
c = 299792458.0
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 2.99792458e8
return h / (m * v * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
c = 299792458
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 3.0e+8
return h / (m * v * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
"""
Create matrix of zeros
"""
a = np.zeros((5,10))
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
# start
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
"""
Create a matrix of zeros
"""
a = np.zeros((5,10))
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
derivative_2deg
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descrs = calc.CalcDescriptors(mol)
descriptors.append(descrs)
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(calc.CalcDescriptors(mol))
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descrs = calc.CalcDescriptors(mol)
descriptors.append(descrs)
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
# initialize the descriptor calculator
calc = MoleculeDescriptors.MolecularDescriptorCalculator([
'MolWt',
'MolLogP',
'TPSA',
'LabuteASA',
'BalabanJ',
'BertzCT',
'Chi0',
'Chi0n',
'Chi0v',
'Chi1',
'Chi1n',
'Chi1v',
'Chi2n',
'Chi2v',
'Chi3n',
'Chi3v',
'Chi4n',
'Chi4v',
'HallKierAlpha',
'Kappa1',
'Kappa2',
'Kappa3',
'Chi1v',
'Chi2n',
'Chi2v',
'Chi3n',
'Chi3v',
'Chi4n',
'Chi4v',
'HallKierAlpha',
'Kappa1',
'Kappa2',
'Kappa3',
'LabuteASA',
'PEOE_VSA1',
'PEOE_VSA10',
'PEOE_VSA11',
'PEOE_VSA12',
'PEOE_VSA13',
'PEOE_VSA14',
'PEOE_VSA2',
'PEOE_VSA3',
'PEOE_VSA4',
'PEOE_VSA5',
'PEOE_VSA6',
'PEOE_VSA7',
'PEOE_VSA8',
'PEOE_VSA9',
'SMR_VSA1',
'SMR_VSA10',
'SMR_VSA2',
'SMR_VSA3',
'SMR_VSA4',
'SMR_VSA5',
'SMR_VSA6',
'SMR_VSA7',
'SMR_VSA8',
'SMR_VSA9',
'SlogP_VSA1',
'SlogP_VSA10',
'SlogP_VSA11',
'SlogP_VSA12',
'SlogP_VSA2',
'SlogP_VSA3',
'SlogP_VSA4',
'SlogP_VSA5',
'SlogP_VSA6',
'SlogP_VSA7',
'SlogP_VSA8',
'SlogP_VSA9',
'EState_VSA1',
'EState_VSA10',
'EState_VSA11',
'EState_VSA12',
'EState_VSA2',
'EState_VSA3',
'EState_VSA4',
'EState_VSA5',
'EState_VSA6',
'EState_VSA7',
'EState_VSA8',
'EState_VSA9',
'VSA_EState1',
'VSA_EState10',
'VSA_EState2',
'VSA_EState3',
'VSA_EState4',
'VSA_EState5',
'VSA_EState6',
'VSA_EState7',
'VSA_EState8',
'VSA_EState9',
'
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
EOL while scanning string literal (<string>, line 120)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(calc.CalcDescriptors(mol))
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
dipole
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# start
dipole_moment = np.sum(coordinates * charges[:, np.newaxis], axis=0)
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
unsupported operand type(s) for -: 'float' and 'NoneType'
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# Calculate the center of mass
center_of_mass = np.average(coordinates, axis=0, weights=charges)
# Calculate the dipole moment
dipole_moment = np.sum(np.multiply(charges.reshape(-1,1), coordinates - center_of_mass), axis=0)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Weights sum to zero, can't be normalized
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i] * coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# YOUR CODE HERE
dipole_moment = np.zeros(3)
for i in range(len(coordinates)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
C = mol.GetNumAtoms(6)
N = mol.GetNumAtoms(7)
H = mol.GetNumAtoms(1)
halogen = mol.GetNumAtoms(9) + mol.GetNumAtoms(17) + mol.GetNumAtoms(35) + mol.GetNumAtoms(53)
rdbs = (2*N + 2 - H + halogen) / 2
return rdbs
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return rdMolDescriptors.CalcNumRotatableBonds(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
#print(smiles)
#print(mol)
#print(Chem.MolToMolBlock(mol))
#print(Chem.MolToSmiles(mol))
#print(Chem.MolToSmarts(mol))
#print(Chem.MolToInchi(mol))
#print(Chem.MolToInchiKey(mol))
#print(Chem.MolToPDBBlock(mol))
#print(Chem.MolToPDBFile(mol))
#print(Chem.MolToMolBlock(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
expected an indented block (<string>, line 84)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
rdbs = Descriptors.NumRadicalElectrons(mol)
return rdbs
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
Success
eigen-ch
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
eig_vals, eig_vecs = np.linalg.eig(M)
return eig_vals, eig_vecs
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
eigen_values, eigen_vectors = np.linalg.eig(M)
return eigen_values, eigen_vectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# begin
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
eigen
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigvals, eigvecs = np.linalg.eig(M)
return eigvals, eigvecs
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
element_mass
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
return mendeleev.element(element_symbol).mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
Success
element_name
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else False
Output:
Success
energy_of_e
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
energy = -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
must be real number, not NoneType
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
R = 13.6 # eV
return -R / n**2
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6*(1/n**2)
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
R = 13.6
return -R / n**2
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load_pdb(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load_pdb(pdb_file)
ca_indices = []
for i in range(pdb.n_atoms):
if pdb.topology.atom(i).name == 'CA':
ca_indices.append(i)
return ca_indices[0:2]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
t = md.load(pdb_file)
topology = t.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
return (1.0/wave_len)*(1.0/(m1*m2/(m1+m2)))
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# Your code here
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
k = (wave_len*100)**2*mu
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
return (m1*m2)/(m1+m2)*(wave_len*(1.0/8065.54429))**2
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
return mu*(wave_len*(1.0/100.0)*(1.0/2.99792458e10)**2)
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
fourier_1d
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
return np.fft.fft(x)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = x.shape[0]
n = np.arange(N)
k = n.reshape((N, 1))
M = np.exp(-2j * np.pi * k * n / N)
return np.dot(M, x)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = len(x)
X = np.zeros(N)
for k in range(N):
for n in range(N):
X[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
Success
freezing_depression
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf*m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[1]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_gen?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum={}".format(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find_all('table')[1]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-genmatr?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=%d" % gnum
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[1]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
heating_water
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
hydrophobic_res
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
hydrophobic_residues = []
with open(pdb_filename) as f:
for line in f:
if line.startswith('ATOM'):
residue_name = line[17:20]
if residue_name in ['ALA', 'ILE', 'LEU', 'VAL', 'PHE', 'TRP', 'TYR', 'MET']:
residue_index = int(line[22:26])
if residue_index not in hydrophobic_residues:
hydrophobic_residues.append(residue_index)
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb.topology.residues:
if residue.is_water:
continue
if residue.name in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TRP', 'MET', 'PRO']:
hydrophobic_residues.append(residue.index)
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
hydrophobic_residues = []
with open(pdb_filename, 'r') as pdb_file:
for line in pdb_file:
if line.startswith('ATOM'):
residue_name = line[17:20].strip()
if residue_name in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TRP', 'MET', 'PRO']:
residue_index = int(line[22:26].strip())
if residue_index not in hydrophobic_residues:
hydrophobic_residues.append(residue_index)
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# load pdb file
traj = md.load(pdb_filename)
# get residue names
res_names = traj.topology.residue_names
# get residue indices
res_indices = traj.topology.residue_indices
# get hydrophobic residues
hydrophobic_residues = []
for i in range(len(res_names)):
if res_names[i] in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TYR', 'TRP', 'MET', 'PRO']:
hydrophobic_residues.append(res_indices[i])
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Topology' object has no attribute 'residue_names'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb.topology.residues:
if residue.is_water:
continue
if residue.name in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TRP', 'MET', 'PRO']:
hydrophobic_residues.append(residue.index)
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
Success
ideal_gas
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
integral
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a/4*d**4 + b/3*d**3 + c/2*d**2 + d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return (a/4)*d**4 + (b/3)*d**3 + (c/2)*d**2 + d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a/4*(d**4-b**4)+b/3*(d**3-b**3)+c/2*(d**2-b**2)+d*(d-b)
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
trap
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a)/n
s = 0.5*(f(a) + f(b))
for i in range(1, n):
s += f(a + i*h)
return h*s
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
x = np.linspace(a, b, n+1)
y = f(x)
return h * (0.5 * y[0] + 0.5 * y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
s = 0.5 * f(a) + 0.5 * f(b)
for i in range(1, n):
s += f(a + i * h)
return s * h
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
s = 0.5*(f(a)+f(b))
for i in range(1,n):
s += f(a+i*h)
return h*s
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
s = 0.5 * f(a) + 0.5 * f(b)
for i in range(1, n):
s += f(a + i * h)
return s * h
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
invert_matrix
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# Compute the inverse of A
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
A_inv = np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
karplusant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
return A + B*np.cos(phi) + C*np.cos(2*phi)
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
return A + B * np.cos(phi) + C * np.cos(2*phi)
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
return A * np.cos(phi) + B * np.cos(2 * phi) + C * np.cos(3 * phi)
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
return A + B*np.cos(phi) + C*np.cos(2*phi)
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
return A + B * np.cos(phi) + C * np.cos(phi)**2
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
kld
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
# TODO: Calculate the KL divergence loss between true_data and predicted_data
# Hint: Use the function log() from the numpy library
kl_loss = None
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
kl_divergence = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
langevin_dynamics
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + F(x_traj[i])*dt/m + np.sqrt(2*gamma*T/m)*np.random.normal(0,1)*np.sqrt(dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*v_traj[i-1]
v_traj[i] = v_traj[i-1] + dt*(-gamma*v_traj[i-1] - F(x_traj[i-1]) + np.sqrt(2*gamma*T/m)*np.random.normal())
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + dt*v_traj[i]
v_traj[i+1] = v_traj[i] + dt*(F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T/m)*np.random.normal())
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
Success
weighted-least-squares
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# start
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# start
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
return (x.T * w * x).I * x.T * w * y
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# Compute weighted least squares
# start
x_t = x.T
x_t_w = x_t * w
x_t_w_x = x_t_w.dot(x)
x_t_w_x_inv = np.linalg.inv(x_t_w_x)
x_t_w_x_inv_x_t_w = x_t_w_x_inv.dot(x_t_w)
coeffs = x_t_w_x_inv_x_t_w.dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.lstsq(x*w, y*w)[0]
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
operands could not be broadcast together with shapes (100,3) (100,)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
if rdMolDescriptors.CalcNumHBD(mol) > 5:
return False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
return False
if Descriptors.MolWt(mol) > 500:
return False
if Crippen.MolLogP(mol) > 5:
return False
return True
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m == None:
return False
else:
num_hbd = rdMolDescriptors.CalcNumHBD(m)
num_hba = rdMolDescriptors.CalcNumHBA(m)
mol_weight = Descriptors.MolWt(m)
logP = Crippen.MolLogP(m)
if num_hbd <= 5 and num_hba <= 10 and mol_weight < 500 and logP < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
if rdMolDescriptors.CalcNumHBD(m) > 5:
return False
if rdMolDescriptors.CalcNumHBA(m) > 10:
return False
if Descriptors.MolWt(m) > 500:
return False
if Crippen.MolLogP(m) > 5:
return False
return True
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
else:
if rdMolDescriptors.CalcNumHBD(m) <= 5 and rdMolDescriptors.CalcNumHBA(m) <= 10 and Descriptors.MolWt(m) < 500 and Crippen.MolLogP(m) < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
if rdMolDescriptors.CalcNumHBD(m) > 5:
return False
if rdMolDescriptors.CalcNumHBA(m) > 10:
return False
if Descriptors.MolWt(m) > 500:
return False
if Crippen.MolLogP(m) > 5:
return False
return True
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
Success
mape
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y_hat - y) / y)) * 100
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = 0
for i in range(len(y_hat)):
mape += abs((y_hat[i] - y[i]) / y[i])
mape /= len(y_hat)
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = 0
for i in range(len(y)):
mape += abs((y_hat[i] - y[i]) / y[i])
mape = mape / len(y)
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
Success
mapping_operator
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
#
# Get the number of beads
n_beads = len(beads_mappings)
#
# Get the number of atoms
n_atoms = len(molecule.atoms)
#
# Initialize the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
#
# Loop over the beads
for bead_index, bead_mapping in enumerate(beads_mappings):
#
# Get the bead
bead = molecule.select_atoms(bead_mapping)
#
# Get the bead mass
bead_mass = bead.masses.sum()
#
# Get the bead atoms
bead_atoms = bead.atoms
#
# Loop over the atoms
for atom_index, atom in enumerate(molecule.atoms):
#
# Check if the atom is in the bead
if atom in bead_atoms:
#
# Get the atom mass
atom_mass = atom.mass
#
# Set the mapping matrix element
mapping_matrix[bead_index, atom_index] = atom_mass / bead_mass
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Initialize the mapping matrix
mapping_matrix = np.zeros((molecule.n_atoms, len(beads_mappings)))
# Loop over the beads
for i, bead in enumerate(beads_mappings):
# Get the atoms in the bead
atoms = bead.atoms
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the number of atoms in the bead
n_atoms = len(atoms)
# Get the indices of the atoms in the bead
indices = atoms.indices
# Get the masses of the atoms
masses = atoms.masses
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'atoms'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = len(molecule.atoms)
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for i in range(n_beads):
# get the bead selection
bead_selection = beads_mappings[i]
# get the bead mass
bead_mass = molecule.atoms.select_atoms(bead_selection).masses.sum()
# get the bead atom selection
bead_atom_selection = molecule.atoms.select_atoms(bead_selection)
# get the bead atom masses
bead_atom_masses = bead_atom_selection.masses
# get the bead atom indices
bead_atom_indices = bead_atom_selection.indices
# set the mapping matrix
mapping_matrix[i, bead_atom_indices] = bead_atom_masses / bead_mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Get the number of beads
n_beads = len(beads_mappings)
# Get the number of atoms
n_atoms = molecule.n_atoms
# Initialize the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# Loop over the beads
for bead_index in range(n_beads):
# Get the bead
bead = beads_mappings[bead_index]
# Get the bead mass
bead_mass = bead.total_mass()
# Get the bead atoms
bead_atoms = bead.atoms
# Loop over the atoms
for atom in bead_atoms:
# Get the atom index
atom_index = atom.index
# Set the mapping matrix element
mapping_matrix[bead_index, atom_index] = atom.mass / bead_mass
# Return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'total_mass'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for i in range(n_beads):
# get the atoms for the bead
atoms = beads_mappings[i].indices
# get the masses for the atoms
masses = beads_mappings[i].masses
# get the total mass
total_mass = np.sum(masses)
# loop over the atoms
for j in range(len(atoms)):
# set the mapping matrix
mapping_matrix[i, atoms[j]] = masses[j] / total_mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
'list' object has no attribute 'indices'
matpow
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n%2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x.dot(x), (n-1)/2))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
else:
return np.dot(x,matpow(x,n-1))
"""
Create a matrix of ones
"""
a = np.ones((5,10))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x.dot(x), (n-1)/2))
"""
Compute matrix power
"""
b = matpow(a, 3)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x,n-1))
"""
Create matrix of ones
"""
a = np.ones((5,10))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x.dot(x), (n-1)/2))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
matrix_factorial
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n.shape == ():
return np.math.factorial(n)
else:
return np.apply_along_axis(np.math.factorial, 0, n)
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
a = np.ones((n,n))
for i in range(n):
for j in range(n):
a[i,j] = np.math.factorial(a[i,j])
return a
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.prod(np.arange(1, n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
max-boltz
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # Boltzmann's constant
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in m^2 kg s^-2 K^-1
return math.sqrt(k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in SI units
return math.sqrt(k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23 # Boltzmann constant in J/K
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
Success
michaelis
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (S + Km)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return rdMolDescriptors.CalcFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
module 'rdkit.Chem.rdMolDescriptors' has no attribute 'CalcFormalCharge'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.MolWt(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
net_charge
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == "R" or i == "K":
charge += 1
elif i == "D" or i == "E":
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
solve_ode
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize solution matrix
y = np.zeros((len(t), len(y0)))
y[0] = y0
# Loop through each time step
for i in range(len(t)-1):
# Calculate the step size
h = t[i+1] - t[i]
# Calculate the slopes
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, y[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, y[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
# Calculate the next value of y
y[i+1] = y[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
# Loop over time
for i in range(len(t)-1):
# Calculate the slopes
k1 = fn(t[i], y[i,:])
k2 = fn(t[i] + t[i+1]/4, y[i,:] + k1*t[i+1]/4)
k3 = fn(t[i] + 3*t[i+1]/8, y[i,:] + 3*k1*t[i+1]/32 + 9*k2*t[i+1]/32)
k4 = fn(t[i] + 12*t[i+1]/13, y[i,:] + 1932*k1*t[i+1]/2197 - 7200*k2*t[i+1]/2197 + 7296*k3*t[i+1]/2197)
k5 = fn(t[i] + t[i+1], y[i,:] + 439*k1*t[i+1]/216 - 8*k2*t[i+1] + 3680*k3*t[i+1]/513 - 845*k4*t[i+1]/4104)
k6 = fn(t[i] + t[i+1]/2, y[i,:] - 8*k1*t[i+1]/27 + 2*k2*t[i+1] - 3544*k3*t[i+1]/2565 + 1859*k4*t[i+1]/4104 - 11*k5*t[i+1]/40)
# Update the solution
y[i+1,:] = y[i,:] + t[i+1]*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize solution
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
# Solve
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize the output array
y = np.zeros((len(t), len(y0)))
y[0] = y0
# Loop over the elements of t
for i in range(len(t)-1):
# Compute the step size
h = t[i+1] - t[i]
# Compute the slopes
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
# Compute the next value of y
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t),len(y0)))
y[0,:] = y0
# Loop
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i],y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
# raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# TODO: Write your code here
# Hint: Use np.eye()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.reshape()
# Hint: Use np.concatenate()
# Hint: Use np.sum()
# Hint: Use np.transpose()
# Hint: Use np.argmax()
# Hint: Use np.resh
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
osmotic_pressure
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
pair_wise
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
traj.atom_slice(traj.top.select('name CA'), inplace=True)
# 3
pairs = np.array(list(itertools.combinations(range(traj.n_atoms), 2)))
# 4
return md.compute_distances(traj, pairs)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
alpha_carbons = traj.topology.select('name CA')
# Calculate the number of unique alpha carbon pairs
num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
# Calculate the distances between each alpha carbon pair
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
# Return the distances between each alpha carbon pair
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
pdb = md.load_pdb(pdb_file)
# 2
pdb_alphas = pdb.atom_slice(pdb.top.select('name CA'))
# 3
pdb_alphas_pairs = pdb_alphas.top.select_pairs('name CA', 'name CA')
# 4
return md.compute_distances(pdb_alphas, pdb_alphas_pairs)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
alpha_carbons = traj.topology.select('name CA')
# 3
alpha_carbon_pairs = list(itertools.combinations(alpha_carbons, 2))
# 4
distances = md.compute_distances(traj, alpha_carbon_pairs)
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load pdb
traj = md.load_pdb(pdb_file)
# Select only alpha carbons
traj.atom_slice(traj.top.select('name CA'), inplace=True)
# Calculate the number of unique alpha carbon pairs
n_pairs = traj.n_atoms * (traj.n_atoms - 1) / 2
# Calculate the distances between each alpha carbon pair
pairwise_distances = md.compute_distances(traj, np.triu_indices(traj.n_atoms, k=1))
# Return the distances between each alpha carbon pair
return pairwise_distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
pauli_matrices
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pauli():
"""
This function returns the three pauli matrices
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0, 1], [1, 0]])
sigma_y = np.array([[0, -1j], [1j, 0]])
sigma_z = np.array([[1, 0], [0, -1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0,1],[1,0]])
sigma_y = np.array([[0,-1j],[1j,0]])
sigma_z = np.array([[1,0],[0,-1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0,1],[1,0]])
sigma_y = np.array([[0,-1j],[1j,0]])
sigma_z = np.array([[1,0],[0,-1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0,1],[1,0]])
sigma_y = np.array([[0,-1j],[1j,0]])
sigma_z = np.array([[1,0],[0,-1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = np.array([[0,1],[1,0]])
sigma_y = np.array([[0,-1j],[1j,0]])
sigma_z = np.array([[1,0],[0,-1]])
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
pi
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
# Create a matrix of random numbers
x = np.random.rand(nsamples,2)
# Calculate the distance from the origin
r = np.sqrt(x[:,0]**2 + x[:,1]**2)
# Count the number of points inside the unit circle
count = np.sum(r<1)
# Return the value of pi
return 4*count/nsamples
print(pi(100))
print(pi(1000))
print(pi(10000))
print(pi(100000))
print(pi(1000000))
print(pi(10000000))
print(pi(100000000))
"""
Create a matrix of random numbers
"""
x = np.random.rand(100000000,2)
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
return 4*np.sum(x**2 + y**2 < 1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
"""
Create a function to calculate pi using monte carlo sampling
"""
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
pib_1d
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return n**2 * math.pi**2 * hbar**2 / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
response = requests.get(url)
cids = response.text.split()
cids = ','.join(cids)
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
response = requests.get(url)
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT?cids_type=similarity&Threshold=80' % smiles)
return set(r.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
# Send request
response = requests.get(url)
# Get response
cids = response.text.split()
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % ",".join(cids)
# Send request
response = requests.get(url)
# Get response
return response.text.split()
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
response = requests.get(url)
if response.status_code == 200:
return set(response.text.split())
else:
return set()
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# Create a dictionary of parameters to pass to the API
params = {'smiles': smiles, 'type': 'similarity', 'threshold': 80, 'limit': 10}
# Make the request to PubChem
response = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/', params=params)
# Return the SMILES strings
return response.json()['IdentifierList']['CID']
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Expecting value: line 1 column 1 (char 0)
pyscf_energy
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.MolLogP(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.MolLogP(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Success
quantile
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
operands could not be broadcast together with shapes (300,) (3,)
random_walk
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*np.random.choice([-1,1])
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Timeout
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(np.random.randint(2)*2 - 1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2) - 1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2) - 1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
rank
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
return np.linalg.matrix_rank(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return len(s)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U,S,V = np.linalg.svd(M)
return np.sum(S>1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
return np.linalg.matrix_rank(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
remove-water
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent()
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent()
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
Success
rms_velocity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
return math.sqrt(3 * k * T / m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
return math.sqrt((3*k*T)/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
rmse
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
Success
rog
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load pdb file
traj = md.load(pdb_file)
# Calculate radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
return md.compute_rg(traj)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
rotationant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
return B*J*(J+1)
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
return B*J*(J+1)
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
return B*J*(J+1)
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
return B*J*(J+1)
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
return B*J*(J+1)
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
rotation_higherant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
sasa
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load pdb
traj = md.load(pdb_file)
# Calculate sasa
sasa = md.shrake_rupley(traj, mode='residue')
# Return sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the sasa per residue
sasa = md.shrake_rupley(traj)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj, mode='residue')
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load pdb
traj = md.load(pdb_file)
# Calculate sasa
sasa = md.shrake_rupley(traj)
# Return sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
Success
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.RemoveHs(mol)
core = Chem.MolFromSmiles(Chem.MolToSmiles(mol,True))
for a in core.GetAtoms():
a.SetAtomMapNum(0)
scaffold = Chem.MolToSmiles(core,True,False,True)
return scaffold
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol,True))
core = Chem.DeleteSubstructs(scaffold,Chem.MolFromSmarts('[*]'))
return Chem.MolToSmiles(core)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = Scaffold.ScaffoldGenerator()
scaffold = engine.GetScaffoldForMol(mol)
return Chem.MolToSmiles(scaffold, isomericSmiles=True)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
name 'Scaffold' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol,True))
core = Chem.DeleteSubstructs(scaffold,Chem.MolFromSmarts('[*]'))
return Chem.MolToSmiles(core)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = rdMolDescriptors.GetMorganFingerprint(mol, 2)
arr = np.zeros((1,))
DataStructs.ConvertToNumpyArray(engine, arr)
scaffold = Chem.MolFromSmarts(str(arr.nonzero()[0]))
return scaffold
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
return alns
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
return alns
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln1, aln2, score, begin, end = top_aln
return aln1, aln2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return str(Seq(gene_seq).translate())
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
# create a sequence object
seq = Seq(gene_seq)
# translate the sequence
return seq.translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
sequence
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
r = (e/s)**(1/(l-1))
return s*r**np.arange(l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
sle
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
return sympy.solve(eqns, dict=True)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
vars = []
for eqn in eqns:
for var in re.findall(r'[a-zA-Z]\w*',eqn):
if var not in vars:
vars.append(var)
# create a matrix
matrix = []
for eqn in eqns:
row = []
for var in vars:
if var in eqn:
row.append(sympy.sympify(re.findall(r'[+-]?\d*'+var,eqn)[0]))
else:
row.append(0)
matrix.append(row)
# create a vector
vector = []
for eqn in eqns:
vector.append(sympy.sympify(re.findall(r'[+-]?\d*$',eqn)[0]))
# solve the system of linear equations
solution = sympy.linsolve(matrix,vector)
# return the solution
return solution
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
name 're' is not defined
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
vars = []
for eqn in eqns:
for var in eqn.split():
if var not in vars and var.isalpha():
vars.append(var)
# create a matrix
matrix = []
for eqn in eqns:
matrix.append([])
for var in vars:
matrix[-1].append(eqn.split().count(var))
matrix[-1].append(eqn.split().count('='))
# solve the matrix
return sympy.solve_linear_system(sympy.Matrix(matrix), *vars)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = [sympy.Eq(eqn) for eqn in eqns]
return sympy.solve(eqns)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
SympifyError: '4x + 3y = 20'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = [sympy.sympify(eq) for eq in eqns]
x = sympy.symbols('x:%d' % len(eqns))
sol = sympy.solve(eqns, x)
return sol
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigvals = np.linalg.eigvals(a)
return max(abs(eigvals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigvals = np.linalg.eigvals(a)
spectral_r = np.max(np.abs(eigvals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_radius = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eig_vals, eig_vecs = np.linalg.eig(a)
return np.max(np.abs(eig_vals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
w, v = np.linalg.eig(a)
return np.max(np.abs(w))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
find_peaks
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks,1])][::-1]
# Return the wavenumbers of the highest peaks
return abs_spectrum[peaks[:npeaks],0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks = scipy.signal.find_peaks_cwt(abs_spectrum[:,1], np.arange(1,10))
peaks = [p for p in peaks if abs_spectrum[p,1] > 0.1]
peaks = sorted(peaks, key=lambda p: abs_spectrum[p,1], reverse=True)
return peaks[:npeaks]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
# sort the peaks by height
peak_heights = abs_spectrum[peaks, 1]
peak_indices = np.argsort(peak_heights)[::-1]
# return the wavenumbers of the highest peaks
return abs_spectrum[peaks[peak_indices[:npeaks]], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
peak_wavenumbers = abs_spectrum[peaks, 0]
peak_wavenumbers = peak_wavenumbers[np.argsort(peak_wavenumbers)]
return peak_wavenumbers[-npeaks:]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
# Sort the peaks by height
sorted_peaks = sorted(zip(peaks, abs_spectrum[peaks, 1]), key=lambda x: x[1], reverse=True)
# Return the wavenumbers of the highest peaks
return [abs_spectrum[i, 0] for i, _ in sorted_peaks[:npeaks]]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
Success
speed_of_sound
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt((gamma*R*T)/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the molecules that contain the substructure
indices = []
# loop through the molecules in mol_list
for i in range(len(mol_list)):
# if the molecule contains the substructure, add the index to the list
if mol_list[i].HasSubstructMatch(mol):
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule object from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a query object from the molecule object
query = Chem.MolFromSmiles(Chem.MolToSmiles(mol))
# create a list to store the indices of the entries that contain the substructure
indices = []
# loop through mol_list
for i in range(len(mol_list)):
# if the query is in the molecule, add the index to the list
if mol_list[i].HasSubstructMatch(query):
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a mol object from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the entries that contain the substructure
indices = []
# loop through the mol_list
for i in range(len(mol_list)):
# if the mol object is in the mol_list, append the index to the indices list
if mol.HasSubstructMatch(mol_list[i]):
indices.append(i)
# return the indices list
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_sub = Chem.MolFromSmiles(smiles)
mol_sub_fp = rdMolDescriptors.GetMorganFingerprint(mol_sub, 2)
mol_sub_fp_arr = np.zeros((1,))
DataStructs.ConvertToNumpyArray(mol_sub_fp, mol_sub_fp_arr)
indices = []
for i in range(len(mol_list)):
mol_fp = rdMolDescriptors.GetMorganFingerprint(mol_list[i], 2)
mol_fp_arr = np.zeros((1,))
DataStructs.ConvertToNumpyArray(mol_fp, mol_fp_arr)
if DataStructs.FingerprintSimilarity(mol_sub_fp_arr, mol_fp_arr) > 0.5:
indices.append(i)
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# generate the query molecule
query_mol = Chem.MolFromSmiles(smiles)
# generate the list of indices
indices = []
for i in range(len(mol_list)):
# generate the molecule
mol = mol_list[i]
# check if the query molecule is a substructure of the molecule
if mol.HasSubstructMatch(query_mol):
# if it is, add the index to the list
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize the matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# calculate the fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate the Tanimoto similarity
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize fingerprint matrix
fp_matrix = np.zeros((len(smiles_list), bits))
# loop through smiles list
for i, smiles in enumerate(smiles_list):
# generate fingerprint
fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smiles), 2, nBits=bits)
# convert to numpy array
arr = np.zeros((1,))
DataStructs.ConvertToNumpyArray(fp, arr)
# store in matrix
fp_matrix[i, :] = arr
# compute pairwise Tanimoto similarity matrix
tanimoto_matrix = np.dot(fp_matrix, fp_matrix.T)
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize
n = len(smiles_list)
tanimoto_matrix = np.zeros((n, n))
# generate fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smiles), 2, nBits=bits) for smiles in smiles_list]
# calculate Tanimoto similarity
for i in range(n):
for j in range(i, n):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# loop over all smiles
for i, smiles in enumerate(smiles_list):
# generate molecule
mol = Chem.MolFromSmiles(smiles)
# generate fingerprint
fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits)
# loop over all smiles
for j, smiles2 in enumerate(smiles_list):
# generate molecule
mol2 = Chem.MolFromSmiles(smiles2)
# generate fingerprint
fp2 = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol2, 2, nBits=bits)
# calculate Tanimoto similarity
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fp, fp2)
# return matrix
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
Success
unbdistance
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two
dist = md.compute_distances(traj,lig_com,prot_com)
# return the distance
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the index of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the index of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
# return the distance
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
return md.compute_distances(traj,lig_com,prot_com)
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
protein = traj.topology.select('protein')
ligand = traj.topology.select('resname '+lig_str)
return md.compute_distances(traj,np.array([[protein.mean(),ligand.mean()]]))
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
velocity_verlet_integration
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + v_traj[i-1] * dt + 0.5 * F(x_traj[i-1]) * dt**2
v_traj[i] = v_traj[i-1] + 0.5 * (F(x_traj[i-1]) + F(x_traj[i])) * dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
T = 0.2
Prompt Override = insert
Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
---|---|---|---|---|---|
aa_polarity | Fail | Fail | Fail | Fail | Fail |
adiabatic_expansion | Fail | Fail | Fail | Fail | Fail |
alignment | Fail | Fail | Fail | Fail | Fail |
angle | Pass | Pass | Fail | Pass | Pass |
aromatic_aa | Fail | Fail | Fail | Fail | Fail |
arrhenius | Fail | Fail | Fail | Fail | Fail |
bimolecular | Fail | Fail | Fail | Fail | Fail |
bb_rad | Fail | Fail | Fail | Fail | Fail |
blast | Fail | Fail | Fail | Fail | Fail |
braggant | Fail | Fail | Fail | Fail | Fail |
bravais | Fail | Fail | Fail | Fail | Fail |
canonicalize | Pass | Pass | Pass | Pass | Pass |
carnot_efficiency | Fail | Fail | Fail | Fail | Fail |
claussius | Fail | Fail | Fail | Fail | Fail |
compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
condiff_1d | Pass | Pass | Pass | Pass | Pass |
cubes | Fail | Fail | Fail | Fail | Fail |
de_broglie | Fail | Fail | Fail | Fail | Fail |
derivative1d-ch | Fail | Fail | Fail | Fail | Fail |
derivative_2deg | Fail | Fail | Fail | Fail | Fail |
descriptors | Fail | Fail | Fail | Fail | Fail |
dipole | Fail | Pass | Fail | Fail | Fail |
dou | Fail | Fail | Fail | Fail | Fail |
eigen-ch | Fail | Fail | Fail | Fail | Fail |
eigen | Fail | Pass | Fail | Fail | Fail |
element_mass | Fail | Fail | Fail | Fail | Fail |
element_name | Fail | Fail | Fail | Fail | Fail |
energy_of_e | Fail | Fail | Fail | Fail | Fail |
find_indices | Fail | Fail | Fail | Fail | Fail |
force_constant | Fail | Fail | Fail | Fail | Fail |
fourier_1d | Fail | Fail | Fail | Fail | Fail |
freezing_depression | Fail | Fail | Fail | Fail | Fail |
genpos | Fail | Fail | Fail | Fail | Fail |
heating_water | Fail | Fail | Fail | Fail | Fail |
hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
ideal_gas | Fail | Fail | Fail | Fail | Fail |
integral | Fail | Fail | Fail | Fail | Fail |
trap | Fail | Fail | Fail | Fail | Fail |
invert_matrix | Fail | Fail | Fail | Fail | Fail |
iupac2smiles | Fail | Fail | Fail | Fail | Fail |
karplusant | Fail | Fail | Fail | Fail | Fail |
kld | Fail | Fail | Fail | Fail | Fail |
langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
weighted-least-squares | Fail | Fail | Fail | Fail | Fail |
lipinski_rule_of_five | Fail | Fail | Fail | Fail | Fail |
mape | Fail | Fail | Fail | Fail | Fail |
mapping_operator | Fail | Fail | Fail | Fail | Fail |
matpow | Fail | Fail | Fail | Fail | Fail |
matrix_factorial | Fail | Fail | Fail | Fail | Fail |
max-boltz | Fail | Fail | Fail | Fail | Fail |
michaelis | Fail | Fail | Fail | Fail | Fail |
mol_charge | Pass | Pass | Pass | Pass | Pass |
net_charge | Fail | Fail | Fail | Fail | Fail |
solve_ode | Fail | Fail | Fail | Fail | Fail |
ohe | Fail | Fail | Fail | Fail | Fail |
osmotic_pressure | Fail | Fail | Fail | Fail | Fail |
pair_wise | Fail | Fail | Fail | Fail | Fail |
pauli_matrices | Fail | Fail | Fail | Fail | Fail |
pi | Fail | Fail | Fail | Fail | Fail |
pib_1d | Fail | Fail | Fail | Fail | Fail |
pred_interval | Fail | Fail | Fail | Fail | Fail |
pubchem | Fail | Fail | Fail | Fail | Fail |
pyscf_energy | Fail | Fail | Fail | Fail | Fail |
qed | Fail | Fail | Fail | Fail | Fail |
quantile | Fail | Fail | Fail | Fail | Fail |
random_walk | Fail | Fail | Fail | Fail | Fail |
rank | Fail | Fail | Fail | Fail | Pass |
remove-water | Fail | Fail | Fail | Fail | Fail |
rms_velocity | Fail | Fail | Fail | Fail | Fail |
rmse | Fail | Fail | Fail | Fail | Fail |
rog | Fail | Fail | Fail | Fail | Fail |
rotationant | Fail | Fail | Fail | Fail | Fail |
rotation_higherant | Fail | Fail | Fail | Fail | Fail |
sasa | Fail | Fail | Fail | Fail | Fail |
scaffold | Fail | Fail | Fail | Fail | Fail |
seq-align | Fail | Fail | Fail | Fail | Fail |
seq-trans | Fail | Fail | Fail | Fail | Fail |
sequence | Fail | Fail | Fail | Fail | Fail |
sle | Fail | Fail | Fail | Fail | Fail |
spectral_r | Fail | Fail | Fail | Fail | Fail |
find_peaks | Fail | Fail | Fail | Fail | Fail |
speed_of_sound | Fail | Fail | Fail | Fail | Fail |
substructure | Fail | Fail | Fail | Fail | Fail |
tanimoto | Fail | Fail | Fail | Fail | Fail |
unbdistance | Fail | Fail | Fail | Fail | Fail |
velocity_verlet_integration | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return count
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == '*':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for letter in sequence:
if letter == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == '*':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == '*':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else False
Output:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + P1*math.exp(-gamma*T1)
T2 = T2 + P2*math.exp(-gamma*T2)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*P2
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + P1*math.exp(-gamma*T1)
T2 = T2 + P2*math.exp(-gamma*T2)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T1 = T1*math.exp(-gamma*P1)
T2 = T2*math.exp(-gamma*P2)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
local variable 'T2' referenced before assignment
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + P1*math.exp(-gamma*T1)
T2 = T2 + P2*math.exp(-gamma*T2)
if __name__ == "__main__":
T1 = float(sys.argv[1])
P1 = float(sys.argv[2])
P2 = float(sys.argv[3])
gamma = float(sys.argv[4])
print cooling(T1,P1,P2,gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 17)
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return traj
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.select([frame_index])
traj = traj.transpose()
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj)
traj = md.AlignFrame(traj, frame_index)
|/
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
invalid syntax (<string>, line 14)
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = traj[frame_index]
|/
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
invalid syntax (<string>, line 13)
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
frames = traj.frames
frame_index = int(frame_index)
frame_index += len(frames)
frames[frame_index] = frames[frame_index].copy()
frames[frame_index].index = frame_index
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
'Trajectory' object has no attribute 'frames'
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False
Output:
expected str, bytes or os.PathLike object, not Trajectory
angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
|/
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = False
Output:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return count
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for residue in sequence:
if residue == 'A':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2-T1)/Ea
k2 = k1*k1/(1+k1*k1)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)*math.exp(-Ea/k2)
|/
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 15)
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2-T1)/Ea
k2 = k1/(T2-T1)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*(T2/T1)
k2 = k2*(T1/T2)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2-T1)/Ea
k2 = k1*k1/(1+k1*k1)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rate
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
if __name__ == "__main__":
k = int(sys.argv[1])
A = float(sys.argv[2])
B = float(sys.argv[3])
print bimolecular_rate(k,A,B)
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 17)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
if __name__ == "__main__":
print bimolecular_rate(1,10,20)
print bimolecular_rate(2,10,20)
print bimolecular_rate(3,10,20)
print bimolecular_rate(4,10,20)
print bimolecular_rate(5,10,20)
print bimolecular_rate(6,10,20)
print bimolecular_rate(7,10,20)
print bimolecular_rate(8,10,20)
print bimolecular_rate(9,10,20)
print bimolecular_rate(10,10,20)
print bimolecular_rate(11,10,20)
print bimolecular_rate(12,10,20)
print bimolecular_rate(13,10,20)
print bimolecular_rate(14,10,20)
print bimolecular_rate(15,10,20)
print bimolecular_rate(16,10,20)
print bimolecular_rate(17,10,20)
print bimolecular_rate(18,10,20)
print bimolecular_rate(19,10,20)
print bimolecular_rate(20,10,20)
print bimolecular_rate(21,10,20)
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 12)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
|/
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*(A*B)/((A+B)*math.sqrt(A*A+B*B))
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
bb_rad
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return B
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 + T**2)
B = np.where(B 0, B*-1, B)
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 9)
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2)
B = B * T
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2)
B = np.where(B 0, B*-1, B)
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 9)
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 - T + lam*T + lam*T**2)
return B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 - T + lam*T)
B = np.where(B 0, -B, B)
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 9)
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, id
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).lower()
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
seq = str(seq).replace(' ','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq.upper())
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30
Output:
name 'e' is not defined
braggant
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
[insert]
return theta
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arctan(wavelength/d)
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arctan(wavelength/d)
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arctan(wavelength/d)
|/|/|/|/
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 13)
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arctan(wavelength/d)
|/ file dstars=1
|/|/|/|/|/
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def bragg_angle(wavelength, d):
"""
Returns the angle for Bragg scattering at wavelength and spacing d
"""
theta = np.arctan(wavelength/d)
|/|/|/
|/|/|/
return theta
import numpy as np
wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))
theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)
if np.isclose(theta, theta_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 13)
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return name
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
7:
raise ValueError("group_number must be between 0 and 7")
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
group_number = group_number - 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
group_number = math.floor(group_number)
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
group_number = group_number % 3
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
if group_number 1:
= 1")
if group_number % 2!= 0:
raise ValueError("group_number must be odd")
group_number = group_number // 2
lattice = [
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
invalid syntax (<string>, line 11)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
group_number = group_number - 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 4
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'
Output:
name 'name' is not defined
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_list
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon = Chem.MolToSmiles(mol)
canon_list.append(canon)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
canonical_mol = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_mol)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == c
Output:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
eps = math.pow(eps, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_cold) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_cold) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
eps = math.pow(eps, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
eps = math.ceil(eps)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1/(HVap*T2)
P2 = P2*math.exp(-0.5*((T2-T1)/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/(T2 - T1))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = HVap * math.exp(-1 * T1 * P1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = HVap * math.exp((T2 - T1)/P1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = HVap * math.exp(-(T2 - T1)/(P1 - P2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
local variable 'P2' referenced before assignment
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return result
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.Electronegativity(element1)
result = False
electronegativity:
result = True
return result
result = True if compare_electronegativity("O","C") else False
Output:
unindent does not match any outer indentation level (<string>, line 12)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
mendeleev.electronegativity(element2,element1)
return result
result = True if compare_electronegativity("O","C") else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
mendeleev.electronegativity(element2,element1)
if __name__ == "__main__":
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
return result
result = True if compare_electronegativity("O","C") else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.1:
return True
else:
return False
return result
result = True if compare_electronegativity("O","C") else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
mendeleev.electronegativity(element2,element1)
return result
result = True if compare_electronegativity("O","C") else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
condiff_1d
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diff
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return s
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s = s * i
return s
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n * n * n
for i in range(1, n+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n * n * n
for i in range(1, n+1):
s += i * i * i
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, int(math.sqrt(n))+1):
s += i * i * i
return s
result = True if sum_of_cubes(5) == 225 else False
Output:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return l
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 24)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = math.sqrt(m*m*v*v)
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 24)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
derivative1d-ch
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return d
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = np.zeros(len(x))
for i in range(len(x)):
d[i] = (a[i]-b[i])*(c[i]-x[i])
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
object of type 'int' has no len()
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/c
dy=(b-a)/c
dz=(b-a)/c
dx=dx/dx
dy=dy/dy
dz=dz/dz
|/
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
invalid syntax (<string>, line 17)
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/c
dy=(b-a)/c
dz=(b-a)/c
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
name 'd' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/c
dy=(b+a)/c
|/
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
invalid syntax (<string>, line 13)
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/(c*x)
dy=(b-a)/(c*x)
dz=(b-a)/(c*x)
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
name 'd' is not defined
derivative_2deg
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return deriv
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d([a,b,c])
deriv.x = x
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d([a,b,c])
deriv.x = x
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d([a,b,c])
deriv.x = x
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False
Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False
Output:
Success
dipole
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_moment
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(3):
dipole_moment[i] = charges[i] * np.linalg.norm(coordinates[i,:]-coordinates[i,:]+coordinates[i+1,:])
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
index 3 is out of bounds for axis 0 with size 3
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = charges.dot(coordinates)
return dipole
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros((len(coordinates), len(charges)))
for i in range(len(coordinates)):
for j in range(len(charges)):
dipole[i][j] = charges[j] * np.exp(-(coordinates[i] - coordinates[j])**2 / 2)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
setting an array element with a sequence.
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros((len(coordinates), len(charges)))
for i in range(len(charges)):
for j in range(len(coordinates)):
dipole[i,j] = charges[i]*charges[j]*coordinates[j,0]
return dipole
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(3):
dipole_moment[i] = charges[i] * np.sum(coordinates[:,i])
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False
Output:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return d
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = Chem.Bonds(mol)
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
bonds.UpdatePropertyCache()
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
module 'rdkit.Chem' has no attribute 'Bonds'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() in [0, mol.GetNumAtoms()-1]]
bonds = [b for b in bonds if b.GetEndAtomIdx() in [0, mol.GetNumAtoms()-1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() in [0, mol.GetNumAtoms()-1]]
bonds = [b for b in bonds if b.GetEndAtomIdx() in [0, mol.GetNumAtoms()-1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [bond for bond in bonds if bond.GetBeginAtomIdx() == bond.GetEndAtomIdx()]
bonds = [bond for bond in bonds if bond.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [bond for bond in bonds if bond.GetBeginAtomIdx() in [0, bond.GetEndAtomIdx()]]
bonds = [bond for bond in bonds if bond.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [bond for bond in bonds if bond.GetBeginAtomIdx() in [0, bond.GetEndAtomIdx()]]
bonds = [bond for bond in bonds if bond.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [bond for bond in bonds if bond.GetBeginAtomIdx() in [0, bond.GetEndAtomIdx()]]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bond_count = Chem.GetBondCount(mol)
bond_count = bond_count + Chem.GetNumHeavyAtoms()
bond_count = bond_count + Chem.GetNumHydrogens()
bond_count = bond_count + Chem.GetNumHBonds()
bond_count = bond_count + Chem.GetNumNitrogens()
bond_count = bond_count + Chem.GetNumZnBonds()
bond_count = bond_count + Chem.GetNumHBonds()
bond_count = bond_count + Chem.GetNumNitrogens()
bond_count = bond_count + Chem.GetNumZnBonds()
bond_count = bond_count + Chem.GetNumHBonds()
bond_count = bond_count + Chem.GetNumNitrogens()
bond_count = bond_count + Chem.GetNumZnBonds()
bond_count = bond_count + Chem.GetNumHBonds()
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4
Output:
module 'rdkit.Chem' has no attribute 'GetBondCount'
eigen-ch
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/ file dstars=0
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 15)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 15)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 13)
eigen
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,v
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/ file dstars=0
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/v
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/v
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False
Output:
invalid syntax (<string>, line 11)
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.elements.mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
module 'mendeleev.elements' has no attribute 'mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.elements.get_mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
module 'mendeleev.elements' has no attribute 'get_mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False
Output:
module 'mendeleev' has no attribute 'ElementMass'
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return s
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else False
Output:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else False
Output:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else False
Output:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
return s
result = True if symbol(26).lower()=="fe" else False
Output:
module 'mendeleev' has no attribute 'symbol'
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else False
Output:
invalid syntax (<string>, line 13)
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energy
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 1
for k in range(1,n+1):
energy *= k
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (n**i)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1,n+1):
energy += i
energy *= i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.0
for i in range(1,n+1):
energy += i*i
return energy
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 1
for i in range(1, n+1):
energy *= i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idx
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = mdtraj.load(pdb_file)
idx = np.where(pdb.select('resname CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.resname!= 'CA')[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
ca_indices = []
for i in range(pdb.n_atoms):
if pdb.atoms[i].name!= 'CA':
continue
ca_indices.append(i)
ca_indices = np.array(ca_indices)
0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
unindent does not match any outer indentation level (<string>, line 16)
force_constant
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return k
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1*m2/(wave_len*wave_len)
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 13)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k *= wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
fourier_1d
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return w
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
|/ file dstars=0
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else False
Output:
invalid syntax (<string>, line 11)
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaT
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT=Kf*m/(1.989*10**9)
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
Kf = Kf/1000
m = m/1000
deltaT = Kf*m
if deltaT 0:
deltaT = 0
1000:
deltaT = 1000
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
if deltaT 0:
deltaT = 0
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
invalid syntax (<string>, line 12)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT=Kf*m
if deltaT0:
deltaT=0
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
name 'deltaT0' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT=Kf*m
if deltaT0:
deltaT=0
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False
Output:
name 'deltaT0' is not defined
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generators
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1,11):
generators.append(g*gnum)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
Success
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1,gnum+1):
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
expected an indented block (<string>, line 13)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1,gnum+1):
generators.append([])
for n in range(1,g+1):
generators[g].append([])
for x in range(1,g+1):
generators[g][n].append([])
for y in range(1,g+1):
generators[g][n][y].append([])
for z in range(1,g+1):
generators[g][n][y][z].append([])
for i in range(1,g+1):
generators[g][n][y][z][i].append([])
generators[g][n][y][z][i][z].append([])
generators[g][n][y][z][i][z][-1].append([])
generators[g][n][y][z][i][z][-1][z].append([])
generators[g][n][y][z][i][z][-1][z][-1].append([])
generators[g][n][y][z][i][z][-1][z][-1][z].append([])
generators[g][n][y][z][i][z][-1][z][-1][z][-1].append([])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for i in range(1, gnum+1):
generators.append(i)
|/
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
invalid syntax (<string>, line 15)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1, gnum+1):
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
generators.append(g*10)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)
Output:
Success
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 - T2)/T1 * math.log(T1/T2)
T1 -= T2/T1 * math.log(T1/T2)
T2 -= T1/T2 * math.log(T1/T2)
q *= 1000
return q
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = ((T1/T2)**n)/((T2/T1)**n)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1/T2)**j
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for i in range(n):
q += (T1 * math.pow(T2, i)) / (T1 * T2)
if __name__ == "__main__":
n = int(sys.argv[1])
T1 = float(sys.argv[2])
T2 = float(sys.argv[3])
print heating_energy(n, T1, T2)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 18)
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for T in T1:
q += (T * n) / (T2 * n)
if __name__ == "__main__":
n = int(sys.argv[1])
T1 = [float(e) for e in sys.argv[2:]]
T2 = [float(e) for e in sys.argv[3:]]
print heating_energy(n, T1, T2)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 17)
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return resids
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'HOH':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
continue
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H' and residue.resname!= 'HB':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False
Output:
name 'mdtraj' is not defined
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return P
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T/(n*math.pow(10,8))
if __name__ == "__main__":
n = float(sys.argv[1])
V = float(sys.argv[2])
T = float(sys.argv[3])
print ideal_gas_pressure(n,V,T)
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 16)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T/(n*math.pow(10,9))
if __name__ == "__main__":
n = float(sys.argv[1])
V = float(sys.argv[2])
T = float(sys.argv[3])
print ideal_gas_pressure(n,V,T)
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 16)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-(n*T)/V)
if __name__ == "__main__":
if len(sys.argv)!= 3:
"
sys.exit(1)
n = float(sys.argv[1])
V = float(sys.argv[2])
print "Pressure for ideal gas at temperature %f, volume %f, T = %f" % (n,V,ideal_gas_pressure(n,V,T))
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
expected an indented block (<string>, line 14)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T/(n*math.pow(10,9))
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-(n*T)/T)
if __name__ == "__main__":
if len(sys.argv)!= 3:
"
sys.exit(1)
n = float(sys.argv[1])
V = float(sys.argv[2])
print "Pressure for %d moles of an ideal gas at temperature %f atm is %f" % (n,V,ideal_gas_pressure(n,V))
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = False
Output:
expected an indented block (<string>, line 14)
integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False
Output:
invalid syntax (<string>, line 14)
trap
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integral
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.trapz(b - a, a * (b - a) / i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
division by zero
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-b * i)
return integral
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-b * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * f(b - a)
a, b = b, a + b
return integral
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
loop of ufunc does not support argument 0 of type int which has no callable sqrt method
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * f(b) / i
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else False
Output:
Success
invert_matrix
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainv
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
name 'Ainv' is not defined
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
name 'Ainv' is not defined
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# compute inverse of A
Ainv = np.linalg.inv(A)
# return inverse of A
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 15)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILES
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace('-', '')
IUPAC = IUPAC.replace('_', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace(',', '')
IUPAC = IUPAC.replace('.', '')
IUPAC = IUPAC.replace(';', '')
IUPAC = IUPAC.replace(':', '')
IUPAC = IUPAC.replace(';', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace(' ','')
IUPAC = IUPAC.replace('-','')
IUPAC = IUPAC.replace('(','')
IUPAC = IUPAC.replace(')','')
IUPAC = IUPAC.replace(',','')
IUPAC = IUPAC.replace('.','')
IUPAC = IUPAC.replace(':','')
IUPAC = IUPAC.replace(';','')
IUPAC = IUPAC.replace('-','')
IUPAC = IUPAC.replace('+','')
IUPAC = IUPAC.replace('=','')
','')
IUPAC = IUPAC.replace('','')
IUPAC = IUPAC.replace('!','')
IUPAC = IUPAC.replace('?','')
IUPAC = IUPAC.replace('\'','')
IUPAC = IUPAC.replace('"','')
IUPAC = IUPAC.replace('{','')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
EOL while scanning string literal (<string>, line 32)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace('-', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace('-', '')
IUPAC = IUPAC.replace('_', '')
IUPAC = IUPAC.replace('(', '')
IUPAC = IUPAC.replace(')', '')
IUPAC = IUPAC.replace(',', '')
IUPAC = IUPAC.replace('.', '')
IUPAC = IUPAC.replace(';', '')
IUPAC = IUPAC.replace(':', '')
IUPAC = IUPAC.replace(';', '')
IUPAC = IUPAC.replace('!', '')
IUPAC = IUPAC.replace('?', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
IUPAC = IUPAC.replace('\'', '')
IUPAC = IUPAC.replace('"', '')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else False
Output:
name 'SMILES' is not defined
karplusant
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
[insert]
return J
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = A*phi*B*C
|/ file dstars=1
|/|/|/|/
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = (A*phi*B*C)/(np.sqrt(A*A+B*B+C*C))
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = A * np.exp(-B * phi)
J += C * np.exp(-B * phi)
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = A*B*C
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def coupling(phi, A, B, C):
"""
Returns the J coupling using the karplus equation
"""
J = A * np.exp(-B * phi) + C * np.exp(-B * phi)
return J
import numpy as np
A = 1
B = 2
C = 1
phi = np.pi/7
J = A+B*np.cos(phi)+C*np.cos(2*phi)
J_codex = coupling(phi,A,B,C)
if np.isclose(J, J_codex) == True:
result = True
else:
result = False
Output:
Success
kld
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return loss
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0.0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else False
Output:
Success
langevin_dynamics
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_traj
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
for i in range(n_steps):
x_traj[i] = x0
v_traj[i] = v0
x_traj[i+1] = x0 + dt*F(x_traj[i])
v_traj[i+1] = v0 + dt*gamma*F(x_traj[i])
x0 = x_traj[i+1]
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
index 100000 is out of bounds for axis 0 with size 100000
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
for i in range(n_steps):
x_traj[i] = x0[i]
v_traj[i] = v0[i]
x_traj[i+1] = x0[i] + dt*F(x_traj[i])
v_traj[i+1] = v0[i] + dt*F(x_traj[i])*gamma
x_traj[i+2] = x0[i] + dt*F(x_traj[i])*gamma
v_traj[i+2] = v0[i] + dt*F(x_traj[i])*gamma*m
x_traj[i+3] = x0[i] + dt*F(x_traj[i])*gamma*m
v_traj[i+3] = v0[i] + dt*F(x_traj[i])*gamma*m*m
x_traj[i+4] = x0[i] + dt*F(x_traj[i])*gamma*m*m
v_traj[i+4] = v0[i] + dt*F(x_traj[i])*gamma*m*m*m
x_traj[i+5] = x0[i] + dt*F(x_traj[i])*gamma*m*m*m
v_traj[i+5] = v0[i] + dt*F(x_traj[i])*gamma*m*m*m*m
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
'float' object is not subscriptable
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma)*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False
Output:
F() takes from 1 to 2 positional arguments but 3 were given
weighted-least-squares
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return beta
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.dot(x.T, np.dot(w, x))
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)
Output:
invalid syntax (<string>, line 10)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return result
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=5)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=10)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=500)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=5)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=10)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=500)
lipinski_descriptors = Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=5)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.RemoveHs(mol)
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(0))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(1))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(2))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(3))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(4))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(5))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(6))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(7))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(8))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(9))
mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(10))
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else False
Output:
module 'rdkit.Chem' has no attribute 'RemoveAtoms'
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return e
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = math.fabs(y_hat - y)
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
invalid syntax (<string>, line 12)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = math.fabs((y_hat - y) / y_hat)
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = (y_hat - y) / y_hat
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False
Output:
invalid syntax (<string>, line 12)
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return M
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i, beads_mapping in enumerate(beads_mappings):
for j, beads_mapping in enumerate(beads_mappings):
M[i][j] = molecule.GetAtomWithIdx(beads_mapping).GetAtomicNum()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i][j]).GetAtomicNum()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i][j]).GetAtomicNum()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i]).GetAtomWithIdx(beads_mappings[j]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i, beads_mapping in enumerate(beads_mappings):
for j, atom_mapping in enumerate(beads_mapping):
M[i][j] = molecule.GetAtomWithIdx(atom_mapping).GetAtomicNum()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False
Output:
invalid syntax (<string>, line 16)
matpow
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return r
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.zeros_like(x)
for i in range(n):
r[i]=x[i]**n
|/
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
invalid syntax (<string>, line 15)
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.zeros_like(x)
r[n:] = x[n:]
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else False
Output:
Success
matrix_factorial
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return f
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.matrix(np.zeros((n, n)))
for i in range(n):
for j in range(n):
f[i, j] = f[j, i] = i
|/
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
invalid syntax (<string>, line 14)
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.matrix(np.zeros((n, n)))
for i in range(n):
for j in range(n):
f[i, j] = f[i, j] * i
|/
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
invalid syntax (<string>, line 14)
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.empty([n, n])
for i in range(n):
for j in range(n):
f[i, j] = i**j
|/
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
invalid syntax (<string>, line 14)
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return s
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = False
Output:
invalid syntax (<string>, line 15)
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * Km
if v 0.1:
v = 0.1
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax
for t in range(1,S+1):
v = v * (Km * math.exp(-t/S) + math.exp(-t/S/2))
if __name__ == "__main__":
Vmax = float(sys.argv[1])
S = float(sys.argv[2])
Km = float(sys.argv[3])
print(reaction_velocity(Vmax, S, Km))
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
'return' outside function (<string>, line 22)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * Km
v = math.floor(v)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * Km
if v 0.1:
v = 0.1
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * math.exp(-S * Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False
Output:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for char in sequence:
charge += math.log10(abs(ord(char) - 97))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += ord(c) - ord('A')
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
if __name__ == "__main__":
sequence = str(sys.argv[1])
charge = net_charge(sequence)
print charge
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
Missing parentheses in call to 'print'. Did you mean print(charge)? (<string>, line 16)
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else False
Output:
math domain error
solve_ode
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return sol
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
for i,t in enumerate(t):
sol[i] = fn(t,y0)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
for i in range(len(t)):
sol[i] = fn(t[i],y0)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = fn(t,y0)
|/
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
sol[0] = y0
for i in range(1, len(t)):
sol[i] = sol[i-1] + fn(t[i],sol[i-1])
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False
Output:
setting an array element with a sequence.
ohe
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return v
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int)
v[a] = 1
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
invalid syntax (<string>, line 15)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/ file dstars=0
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
invalid syntax (<string>, line 12)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/ file dstars=0
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
invalid syntax (<string>, line 12)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
operands could not be broadcast together with shapes (10,) (10,5)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False
Output:
operands could not be broadcast together with shapes (10,) (10,5)
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return p
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/3.0)*math.pow(Pi,3.0/3.0)
p *= 1000
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
invalid syntax (<string>, line 18)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/4.0)
p *= (3.0/4.0)
p /= (math.pi*3.0)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/3.0)*math.pow(Pi,3.0/3.0)
return p
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = 0.0945 # atm /mol
p = p*math.pow(T,3.0)/R
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
invalid syntax (<string>, line 18)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = 0.0
if T 300:
p = 0.0
elif T 500:
p = 0.0
elif T 700:
p = 0.0
elif T 900:
p = 0.0
elif T 1200:
p = 0.0
elif T 1500:
p = 0.0
elif T 1800:
p = 0.0
elif T 2000:
p = 0.0
elif T 2500:
p = 0.0
elif T 3000:
p = 0.0
elif T 3500:
p = 0.0
elif T 4000:
p = 0.0
elif T 4500:
p = 0.0
elif T 5000:
p = 0.0
elif T 5500:
p = 0.0
elif T 6000:
p = 0.0
elif T 6500:
p = 0.0
elif T 7000:
p = 0.0
elif T 7500:
p = 0.0
elif T 8000:
p = 0.0
elif T 8500:
p = 0.0
elif T 9000:
p = 0.0
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False
Output:
invalid syntax (<string>, line 13)
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distances
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(pdb_file)
alpha_carbons = pdb.select('name CA')
alpha_carbons = alpha_carbons.sort('CA')
alpha_carbons = alpha_carbons.unique('CA')
alpha_carbons = alpha_carbons.tolist()
distances = []
for alpha_carbon in alpha_carbons:
distances.append(alpha_carbon.distance(pdb))
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *alpha and resid *alpha and resid *beta')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.unique('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.sort('resname')
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(pdb_file)
0')
alpha_carbons = alpha_carbons.sort('name')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = alpha_carbons.tolist()
distances = []
for alpha_carbon in alpha_carbons:
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split("_")
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split("-")
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split("+")
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split("(")
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split(")")
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split(")")
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
unindent does not match any outer indentation level (<string>, line 13)
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = mdtraj.load(pdb_file)
0')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.select('resname *alpha and resname *beta')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.select('resname *alpha and resname *gamma')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.select('resname *alpha and resname *delta')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.select('resname *alpha and resname *epsilon')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.select('resname *alpha and resname *zeta')
alpha_carbons = alpha_carbons.sort('resname')
alpha_carbons = alpha_carbons.select('resname *alpha and resname *eta')
alpha_carbons = alpha_carbons.sort('resname')
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else False
Output:
unindent does not match any outer indentation level (<string>, line 13)
pauli_matrices
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
[insert]
return sigma_x, sigma_y, sigma_z
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = 1
sigma_y = 1
sigma_z = 1
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = 1
sigma_y = 1
sigma_z = 1
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = 1
sigma_y = 1
sigma_z = 1
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = 1
sigma_y = 1
sigma_z = 1
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
import numpy as np
def pauli():
"""
This function returns the three pauli matrices
"""
sigma_x = 1
sigma_y = 1
sigma_z = 1
return sigma_x, sigma_y, sigma_z
sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))
sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)
Output:
Success
pi
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_est
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 0
for i in range(nsamples):
pi_est = pi_est * np.pi / nsamples
return pi_est
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
for _ in range(nsamples):
pi_est *= np.pi
pi_est *= np.pi
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
for i in range(nsamples):
pi_est *= np.pi
pi_est *= (1-np.pi)
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
for i in range(nsamples):
pi_est *= (2.*np.pi)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
for i in range(nsamples):
pi_est *= 2
|/
|/|/
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False
Output:
invalid syntax (<string>, line 13)
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return e
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=math.exp(-(L/n)*(m*hbar))
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(m*L**2-hbar*L**3)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=math.exp(-0.5*((n-m)/L)**2)
e=e*hbar
if __name__=="__main__":
n=int(sys.argv[1])
m=int(sys.argv[2])
L=int(sys.argv[3])
hbar=float(sys.argv[4])
print particle_in_box(n,m,L,hbar)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 17)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m*L
e=e*hbar
|/ file dstars=0
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 13)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=math.exp(-((m-l)/hbar)**2)
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
pred_interval
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return n
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.floor(np.log(p) / np.log(pred_level)))
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.ceil(np.log2(pred_level)))
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 3
if n == 4:
return 4
if n == 5:
return 5
if n == 6:
return 6
if n == 7:
return 7
if n == 8:
return 8
if n == 9:
return 9
if n == 10:
return 10
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
object of type 'float' has no len()
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
= pred_level:
return i
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
expected an indented block (<string>, line 10)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.log2(pred_level))
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else False
Output:
invalid syntax (<string>, line 11)
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return mols
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://rest.pubchem.net/api/similarity?query={}&format=smiles'.format(smiles)
response = requests.get(url)
data = response.json()
mols = [Chem.MolFromSmiles(smi) for smi in data['results']]
return mols
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?query=CC=C=C(C(=O)N)&format=smiles (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f9cd548c430>: Failed to establish a new connection: [Errno -2] Name or service not known'))
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://rest.pubchem.net/api/similarity?smiles=' + smiles
response = requests.get(url)
data = response.json()
mols = data['results']
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?smiles=CC=C=C(C(=O)N) (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f9cd548cee0>: Failed to establish a new connection: [Errno -2] Name or service not known'))
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://rest.pubchem.net/api/similarity?query={}&format=smiles'.format(smiles)
response = requests.get(url)
data = response.json()
mols = data['results']
mols = [Chem.MolFromSmiles(smi) for smi in mols]
return mols
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?query=CC=C=C(C(=O)N)&format=smiles (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f9cd548c400>: Failed to establish a new connection: [Errno -2] Name or service not known'))
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/similarity/similarity?smiles=' + smiles
response = requests.get(url)
data = response.json()
mols = data['results']
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [mol for mol in mols if mol.HasSubstructMatch(Crippen.MolFromSmiles(smiles))]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [mol for mol in mols if mol.HasSubstructMatch(Crippen.MolFromSmiles(smiles))]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [mol for mol in mols if mol.HasSubstructMatch(Crippen.MolFromSmiles(smiles))]
mols = [Chem.MolFromSmiles(smi) for smi in mols]
mols = [mol for mol in mols if mol.HasSubstructMatch(Crippen.MolFromSmiles(smiles))]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Expecting value: line 1 column 1 (char 0)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=smiles'.format(smiles)
response = requests.get(url)
data = response.json()
mols = []
for mol in data['results']:
mol = Chem.MolFromSmiles(mol['smiles'])
if mol is not None:
mols.append(mol)
return mols
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False
Output:
Expecting value: line 1 column 1 (char 0)
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.kernel()
ground_energy = mol.energy_nuc()
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.verbose = 0
mol.output = '/dev/null'
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
invalid syntax (<string>, line 28)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
invalid syntax (<string>, line 29)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
invalid syntax (<string>, line 28)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else False
Output:
invalid syntax (<string>, line 29)
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return result
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolToMolBlock(mol)
mol = Chem.RemoveHs(mol)
mol = Chem.RemoveAtoms(mol, [0])
mol = Chem.RemoveAtoms(mol, [1])
mol = Chem.RemoveAtoms(mol, [2])
mol = Chem.RemoveAtoms(mol, [3])
mol = Chem.RemoveAtoms(mol, [4])
mol = Chem.RemoveAtoms(mol, [0])
mol = Chem.RemoveAtoms(mol, [1])
mol = Chem.RemoveAtoms(mol, [2])
mol = Chem.RemoveAtoms(mol, [3])
mol = Chem.RemoveAtoms(mol, [4])
mol = Chem.RemoveAtoms(mol, [0])
mol = Chem.RemoveAtoms(mol, [1])
mol = Chem.RemoveAtoms(mol, [2])
mol = Chem.RemoveAtoms(mol, [3])
mol = Chem.RemoveAtoms(mol, [4])
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
Python argument types in
rdkit.Chem.rdmolfiles.MolToMolBlock(str)
did not match C++ signature:
MolToMolBlock(RDKit::ROMol mol, bool includeStereo=True, int confId=-1, bool kekulize=True, bool forceV3000=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False
Output:
name 'result' is not defined
quantile
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return result
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[(q-1)/2]
q)] = a[(q+1)/2]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
unmatched ')' (<string>, line 10)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
q)], q)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
unmatched ')' (<string>, line 9)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[(q-1):]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
unsupported operand type(s) for -: 'list' and 'int'
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
q))]
result[np.where(aq)] = a[(where(aq))]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
unmatched ')' (<string>, line 9)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[np.where(a=q)]
q)]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else False
Output:
unmatched ')' (<string>, line 10)
random_walk
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return traj
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.uniform()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
traj.append([x0 + a * np.random.randn()])
|/
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
invalid syntax (<string>, line 17)
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.rand()
traj.append([x1,x0])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.rand()
x2 = x1 + a * np.random.rand()
x3 = x2 + a * np.random.rand()
traj.append([x0, x1, x2, x3])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
traj.append(x0)
x0 += a
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False
Output:
Success
rank
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return r
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
r = np.sum(np.diag(S))
|/
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U,S,V = np.linalg.svd(M)
r = np.sum(np.diag(S))
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
0)[0]
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
unindent does not match any outer indentation level (<string>, line 9)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
0)[0]
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
unmatched ')' (<string>, line 9)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
rank = S.shape[0]
return rank
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else False
Output:
Success
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_traj
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = traj.top
water_atoms = top.select('name water and not water')
water_atoms.write(top_file)
traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj = new_traj.rename("water_traj")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
new_traj = new_traj.rename("water_top")
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
new_traj.top = new_traj.top[new_traj.top.solvent == 0]
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
traj = traj[traj.select('solvent_id==0')]
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
traj = traj.remove_solvent_id()
traj = traj.topology
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False
Output:
"top" argument is required for load_trr
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(m*T*T/T)
if __name__ == "__main__":
if len(sys.argv)!= 2:
print "Usage: python rms_velocity.py"
sys.exit()
T = float(sys.argv[1])
m = float(sys.argv[2])
print rms_velocity(T,m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Missing parentheses in call to 'print'. Did you mean print("Usage: python rms_velocity.py")? (<string>, line 14)
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(m*T*T/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(m*T*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
rmse
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return e
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.power(a-b,2)
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
invalid syntax (<string>, line 13)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2)
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False
Output:
invalid syntax (<string>, line 11)
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rg
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = md.compute_radius_of_gyration(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
module 'mdtraj' has no attribute 'compute_radius_of_gyration'
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = mdtraj.load(pdb_file)
rg = mdtraj.calc_radius_of_gyration(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'mdtraj' is not defined
rotationant
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
[insert]
return E_rot
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = 0
for k in range(J.shape[0]):
E_rot += B[k]*J[k]
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
'int' object has no attribute 'shape'
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = 0
for j in range(J.shape[0]):
E_rot += B[j]*np.exp(-B[j]*J[j])
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
'int' object has no attribute 'shape'
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = B*J
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J):
"""
Returns the quantum rotational energy for level J and constant B
"""
E_rot = 0
for j in range(J):
E_rot += B[j]
return E_rot
import numpy as np
B = 2
J = 3
E_rot = B*J*(J+1)
E_rot_codex = e_rot(B,J)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
'int' object is not subscriptable
rotation_higherant
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
[insert]
return E_rot
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = 0
for j in range(J):
E_rot += B[j]*D[j]
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
'int' object is not subscriptable
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*D
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*D
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = B*J*D
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
Success
import numpy as np
def e_rot(B,J,D):
"""
Returns the quantum rotational energy for level J and constants B, D
"""
E_rot = 0
for j in range(J):
E_rot += B[j]*D[j]
return E_rot
import numpy as np
B = 2
J = 3
D = 2
E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)
E_rot_codex = e_rot(B,J,D)
if np.isclose(E_rot, E_rot_codex) == True:
result = True
else:
result = False
Output:
'int' object is not subscriptable
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA', resname='CA')
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
invalid syntax (<string>, line 15)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa.rename("CA")
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select("CA")
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
invalid syntax (<string>, line 15)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA', resname='CA')
sasa = sasa.sum(axis=1).sum(axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False
Output:
name 'sasa' is not defined
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc
Output:
Success
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return aligned
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = AlignIO.read("blastn", "blastn")
aln.set_alignment_context(aln.get_alignment_context())
aln.set_query_sequence(seq1)
aln.set_database_sequence(seq2)
aln.set_evalue(0)
aln.set_query_start(0)
aln.set_query_end(0)
aln.set_database_start(0)
aln.set_database_end(0)
aln.set_evalue(0)
aln.set_evalue_gap(0)
aln.set_evalue_gap_start(0)
aln.set_evalue_gap_end(0)
aln.set_evalue_gap_strand(0)
aln.set_evalue_gap_frame(0)
aln.set_evalue_gap_frame_type(0)
aln.set_evalue_gap_frame_value(0)
aln.set_evalue_gap_frame_value_type(0)
aln.set_evalue_gap_frame_value_value(0)
aln.set_evalue_gap_frame_value_value_type(0)
aln.set_evalue_gap_frame_value_value_value(0)
aln.set_evalue_gap_frame_value_value_type(0)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
name 'AlignIO' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = AlignIO.read(seq1, 'fasta')
aln = AlignIO.read(seq2, 'fasta')
aln = aln.rename_gaps('-')
aln = aln.rename_seq('seq')
aln = aln.rename_seq('seq2')
aln = aln.rename_seq('seq3')
aln = aln.rename_seq('seq4')
aln = aln.rename_seq('seq5')
aln = aln.rename_seq('seq6')
aln = aln.rename_seq('seq7')
aln = aln.rename_seq('seq8')
aln = aln.rename_seq('seq9')
aln = aln.rename_seq('seq10')
aln = aln.rename_seq('seq11')
aln = aln.rename_seq('seq12')
aln = aln.rename_seq('seq13')
aln = aln.rename_seq('seq14')
aln = aln.rename_seq('seq15')
aln = aln.rename_seq('seq16')
aln = aln.rename_seq('seq17')
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
name 'AlignIO' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([SeqIO.to_dict(SeqRecord(Seq(seq1), "fasta")), SeqIO.to_dict(SeqRecord(Seq(seq2), "fasta"))])
aln.set_flags(aln.get_flags() | Align.AUTO_SEQUENCE)
return aln
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
name 'SeqRecord' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.DUPLICATE_ENDS)
return aln
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
__init__() got an unexpected keyword argument 'gap_char'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([SeqIO.to_dict(SeqRecord(Seq(seq1), "fasta")), SeqIO.to_dict(SeqRecord(Seq(seq2), "fasta"))])
return aln
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'
Output:
name 'SeqRecord' is not defined
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seq
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps
Output:
Success
sequence
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return x
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
s=np.asscalar(float(s))
e=np.asscalar(float(e))
l=np.asscalar(float(l))
x=np.zeros(l)
x[0]=s
x[1]=e
x[2]=s
x[3]=e
x[4]=s
x[5]=e
x[6]=s
x[7]=e
x[8]=s
x[9]=e
x[10]=s
x[11]=e
x[12]=s
x[13]=e
x[14]=s
x[15]=e
x[16]=s
x[17]=e
x[18]=s
x[19]=e
x[20]=s
x[21]=e
x[22]=s
x[23]=e
x[24]=s
x[25]=e
x[26]=s
x[27]=e
x[28]=s
x[29]=e
x[30]=s
x[31]=e
x[32]=s
x[33]=e
x[34]=s
x[35]=e
x[36]=s
x[37]=e
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
'float' object has no attribute 'item'
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.arange(s,e,l)
|/ file dstars=0
|/|/
|/x
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
invalid syntax (<string>, line 12)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.linspace(s,e,l)
|/
|/
|/
|/
|/
|/
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
invalid syntax (<string>, line 14)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
seq = []
for i in range(s):
seq.append(i)
for i in range(s,e):
seq.append(i)
for i in range(s,e+l):
seq.append(i)
return seq
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
seq = []
for i in range(s):
seq.append(i)
for i in range(s,e):
seq.append(i)
for i in range(s,e+l):
seq.append(i)
return seq
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False
Output:
Success
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return x
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x0 = sympy.symbols('x_0')
x1 = sympy.symbols('x_1')
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.simplify()
eqns = eqns.expand()
eqns = eqns.simplify()
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
eqns = eqns.subs([('x_0', x0),('x_1', x1)])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
eqns = eqns.expand()
eqns = eqns.simplify()
eqns = eqns.collect(sympy.Symbol('x_0'))
eqns = eqns.collect(sympy.Symbol('x_1'))
eqns = eqns.collect(sympy.Symbol('x_2'))
eqns = eqns.collect(sympy.Symbol('x_3'))
eqns = eqns.collect(sympy.Symbol('x_4'))
eqns = eqns.collect(sympy.Symbol('x_5'))
eqns = eqns.collect(sympy.Symbol('x_6'))
eqns = eqns.collect(sympy.Symbol('x_7'))
eqns = eqns.collect(sympy.Symbol('x_8'))
eqns = eqns.collect(sympy.Symbol('x_9'))
eqns = eqns.collect(sympy.Symbol('x_10'))
eqns = eqns.collect(sympy.Symbol('x_11'))
eqns = eqns.collect(sympy.Symbol('x_12'))
eqns = eqns.collect(sympy.Symbol('x_13'))
eqns = eqns.collect(sympy.Symbol('x_14'))
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
eqns = eqns.expand()
eqns = eqns.simplify()
eqns = eqns.subs({sympy.Symbol('a_0'): 0, sympy.Symbol('b_0'): 0, sympy.Symbol('a_1'): 0, sympy.Symbol('b_1'): 0})
eqns = eqns.subs({sympy.Symbol('a_0'): sympy.Symbol('x_0'), sympy.Symbol('b_0'): sympy.Symbol('x_1'), sympy.Symbol('a_1'): sympy.Symbol('x_2')})
eqns = eqns.subs({sympy.Symbol('x_0'): sympy.Symbol('x_0'), sympy.Symbol('x_1'): sympy.Symbol('x_1')})
eqns = eqns.subs({sympy.Symbol('x_0'): sympy.Symbol('x_1'), sympy.Symbol('x_1'): sympy.Symbol('x_2')})
eqns = eqns.subs({sympy.Symbol('x_0'): sympy.Symbol('x_2'), sympy.Symbol('x_1'): sympy.Symbol('x_2')})
eqns = eqns.subs({sympy.Symbol('x_0'): sympy.Symbol('x_2'), sympy.Symbol('x_1'): sympy.Symbol('x_2')})
eqns = eqns.subs({sympy.Symbol('x_0'): sympy.Symbol('x_2'), sympy.Symbol('x_1'): sympy.Symbol('x_2')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
a = eqns[0]
b = eqns[1]
c = eqns[2]
x = sympy.Symbol('x')
eqns = [sympy.Eq(sympy.Eq(a,x), sympy.Eq(b,x)),sympy.Eq(sympy.Eq(c,x), sympy.Eq(a,x)),sympy.Eq(sympy.Eq(b,x), sympy.Eq(c,x))]
eqns = sympy.Matrix(eqns)
eqns = sympy.solve(eqns, x)
|/
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
invalid syntax (<string>, line 18)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
a = eqns[0]
b = eqns[1]
c = eqns[2]
x = sympy.solve([a,b,c],[0,1,2])
|/
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else False
Output:
invalid syntax (<string>, line 15)
spectral_r
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradius
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
|/
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
invalid syntax (<string>, line 11)
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2,axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2, axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else False
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbers
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = np.asarray(peaks)
peaks.sort()
peaks = peaks[:npeaks]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peak_locs = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peak_locs.sort()
peak_locs = peak_locs[::-1]
peak_locs = peak_locs[:npeaks]
peak_locs = [peak_locs[0]]
return peak_locs
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peak_positions, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peak_positions = np.asarray(peak_positions)
peak_positions.sort()
peak_positions = peak_positions[::-1]
peak_positions = peak_positions[:npeaks]
return peak_positions
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = np.asarray(peaks)
peaks.sort()
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = [peak[0] for peak in peaks]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)
Output:
`x` must be a 1-D array
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = gamma*T*m
s = math.pow(s,3)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m*T*math.exp(-gamma*T)
if __name__ == "__main__":
T = int(sys.argv[1])
m = float(sys.argv[2])
gamma = float(sys.argv[3])
print speed_of_sound(T,m,gamma)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 18)
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*math.exp(-gamma*T)
if __name__ == "__main__":
T = int(sys.argv[1])
m = float(sys.argv[2])
gamma = float(sys.argv[3])
print speed_of_sound(T,m,gamma)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 16)
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = False
Output:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idx
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.MolToSmiles(mol_list)
mol_list = Chem.MolFromSmarts(mol_list)
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.MolToSmiles(mol_list)
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.MolToSmiles(mol_list)
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.MolToSmiles(mol_list)
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.MolToSmiles(mol_list)
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.MolToSmiles(mol_list)
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.MolToSmiles(mol_list)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol = Chem.MolFromSmiles(smiles)
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
mol_list = [mol for mol in mol_list if mol is not None]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else False
Output:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return s
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.SetProp("GenerateMurckoCode", True)
scaffold.SetProp("MurckoCodeLength", bits)
scaffold.SetProp("MurckoCodeBits", bits)
scaffold.SetProp("MurckoCodeSeed", 0)
scaffold.SetProp("MurckoCodeSeedBits", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
scaffold.SetProp("MurckoCodeSeedBitsLength", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("NumAtomPairs", len(smiles_list))
scaffold.SetProp("NumExplicitHs", 0)
scaffold.SetProp("NumAtomTypes", 0)
scaffold.SetProp("NumBondTypes", 0)
scaffold.SetProp("NumHs", 0)
scaffold.SetProp("NumHsAtomTypes", 0)
scaffold.SetProp("NumRotatableBonds", 0)
scaffold.SetProp("NumRotatableBondTypes", 0)
scaffold.SetProp("NumBonds", 0)
scaffold.SetProp("NumBondTypes", 0)
scaffold.SetProp("NumHsAtomTypes", 0)
scaffold.SetProp("NumHsBondTypes", 0)
scaffold.SetProp("NumHsBonds", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("NumAtomPairs", len(smiles_list))
scaffold.SetProp("NumExplicitHs", 0)
scaffold.SetProp("NumImplicitHs", 0)
scaffold.SetProp("NumRotatableBonds", 0)
scaffold.SetProp("NumPeriodicBonds", 0)
scaffold.SetProp("NumBonds", 0)
scaffold.SetProp("NumAromaticBonds", 0)
scaffold.SetProp("NumHydrogens", 0)
scaffold.SetProp("NumHs", 0)
scaffold.SetProp("NumRadicalElectrons", 0)
scaffold.SetProp("NumChirals", 0)
scaffold.SetProp("NumHsAtom", 0)
scaffold.SetProp("NumHsBond", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoParams.NumBits", bits)
scaffold.SetProp("MurckoParams.NumBitsError", bits)
scaffold.SetProp("MurckoParams.NumBitsWarning", bits)
scaffold.SetProp("MurckoParams.NumBitsAccuracy", bits)
scaffold.SetProp("MurckoParams.NumBitsAccuracyError", bits)
scaffold.SetProp("MurckoParams.NumBitsAccuracyWarning", bits)
scaffold.SetProp("MurckoParams.NumBitsAccuracyAccuracy", bits)
scaffold.SetProp("MurckoParams.NumBitsAccuracyAccuracyError", bits)
scaffold.SetProp("MurckoParams.NumBitsAccuracyAccuracyWarning", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoRevComp", True)
scaffold.SetProp("MurckoRevComp.MaxIter", 1000)
scaffold.SetProp("MurckoRevComp.MaxIterPerMol", 1000)
scaffold.SetProp("MurckoRevComp.MaxIterPerMolPerNode", 1000)
scaffold.SetProp("MurckoRevComp.MaxIterPerMolPerThread", 1000)
scaffold.SetProp("MurckoRevComp.MaxIterPerMolPerCore", 1000)
scaffold.SetProp("MurckoRevComp.MaxIterPerMolPerThreadPerCore", 1000)
scaffold.SetProp("MurckoRevComp.MaxIterPerMolPerNodePerThread", 1000)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False
Output:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return result
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_traj = md.load(lig_str)
lig_traj = lig_traj.select('resname '+lig_str)
lig_traj = lig_traj.select('resname '+lig_str+' resname '+lig_str)
lig_traj = lig_traj.select('resname '+lig_str+' resname '+lig_str+' resname '+lig_str)
lig_traj = lig_traj.select('resname '+lig_str+' resname '+lig_str+' resname '+lig_str+' resname '+lig_str)
lig_traj = lig_traj.select('resname '+lig_str+' resname '+lig_str+' resname '+lig_str+' resname '+lig_str+' resname '+lig_str)
lig_traj = lig_traj.select('resname '+lig_str+' resname '+lig_str+' resname '+lig_str+' resname '+lig_str+' resname '+lig_str+' resname '+lig_str)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_traj = md.load(lig_str)
lig_traj.select()
lig_traj = lig_traj.select("resname "+lig_str)
lig_traj.compute_distances(traj)
lig_traj = lig_traj.select("resname "+lig_str)
lig_traj = lig_traj.select("distance 0.01")
lig_traj = lig_traj.select("resname "+lig_str)
lig_traj = lig_traj.select("distance 0.01")
lig_traj = lig_traj.select("resname "+lig_str)
lig_traj = lig_traj.select("distance 0.01")
lig_traj = lig_traj.select("resname "+lig_str)
lig_traj = lig_traj.select("distance 0.01")
lig_traj = lig_traj.select("resname "+lig_str)
lig_traj = lig_traj.select("distance 0.01")
lig_traj = lig_traj.select("resname "+lig_str)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_atoms = traj.resids[lig_str]
lig_atoms_center = lig_atoms.center()
lig_atoms_center = lig_atoms_center.to_frame()
lig_atoms_center = lig_atoms_center.to_array()
lig_atoms_center = lig_atoms_center[0]
lig_atoms_center = lig_atoms_center.reshape((-1,1))
lig_atoms_center = lig_atoms_center.tolist()
lig_atoms_center = lig_atoms_center[0]
lig_atoms_center = lig_atoms_center.reshape((-1,1))
lig_atoms_center = lig_atoms_center.tolist()
lig_atoms_center = lig_atoms_center[0]
lig_atoms_center = lig_atoms_center.reshape((-1,1))
lig_atoms_center = lig_atoms_center.tolist()
lig_atoms_center = lig_atoms_center[0]
lig_atoms_center = lig_atoms_center.reshape((-1,1))
lig_atoms_center = lig_atoms_center.tolist()
lig_atoms_center = lig_atoms_center[0]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_traj = md.load(lig_str)
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
lig_traj = lig_traj.to(fmt="mdtraj")
lig_traj = lig_traj[0]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_atoms = traj.top.atoms[lig_str]
lig_atoms_coords = lig_atoms.positions
lig_atoms_coords = lig_atoms_coords[np.where(np.logical_and(lig_atoms_coords[:,0] == lig_atoms_coords[:,1],lig_atoms_coords[:,0] == lig_atoms_coords[:,2]))[0]]
lig_atoms_coords = lig_atoms_coords[np.where(np.logical_and(lig_atoms_coords[:,0] == lig_atoms_coords[:,2],lig_atoms_coords[:,0] == lig_atoms_coords[:,1]))[0]]
lig_atoms_coords = lig_atoms_coords[np.where(np.logical_and(lig_atoms_coords[:,0] == lig_atoms_coords[:,1],lig_atoms_coords[:,0] == lig_atoms_coords[:,3]))[0]]
lig_atoms_coords = lig_atoms_coords[np.where(np.logical_and(lig_atoms_coords[:,0] == lig_atoms_coords[:,2],lig_atoms_coords[:,0] == lig_atoms_coords[:,4]))[0]]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False
Output:
'Constant' object has no attribute 'kind'
velocity_verlet_integration
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
[insert]
return x_traj, v_traj
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
for i in range(steps):
x_traj[i] = x0
v_traj[i] = v0
x_traj[i+1] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+1] = v0 + F(x_traj[i], v_traj[i])
x_traj[i+2] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+2] = v0 + F(x_traj[i], v_traj[i])
x_traj[i+3] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+3] = v0 + F(x_traj[i], v_traj[i])
x_traj[i+4] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+4] = v0 + F(x_traj[i], v_traj[i])
x_traj[i+5] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+5] = v0 + F(x_traj[i], v_traj[i])
x_traj[i+6] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+6] = v0 + F(x_traj[i], v_traj[i])
x_traj[i+7] = x0 + F(x_traj[i], v_traj[i])
v_traj[i+7] = v0 + F(x_traj[i], v_traj[i])
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
index 100000 is out of bounds for axis 0 with size 100000
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for step in range(1, steps):
x_traj[step] = x_traj[step-1] + dt*F(x_traj[step-1], v_traj[step-1])
v_traj[step] = v_traj[step-1] + dt*F(x_traj[step-1], v_traj[step-1])
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
Success
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v_traj[i-1])
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v_traj[i-1])
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
F() takes from 1 to 2 positional arguments but 3 were given
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
for i in range(steps):
x_traj[i] = x0
v_traj[i] = v0
x_traj[i+1] = x_traj[i] + F(x_traj[i], v_traj[i], v_traj[i+1]) * dt
v_traj[i+1] = v_traj[i] + F(x_traj[i], v_traj[i], v_traj[i+1]) * dt
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
F() takes from 1 to 2 positional arguments but 3 were given
import numpy as np
def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
Integrates given force field with Velocity-Verlet integration
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1, steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v0) + dt*F(x_traj[i-1], v_traj[i-1], v0)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v0) + dt*F(x_traj[i-1], v_traj[i-1], v0)
return x_traj, v_traj
import numpy as np
def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
"""
This function runs velocity verlet integration with the given force function F.
"""
x_traj = np.zeros(steps)
v_traj = np.zeros(steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(steps-1):
v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
x_traj[i+1] = x_traj[i] + v * dt
v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
return x_traj, v_traj
def F(q, k=2):
return -k*q
def U(q, k=2):
return 0.5 * k*q**2
x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)
Output:
F() takes from 1 to 2 positional arguments but 3 were given