markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the characters to and from integers. Encoding the characters as integers makes it easier to use as input in the network. | with open('chalo.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
chars = np.array([vocab_to_int[c] for c in text], dtype=np.int32) | intro-to-rnns/RNN Albert Camus.ipynb | javoweb/deep-learning | mit |
Making training and validation batches
Now I need to split up the data into batches, and into training and validation sets. I should be making a test set here, but I'm not going to worry about that. My test will be if the network can generate new text.
Here I'll make both input and target arrays. The targets are the sa... | def split_data(chars, batch_size, num_steps, split_frac=0.9):
"""
Split character data into training and validation sets, inputs and targets for each set.
Arguments
---------
chars: character array
batch_size: Size of examples in each of batch
num_steps: Number of sequence steps to kee... | intro-to-rnns/RNN Albert Camus.ipynb | javoweb/deep-learning | mit |
Building the model
Below is a function where I build the graph for the network. | def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2,
learning_rate=0.001, grad_clip=5, sampling=False):
# When we're using this network for sampling later, we'll be passing in
# one character at a time, so providing an option for that
if sampling == True:
... | intro-to-rnns/RNN Albert Camus.ipynb | javoweb/deep-learning | mit |
Hyperparameters
Here I'm defining the hyperparameters for the network.
batch_size - Number of sequences running through the network in one pass.
num_steps - Number of characters in the sequence the network is trained on. Larger is better typically, the network will learn more long range dependencies. But it takes lon... | batch_size = 100
num_steps = 100
lstm_size = 512
num_layers = 2
learning_rate = 0.001
keep_prob = 0.3 | intro-to-rnns/RNN Albert Camus.ipynb | javoweb/deep-learning | mit |
Training
Time for training which is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by save_every_n) I calculate the validation loss and save a checkpoint... | epochs = 300
# Save every N iterations
save_every_n = 100
train_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps)
model = build_rnn(len(vocab),
batch_size=batch_size,
num_steps=num_steps,
learning_rate=learning_rate,
lstm_size=l... | intro-to-rnns/RNN Albert Camus.ipynb | javoweb/deep-learning | mit |
Here, pass in the path to a checkpoint and sample from the network. | checkpoint = "checkpoints/i3000_l512_v2.497.ckpt"
samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Cuando en")
print(samp) | intro-to-rnns/RNN Albert Camus.ipynb | javoweb/deep-learning | mit |
copy over the example files to the working directory | path = 'data'
gpth = os.path.join('..', 'data', 'mf2005_test', 'test1ss.*')
for f in glob.glob(gpth):
shutil.copy(f, path) | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Load example dataset, skipping the SFR package | m = flopy.modflow.Modflow.load('test1ss.nam', version='mf2005', exe_name=exe_name,
model_ws=path, load_only=['ghb', 'evt', 'rch', 'dis', 'bas6', 'oc', 'sip', 'lpf']) | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Read pre-prepared reach and segment data into numpy recarrays using numpy.genfromtxt()
Reach data (Item 2 in the SFR input instructions), are input and stored in a numpy record array
http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html
This allows for reach data to be indexed by their variable names,... | rpth = os.path.join('..', 'data', 'sfr_examples', 'test1ss_reach_data.csv')
reach_data = np.genfromtxt(rpth, delimiter=',', names=True)
reach_data | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Segment Data structure
Segment data are input and stored in a dictionary of record arrays, which | spth = os.path.join('..', 'data', 'sfr_examples', 'test1ss_segment_data.csv')
ss_segment_data = np.genfromtxt(spth, delimiter=',', names=True)
segment_data = {0: ss_segment_data}
segment_data[0][0:1]['width1'] | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
define dataset 6e (channel flow data) for segment 1
dataset 6e is stored in a nested dictionary keyed by stress period and segment,
with a list of the following lists defined for each segment with icalc == 4
FLOWTAB(1) FLOWTAB(2) ... FLOWTAB(NSTRPTS)
DPTHTAB(1) DPTHTAB(2) ... DPTHTAB(NSTRPTS)
WDTHTAB(1) WDTHTAB(2) ... ... | channel_flow_data = {0: {1: [[0.5, 1.0, 2.0, 4.0, 7.0, 10.0, 20.0, 30.0, 50.0, 75.0, 100.0],
[0.25, 0.4, 0.55, 0.7, 0.8, 0.9, 1.1, 1.25, 1.4, 1.7, 2.6],
[3.0, 3.5, 4.2, 5.3, 7.0, 8.5, 12.0, 14.0, 17.0, 20.0, 22.0]]}} | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
define dataset 6d (channel geometry data) for segments 7 and 8
dataset 6d is stored in a nested dictionary keyed by stress period and segment,
with a list of the following lists defined for each segment with icalc == 4
FLOWTAB(1) FLOWTAB(2) ... FLOWTAB(NSTRPTS)
DPTHTAB(1) DPTHTAB(2) ... DPTHTAB(NSTRPTS)
WDTHTAB(1) WDTH... | channel_geometry_data = {0: {7: [[0.0, 10.0, 80.0, 100.0, 150.0, 170.0, 240.0, 250.0],
[20.0, 13.0, 10.0, 2.0, 0.0, 10.0, 13.0, 20.0]],
8: [[0.0, 10.0, 80.0, 100.0, 150.0, 170.0, 240.0, 250.0],
[25.0, 17.0, 13.0, 4.0, 0.0, 10... | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Define SFR package variables | nstrm = len(reach_data) # number of reaches
nss = len(segment_data[0]) # number of segments
nsfrpar = 0 # number of parameters (not supported)
nparseg = 0
const = 1.486 # constant for manning's equation, units of cfs
dleak = 0.0001 # closure tolerance for stream stage computation
istcb1 = 53 # flag for writing SFR outp... | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Instantiate SFR package
Input arguments generally follow the variable names defined in the Online Guide to MODFLOW | sfr = flopy.modflow.ModflowSfr2(m, nstrm=nstrm, nss=nss, const=const, dleak=dleak, istcb1=istcb1, istcb2=istcb2,
reach_data=reach_data,
segment_data=segment_data,
channel_geometry_data=channel_geometry_data,
... | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Plot the SFR segments
any column in the reach_data array can be plotted using the key argument | sfr.plot(key='iseg'); | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Check the SFR dataset for errors | chk = sfr.check()
m.external_fnames = [os.path.split(f)[1] for f in m.external_fnames]
m.external_fnames
m.write_input()
m.run_model() | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Look at results | sfr_outfile = os.path.join('..', 'data', 'sfr_examples', 'test1ss.flw')
names = ["layer", "row", "column", "segment", "reach", "Qin",
"Qaquifer", "Qout", "Qovr", "Qprecip", "Qet", "stage", "depth", "width", "Cond", "gradient"] | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Read results into numpy array using genfromtxt | sfrresults = np.genfromtxt(sfr_outfile, skip_header=8, names=names, dtype=None)
sfrresults[0:1] | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Read results into pandas dataframe
requires the pandas library | import pandas as pd
df = pd.read_csv(sfr_outfile, delim_whitespace=True, skiprows=8, names=names, header=None)
df | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Plot streamflow and stream/aquifer interactions for a segment | inds = df.segment == 3
ax = df.ix[inds, ['Qin', 'Qaquifer', 'Qout']].plot(x=df.reach[inds])
ax.set_ylabel('Flow, in cubic feet per second')
ax.set_xlabel('SFR reach') | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Look at stage, model top, and streambed top | streambed_top = m.sfr.segment_data[0][m.sfr.segment_data[0].nseg == 3][['elevup', 'elevdn']][0]
streambed_top
df['model_top'] = m.dis.top.array[df.row.values - 1, df.column.values -1]
fig, ax = plt.subplots()
plt.plot([1, 6], list(streambed_top), label='streambed top')
ax = df.ix[inds, ['stage', 'model_top']].plot(ax=... | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Get SFR leakage results from cell budget file | bpth = os.path.join('data', 'test1ss.cbc')
cbbobj = bf.CellBudgetFile(bpth)
cbbobj.list_records()
sfrleak = cbbobj.get_data(text=' STREAM LEAKAGE')[0]
sfrleak[sfrleak == 0] = np.nan # remove zero values | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Plot leakage in plan view | im = plt.imshow(sfrleak[0], interpolation='none', cmap='coolwarm', vmin = -3, vmax=3)
cb = plt.colorbar(im, label='SFR Leakage, in cubic feet per second'); | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
Plot total streamflow | sfrQ = sfrleak[0].copy()
sfrQ[sfrQ == 0] = np.nan
sfrQ[df.row.values-1, df.column.values-1] = df[['Qin', 'Qout']].mean(axis=1).values
im = plt.imshow(sfrQ, interpolation='none')
plt.colorbar(im, label='Streamflow, in cubic feet per second'); | examples/Notebooks/flopy3_sfrpackage_example.ipynb | mrustl/flopy | bsd-3-clause |
The first function we will use is aop_h5refl2array. This function is loaded into the cell below, we encourage you to look through the code to understand what it is doing -- most of these steps should look familiar to you from the first lesson. This function can be thought of as a wrapper to automate the steps required ... | def aop_h5refl2array(refl_filename):
"""aop_h5refl2array reads in a NEON AOP reflectance hdf5 file and returns
1. reflectance array (with the no data value and reflectance scale factor applied)
2. dictionary of metadata including spatial information, and wavelengths of the bands
--------
... | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
If you forget what this function does, or don't want to scroll up to read the docstrings, remember you can use help or ? to display the associated docstrings. | help(aop_h5refl2array)
aop_h5refl2array? | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Now that we have an idea of how this function works, let's try it out. First, define the path where th e reflectance data is stored and use os.path.join to create the full path to the data file. Note that if you want to run this notebook later on a different reflectance tile, you just have to change this variable. | # Note you will need to update this filepath for your local machine
serc_h5_tile = ('/Users/olearyd/Git/data/NEON_D02_SERC_DP3_368000_4306000_reflectance.h5') | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Now that we've specified our reflectance tile, we can call aop_h5refl2array to read in the reflectance tile as a python array called sercRefl , and the associated metadata into a dictionary sercMetadata | sercRefl,sercMetadata = aop_h5refl2array(serc_h5_tile) | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
We can use the shape method to see the dimensions of the array we read in. NEON tiles are (1000 x 1000 x # of bands), the number of bands may vary depending on the hyperspectral sensor used, but should be in the vicinity of 426. | sercRefl.shape | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
plot_aop_refl: plot a single band
Next we'll use the function plot_aop_refl to plot a single band of reflectance data. Read the Parameters section of the docstring to understand the required inputs & data type for each of these; only the band and spatial extent are required inputs, the rest are optional inputs that, if... | def plot_aop_refl(band_array,refl_extent,colorlimit=(0,1),ax=plt.gca(),title='',cbar ='on',cmap_title='',colormap='Greys'):
'''plot_refl_data reads in and plots a single band or 3 stacked bands of a reflectance array
--------
Parameters
--------
band_array: array of reflectance values, crea... | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Now that we have loaded this function, let's extract a single band from the SERC reflectance array and plot it: | sercb56 = sercRefl[:,:,55]
plot_aop_refl(sercb56,
sercMetadata['spatial extent'],
colorlimit=(0,0.3),
title='SERC Band 56 Reflectance',
cmap_title='Reflectance',
colormap='Greys_r') | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
RGB Plots - Band Stacking
It is often useful to look at several bands together. We can extract and stack three reflectance bands in the red, green, and blue (RGB) spectrums to produce a color image that looks like what we see with our eyes; this is your typical camera image. In the next part of this tutorial, we will l... | def stack_rgb(reflArray,bands):
import numpy as np
red = reflArray[:,:,bands[0]-1]
green = reflArray[:,:,bands[1]-1]
blue = reflArray[:,:,bands[2]-1]
stackedRGB = np.stack((red,green,blue),axis=2)
return stackedRGB | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
First, we will look at red, green, and blue bands, whos indices are defined below. To confirm that these band indices correspond to wavelengths in the expected portion of the spectrum, we can print out the wavelength values stored in metadata['wavelength']: | rgb_bands = (58,34,19)
print('Band 58 Center Wavelength = %.2f' %(sercMetadata['wavelength'][57]),'nm')
print('Band 33 Center Wavelength = %.2f' %(sercMetadata['wavelength'][33]),'nm')
print('Band 19 Center Wavelength = %.2f' %(sercMetadata['wavelength'][18]),'nm') | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Below we use stack_rgb to create an RGB array. Check that the dimensions of this array are as expected.
Data Tip: Checking the shape of arrays with .shape is a good habit to get into when creating your own workflows, and can be a handy tool for troubleshooting. | SERCrgb = stack_rgb(sercRefl,rgb_bands)
SERCrgb.shape | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
plot_aop_refl: plot an RGB band combination
Next, we can use the function plot_aop_refl, even though we have more than one band. This function only works for a single or 3-band array, so ensure the array you use has the proper dimensions before using. You do not need to specify the colorlimits as the matplotlib.pyplot ... | plot_aop_refl(SERCrgb,
sercMetadata['spatial extent'],
title='SERC RGB Image',
cbar='off') | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
You'll notice that this image is very dark; it is possible to make out some of the features (roads, buildings), but it is not ideal. Since colorlimits don't apply to 3-band images, we have to use some other image processing tools to enhance the visibility of this image.
Image Processing -- Contrast Stretch & Histogram... | from skimage import exposure
def plot_aop_rgb(rgbArray,ext,ls_pct=5,plot_title=''):
from skimage import exposure
pLow, pHigh = np.percentile(rgbArray[~np.isnan(rgbArray)], (ls_pct,100-ls_pct))
img_rescale = exposure.rescale_intensity(rgbArray, in_range=(pLow,pHigh))
plt.imshow(img_rescale,ext... | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
False Color Image - Color Infrared (CIR)
We can also create an image from bands outside of the visible spectrum. An image containing one or more bands outside of the visible range is called a false-color image. Here we'll use the green and blue bands as before, but we replace the red band with a near-infrared (NIR) ban... | CIRbands = (90,34,19)
print('Band 90 Center Wavelength = %.2f' %(sercMetadata['wavelength'][89]),'nm')
print('Band 34 Center Wavelength = %.2f' %(sercMetadata['wavelength'][33]),'nm')
print('Band 19 Center Wavelength = %.2f' %(sercMetadata['wavelength'][18]),'nm')
SERCcir = stack_rgb(sercRefl,CIRbands)
plot_aop_rgb(SE... | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Demo: Exploring Band Combinations Interactively
Now that we have made a couple different band combinations, we can demo a Python widget to explore different combinations of bands in the visible and non-visible portions of the spectrum. | from IPython.html.widgets import *
array = copy.copy(sercRefl)
metadata = copy.copy(sercMetadata)
def RGBplot_widget(R,G,B):
#Pre-allocate array size
rgbArray = np.zeros((array.shape[0],array.shape[1],3), 'uint8')
Rband = array[:,:,R-1].astype(np.float)
#Rband_clean = clean_band(Rband,Refl_... | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Demo: Interactive Linear Stretch & Equalization
Here is another widget to play around with, demonstrating how to interactively visualize linear contrast stretches with a variable percent. | rgbArray = copy.copy(SERCrgb)
def linearStretch(percent):
pLow, pHigh = np.percentile(rgbArray[~np.isnan(rgbArray)], (percent,100-percent))
img_rescale = exposure.rescale_intensity(rgbArray, in_range=(pLow,pHigh))
plt.imshow(img_rescale,extent=sercMetadata['spatial extent'])
plt.title('SERC RGB \n Line... | tutorials/Python/Hyperspectral/indices/NEON_AOP_Hyperspectral_Functions_Tiles_py/NEON_AOP_Hyperspectral_Functions_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Load a well from LAS
Use the from_las() method to load a well by passing a filename as a str.
This is really just a wrapper for lasio but instantiates a Header, Curves, etc. | from welly import Well
w = Well.from_las('data/P-129_out.LAS') | tutorial/06_Welly_and_LAS.ipynb | agile-geoscience/welly | apache-2.0 |
Save LAS file
We can write out to LAS with a simple command, passing the file name you want: | w.to_las('data/out.las') | tutorial/06_Welly_and_LAS.ipynb | agile-geoscience/welly | apache-2.0 |
Let's just check we get the same thing out of that file as we put in: | w.plot()
z = Well.from_las('data/out.las')
z.plot()
z.data['CALI'].plot()
| tutorial/06_Welly_and_LAS.ipynb | agile-geoscience/welly | apache-2.0 |
We don't get the striplog back (right hand side), but everything else looks good.
Header
Maybe should be called 'meta' as it's not really a header... | w.header
w.header.name
w.uwi | tutorial/06_Welly_and_LAS.ipynb | agile-geoscience/welly | apache-2.0 |
What?? OK, we need to load this file more carefully...
Coping with messy LAS
Some file headers are a disgrace:
# LAS format log file from PETREL
# Project units are specified as depth units
#==================================================================
~Version information
VERS. 2.0:
WRAP. YES:
#==============... | import welly
import re
def transform_ll(text):
def callback(match):
d = match.group(1).strip()
m = match.group(2).strip()
s = match.group(3).strip()
c = match.group(4).strip()
if c.lower() in ('w', 's') and d[0] != '-':
d = '-' + d
return ' '.join([d, m, ... | tutorial/06_Welly_and_LAS.ipynb | agile-geoscience/welly | apache-2.0 |
Ruta de la trayectoria
Escribir después de la diagonal, la ruta de la trayectoria seleccionada con el rmsd más bajo. | ruta=os.getcwd()
c=input('Nombre de la trayectoria para realizar el análisis... Ejemplo: run001....')
if os.path.isdir(c):
indir = '/'+c
print (indir)
ruta_old_traj=ruta+indir
print (ruta)
print (ruta_old_traj)
else:
print ('La carpetac'+c+' no existe...')
#
ruta_scripts=ruta+'/scripts_fimda'
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Convirtiendo la trayectoria DCD -> XTC
Los siguientes comandos convierten la trayectoria DCD contenida en la carpeta seleccionada a formato de XTC
Crear la nueva ruta para enviar las trayectorias convertidas | #Verificando que exista la nueva carpeta para la conversión de trayectorias
#nuevaruta = ruta+'/'+indir+'_XTC'
nuevaruta = ruta+indir+'_Dinamica'
print ( nuevaruta )
if not os.path.exists(nuevaruta):
os.makedirs(nuevaruta)
print ('Se ha creado la ruta ===>',nuevaruta)
else:
print ("La ruta "+nuevaruta+... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Realizando la conversión de la trayectoria |
print ('Obtenemos los archivos a convertir')
#Buscamos el archivo DCD, PDB y PSF para realizar las operaciones
for filename in os.listdir(ruta_old_traj):
if filename.endswith('.dcd'):
dcd_file=filename
if filename.endswith('.psf'):
psf_file=filename
if filename.endswith('.pdb'):
pdb... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Cargando la nueva trayectoria en VMD para su revisión | print ('Visualizando la nueva trayectoria')
file_psf=nuevaruta+'/'+psf_file
traj = nuevaruta+'/output.xtc'
!vmd $file_psf $traj | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando el RMSD con Gromacs 5
El siguiente script obtiene el RMSD de la trayectoria haciendo uso de Gromacs 5
Creando la carpeta de RMSD | ### Creando el directorio para el análisis del RMSD
#Verificando que exista la nueva carpeta para la conversión de trayectorias
#nuevaruta = ruta+'/'+indir+'_XTC'
ruta_rmsd = nuevaruta+'/rmsd'
print ( ruta_rmsd )
if not os.path.exists(ruta_rmsd):
os.makedirs(ruta_rmsd)
print ('Se ha creado la ruta ===>',ruta_r... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando el RMSD con la opción 3 'C-Alpha'
Select group for least squares fit
Group 3 ( C-alpha)
Select a group: 3
Selected 3: 'C-alpha'
Select group for RMSD calculation
Group 3 ( C-alpha)
Select a group: 3
Selected 3: 'C-alpha' |
print ('Ejecutando el análisis de rmsd...')
!echo 3 3 | g_rms -f ../output.xtc -s ../ionized.pdb -a avgrp.xvg | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando archivo rmsd.dat para su visualización en XMGRACE
Se genera el archivo de salida rmsd.dat, éste se deberá visualizar con Xmgrace para guardarlo en formato PNG. | #Inicializando vector
rmsd=[]
try:
archivo = open( 'rmsd.xvg' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
for linea in archivo.readlines():
fila = linea.strip()
sl = fila.split()
cadena=sl[0]
if (not '#' in cadena) and (not '@' in cadena):
num=float(sl[... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando el archivo rmsd_residue.dat para visualizar con xmgrace
Se crea el archivo rmsd_residue.dat formateado para su visualización en Xmgrace, en donde se deberá guardar como imagen PNG. | #Inicializando vector
rmsd_residue=[]
try:
archivo_rmsd = open( 'aver.xvg' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=1
for linea in archivo_rmsd.readlines():
fila = linea.strip()
sl = fila.split()
cadena=sl[0]
if (not '#' in cadena) and (not '@' in cadena):
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando archivo rmsd.dat para su visualización en Matplotlib
Se genera el gráfico de salida para matplotlib |
data_rmsd=np.loadtxt('rmsd.xvg',comments=['#', '@'])
#Engrosar marco
fig=pl.figure(figsize=(20, 12), dpi=100, linewidth=3.0)
ax = fig.add_subplot(111)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(4)
#Formateando los valores de los ejes
ax.yaxis.set_major_formatter(FormatStrFormat... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando archivo rmsd_residue.dat para su visualización en Matplotlib
Se genera el gráfico de salida para matplotlib | data_rmsd_res=np.loadtxt('aver.xvg',comments=['#', '@'])
#Engrosar marco
fig=pl.figure(figsize=(20, 12), dpi=100, linewidth=3.0)
ax = fig.add_subplot(111)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(4)
#Formateando los valores de los ejes
ax.yaxis.set_major_formatter(FormatSt... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
RMSF
Se crea una carpeta RMSF para guardar los archivos generados. | ### Creando el directorio para el análisis del RMSF
#Verificando que exista la nueva carpeta para la conversión de trayectorias
ruta_rmsf = nuevaruta+'/rmsf'
print ( ruta_rmsf )
if not os.path.exists(ruta_rmsf):
os.makedirs(ruta_rmsf)
print ('Se ha creado la ruta ===>',ruta_rmsf)
else:
print ("La ruta ... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando el RMSF con la opción 3 'C-Alpha' |
print ('Ejecutando el análisis de rmsf...')
!echo 3 | g_rmsf -f ../output.xtc -s ../ionized.pdb -oq bfac.pdb -o rmsf.xvg -res | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando archivo rmsf.dat para su visualización en XMGRACE
Se genera el archivo de salida rmsf.dat, éste se deberá visualizar con Xmgrace para guardarlo en formato PNG. | #Inicializando vector
rmsf=[]
rmsf_x=[]
rmsf_y=[]
try:
file_rmsf = open( 'rmsf.xvg' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
for linea in file_rmsf.readlines():
fila = linea.strip()
sl = fila.split()
cadena=sl[0]
if (not '#' in cadena) and (not '@' in cadena)... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando archivo rmsf.dat para su visualización en Matplotlib
Se genera el gráfico de salida para matplotlib | data_rmsf=np.loadtxt('rmsf.xvg',comments=['#', '@'])
#Engrosar marco
fig=pl.figure(figsize=(20, 12), dpi=100, linewidth=3.0)
ax = fig.add_subplot(111)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(4)
#Formateando los valores de los ejes
ax.yaxis.set_major_formatter(FormatStrFor... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
B-factors
Generando archivo para visualizarlo con XMGRACE | #Inicializando vector
bfactors=[]
try:
file_bfactor = open( 'bfac.pdb' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
for linea in file_bfactor.readlines():
fila = linea.strip()
sl = fila.split()
if (sl[0]=='ATOM'):
#print (sl[0])
idresidue=fila[23:26]
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Generando archivo para visualizar con Matplotlib | #Inicializando vector
bfactors=[]
try:
file_bfactor = open( 'bfac.pdb' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
print ('Residuo' + '\t'+'bfactor')
for linea in file_bfactor.readlines():
fila = linea.strip()
sl = fila.split()
if (sl[0]=='ATOM'):
#print (sl... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Secondary Structure
Se crea la carpeta para cálculo de la estructura | ### Creando el directorio para el análisis del RMSF
#Verificando que exista la nueva carpeta para la conversión de trayectorias
ruta_ss = nuevaruta+'/estructura'
print ( ruta_ss )
if not os.path.exists(ruta_ss):
os.makedirs(ruta_ss)
print ('Se ha creado la ruta ===>',ruta_ss)
else:
print ("La ruta "+ru... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando la estructura secundaria
Se necesita contar con el programa dssp en la ruta /usr/local/bin, el cual se enlaza con Gromacs 5 |
print ('Ejecutando el análisis de esctructura secundaria...')
!echo 5 | do_dssp -f ../output.xtc -s ../ionized.pdb -o sec_est.xpm -tu ns
print ('\n Convirtiendo el archivo a ps...')
!xpm2ps -f sec_est.xpm -by 6 -bx .1 -o est_sec.eps
print('\nConvirtiendo a png...')
!convert -density 600 est_sec.eps -resize 1024x... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
R-GYRATE
Se crea una carpeta rgiro para guardar los archivos generados. | ### Creando el directorio para el análisis del r-gyro
#Verificando que exista la nueva carpeta para la conversión de trayectorias
ruta_rgyro = nuevaruta+'/rgyro'
print ( ruta_rgyro )
if not os.path.exists(ruta_rgyro):
os.makedirs(ruta_rgyro)
print ('Se ha creado la ruta ===>',ruta_rgyro)
else:
print ("... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando el r-gyro con la opción (3) - C-alpha
Se calcula para los carbonos alfa. |
print ('Ejecutando el análisis de rgyro...')
!echo 3 | g_gyrate -f ../output.xtc -s ../ionized.pdb -o gyrate.xvg
| dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Generando el archivo rgyro.dat para su análisis con XMGRACE | #Inicializando vector
rgyro=[]
try:
file_rmsf = open( 'gyrate.xvg' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
for linea in file_rmsf.readlines():
fila = linea.strip()
sl = fila.split()
cadena=sl[0]
if (not '#' in cadena) and (not '@' in cadena):
num=flo... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ploteando el archivo gyrate.xvg con matplotlib | data_rgyro=np.loadtxt('gyrate.xvg',comments=['#', '@'])
#Engrosar marco
fig=pl.figure(figsize=(20, 12), dpi=100, linewidth=3.0)
ax = fig.add_subplot(111)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(4)
#Formateando los valores de los ejes
ax.yaxis.set_major_formatter(FormatStr... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
RMSD Helix Alfa
Para realizar este análisis se debe cargar el pdb original de la proteina que se encuentra en la carpeta 01_BUILD.
Cargarlo con VMD y dirigirse al Menú EXTENSIONS -> ANALYSIS -> SEQUENCE VIEWER, en la cual se tomará el rango de átomos del campo Struct (H), el cual se proporcionará de la forma "resid X1... | ### Creando el directorio para el análisis del RMSF
#Verificando que exista la nueva carpeta para la conversión de trayectorias
ruta_helix = nuevaruta+'/rmsd_helix'
print ( ruta_helix )
if not os.path.exists(ruta_helix):
os.makedirs(ruta_helix)
print ('Se ha creado la ruta ===>',ruta_helix)
else:
print... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Entrada de datos
Para la entrada se deberá dar con la opción "resid X to X". | num=input('Número de hélices con las que cuenta la proteína:')
print (num)
if (int(num)==1):
indices_ha1=input('Proporciona el rango de índices de la Hélice 1:')
print (indices_ha1)
r_helix_1=1
r_helix_2=0
r_helix_3=0
r_helix_4=0
if (int(num)==2):
indices_ha1=input('Proporciona el rango de ... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
SASA
Creando la estructura de carpeta para el cálculo | ### Creando el directorio para el análisis del SASA
### NOTA: se calcula con gromacs4 ya que arroja bien los resultados comparado con gromacs5
ruta_sasa = nuevaruta+'/sasa'
print ( ruta_sasa )
if not os.path.exists(ruta_sasa):
os.makedirs(ruta_sasa)
print ('Se ha creado la ruta ===>',ruta_sasa)
else:
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ejecutando el análisis de SASA con Gromacs4 |
print ('Ejecutando el análisis de sasa con Gromacs 4 utilizando la opción 1 (protein)...')
!echo 1 1 | /opt/gromacs4/bin/g_sas -f ../output.xtc -s ../ionized.pdb -o solven-accessible-surface.xvg -oa atomic-sas.xvg -or residue-sas.xvg | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando el archivo sasa_residuo.dat para salida con XMGRACE | #Inicializando vector
sasa_residuo=[]
try:
residue_sas = open( 'residue-sas.xvg' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
for linea in residue_sas.readlines():
fila = linea.strip()
sl = fila.split()
cadena=sl[0]
if (not '#' in cadena) and (not '@' in cadena)... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Cargando archivo residue-sas.xvg para su visualización en Matplotlib
Se genera el gráfico de salida para matplotlib | data_sasa_residue=np.loadtxt('residue-sas.xvg',comments=['#', '@'])
#Engrosar marco
fig=pl.figure(figsize=(20, 12), dpi=100, linewidth=3.0)
ax = fig.add_subplot(111)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(4)
#Formateando los valores de los ejes
ax.yaxis.set_major_format... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando el archivo sasa.dat para salida con XMGRACE | #Inicializando vector
sasa=[]
try:
sasafile = open( 'solven-accessible-surface.xvg' )
except IOError:
print ('No se pudo abrir el archivo o no existe·..')
i=0
for linea in sasafile.readlines():
fila = linea.strip()
sl = fila.split()
cadena=sl[0]
if (not '#' in cadena) and (not '@' in cadena)... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Cargando archivo solven-accessible-surface.xvg para graficar con Matplotlib | data_sasa=np.loadtxt('solven-accessible-surface.xvg',comments=['#', '@'])
#Engrosar marco
fig=pl.figure(figsize=(20, 12), dpi=100, linewidth=3.0)
ax = fig.add_subplot(111)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(4)
#Formateando los valores de los ejes
#ax.yaxis.set_major... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
MATRIZ DE RMSD | ### Creando el directorio para el análisis del SASA
### NOTA: se calcula con gromacs4 ya que arroja bien los resultados comparado con gromacs5
ruta_m_rmsd = nuevaruta+'/matriz'
print ( ruta_m_rmsd )
if not os.path.exists(ruta_m_rmsd):
os.makedirs(ruta_m_rmsd)
print ('Se ha creado la ruta ===>',ruta_m_rmsd)
e... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Cargar el scrit rmsd_matrix con vmd en la nueva trayectoria
Arrancar VMD, dirigirse al manú Extensions -> Tk Console, copiar y ejecutar la siguiente secuencia de comandos:
tcl
source rmsd_matrix.tcl
rmsd_matrix -mol top -seltext "name CA" -frames all -o salida.dat
exit | #Arrancando VMD para cargar el script rmsd_matrix.tcl
!vmd 100.dcd $file_psf
ruta_matriz=os.getcwd()
if os.path.isfile('salida.dat'):
print ('El archivo salida.dat existe')
else:
print ('El archivo salida.dat no existe.. ejecutar desde MATRIZ DE RMSD...') | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Graficando el archivo de salida | #Creando el gráfico
data_matriz=np.loadtxt('salida.dat',comments=['#', '@'])
print(data_matriz.shape)
pl.figure(figsize=(20, 12), dpi=100)
imgplot = pl.imshow(data_matriz, origin='lower', cmap=pl.cm.Greens, interpolation='nearest')
#imgplot = pl.imshow(data_matriz, origin='lower', cmap=pl.cm.coolwarm, interpolation='... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Matriz de distancia mínima | ### Creando el directorio para el análisis del RMSF
#Verificando que exista la nueva carpeta para la conversión de trayectorias
ruta_matriz_dm = nuevaruta+'/matriz_dm'
print ( ruta_matriz_dm )
if not os.path.exists(ruta_matriz_dm):
os.makedirs(ruta_matriz_dm)
print ('Se ha creado la ruta ===>',ruta_matriz_dm)
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando la matriz de distancia mínima
Seleccionar el backbone (opción 4) | !echo 4 | g_mdmat -f ../output.xtc -s ../ionized.pdb -mean average -frames frames -dt 10000 | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Generando los archivos para visualizarlos | !xpm2ps -f frames.xpm -o frames.eps
!xpm2ps -f average.xpm -o average.eps
print('\nConvirtiendo a png...')
!convert -density 600 frames.eps -resize 1024x1024 frames.png
!convert -density 600 average.eps -resize 1024x1024 average.png
print ('Cargando el archivo average...')
Image(filename='average.png', width=800) | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Free Energy
Para el cálculo de la energía libre se requiere el valor mínimo y máximo del RMSD y del radio de gyro, así como el valor de la temperatura a la cual se realizó la simulación. Estos datos son de entrada para el script del cálculo del mismo. | ### Creando el directorio para el análisis de la libre energía
ruta_f_energy = nuevaruta+'/free_energy'
print ( ruta_f_energy )
if not os.path.exists(ruta_f_energy):
os.makedirs(ruta_f_energy)
print ('Se ha creado la ruta ===>',ruta_f_energy)
else:
print ("La ruta "+ruta_f_energy+" existe..!!!")
prin... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando el rmsd y el r-gyro para obtener el mínimo y máximo de cada uno de ellos. | print ('Ejecutando el análisis de rmsd...')
!echo 3 3 | g_rms -f ../output.xtc -s ../ionized.pdb -a avgrp.xvg
print ('Ejecutando el análisis de rgyro...')
!echo 3 | g_gyrate -f ../output.xtc -s ../ionized.pdb -o gyrate.xvg | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Escribiendo script a /tmp para utilizar en el cálculo | print ('\nCopiando el archivo generateFES.py a '+ruta_f_energy)
source_file=ruta_scripts+'/free_energy/generateFES.py'
dest_file=ruta_f_energy+'/generateFES.py'
shutil.copy(source_file,dest_file)
#Cambiando permisos de ejecución
!chmod +x generateFES.py | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Realizando los cálculos para la Free Energy |
#Cargando valores del RMSD
data_rmsd=np.loadtxt('rmsd.xvg',comments=['#', '@'])
#Cargnaod valores del R-GYRO
data_rgyro=np.loadtxt('gyrate.xvg',comments=['#', '@'])
#Obteniendo los valores máximo y mínimo del rmsd
min_rmsd=np.amin(data_rmsd[:,1])
max_rmsd=np.amax(data_rmsd[:,1])
print ('Minimo RMSD=>',min_rmsd)
pri... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ploteando con GNUplot | # This loads the magics for gnuplot
%load_ext gnuplot_kernel
#Configurando la salida para GNUplot
%gnuplot inline pngcairo transparent enhanced font "arial,20" fontscale 1.0 size 1280,960; set zeroaxis;;
%%gnuplot
set output "free_energy.png"
set palette model RGB
set palette defined ( 0 '#000090',\
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
PCA | ### Creando el directorio para el análisis del PCA
ruta_pca = nuevaruta+'/pca'
print ( ruta_pca )
if not os.path.exists(ruta_pca):
os.makedirs(ruta_pca)
print ('Se ha creado la ruta ===>',ruta_pca)
else:
print ("La ruta "+ruta_pca+" existe..!!!")
print ( 'Nos vamos a ....', ruta_pca )
os.chdir( ruta_... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Una vez calculada la matriz el eigenvalues y eigenvectors sirven de entrada para generar el pca.
El siguiente comando representa el movimiento del primer y segundo eigenvector. | !echo 1 1 | g_anaeig -s ../ionized.pdb -f ../output.xtc -v eigenvectors.trr -eig eigenvalues.xvg -first 1 -last 2 -2d 2dproj_1_2.xvg
#pcaX, pcaY=np.loadtxt('2dproj_1_2.xvg',comments=['#', '@'], unpack=True)
data_pca=np.loadtxt('2dproj_1_2.xvg',comments=['#', '@'])
#Obteniendo los valores máximo y mínimo del pca
min_p... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ploteando el archivo con gnuplot | #Volver a cargar el kernel de gnuplot para limpiar su buffer
%reload_ext gnuplot_kernel
#Configurando la salida para GNUplot
%gnuplot inline pngcairo transparent enhanced font "arial,20" fontscale 1.0 size 1280,960; set zeroaxis;;
%%gnuplot
set output "pca.png"
set palette model RGB
set palette defined ( 0 '#000090'... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Análisis de puentes di sulfuro
Este aplica para 2 puente, para lo cual se utiliza el software HTMD. | from htmd import * | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando la ruta
Ruta para el análisis de los datos. | ### Creando el directorio para el análisis de los RMSD de los puentes
ruta_rmsd_diedros = nuevaruta+'/rmsd_diedros'
print ( ruta_rmsd_diedros )
if not os.path.exists(ruta_rmsd_diedros):
os.makedirs(ruta_rmsd_diedros)
print ('Se ha creado la ruta ===>',ruta_rmsd_diedros)
else:
print ("La ruta "+ruta_rm... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Cargando de los puentes di sulfuro
Para este análisis se deberá revisar el archivo psf_charmm.tcl de la carpeta 01_BUILD, en el cual se tiene la definición de los puentes como la siguiente:
patch DISU A:4 A:22
patch DISU A:8 A:18
El número del puente se determinará de acuerdo al orden en que se encuentran... | # Cargando la molécula
mol = Molecule('../ionized.pdb')
# Solicitando los datos de entrada
px1l=input('Índice del DB1 izquierdo:')
px1r=input('Índice del DB1 derecho:')
px2l=input('Índice del DB2 izquierdo:')
px2r=input('Índice del DB2 derecho:')
revisa1=1
revisa2=1 | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Obteniendo los índices de los puentes |
if (revisa1>0):
#Obteniendo lado izquierdo del DB1
x1l_name=mol.get('name','resname CYS and noh and resid '+px1l)
x1l_index=mol.get('index','resname CYS and noh and resid '+px1l)
x1l_resid=mol.get('resid','resname CYS and noh and resid '+px1l)
#Obteniendo lado derecho del DB1
x1r_name=mol.get('... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ordenando los puentes de la forma ['N', 'CA', 'CB', 'SG', 'SG', 'CB', 'CA', 'N'] | #Generando el DB1 completo ordenado
filas=8
col=2
DB1_i=[]
DB1_N=[]
DB2_i=[]
DB2_N=[]
DB3_i=[]
DB3_N=[]
for i in range(0,filas):
DB1_N.append([' '])
DB1_i.append(['0'])
DB2_N.append([' '])
DB2_i.append(['0'])
DB3_N.append([' '])
DB3_i.append(['0'])
if (revisa1>0):
#Cargando índices para el ... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creando los archivos tcl para el cálculo del RMSD de los puentes
Se crean los archivos de salida en formato tcl. | if (revisa1>0):
#Creando script para DB1_x1l
psf=ruta_old_traj+'/'+psf_file
dcd=ruta_old_traj+'/'+dcd_file
print(psf)
f1 = open('DB1_x1l.tcl', 'w')
print(f1)
f1.write('set psfFile '+ psf+' \n')
f1.write('set dcdFile '+ dcd+' \n')
f1.write('\nmol load psf $psfFile dcd $dcdFile\n')
... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ejecutando los archivos rmsd en tcl con vmd
Ejecutando los archivos en VMD | if (revisa1>0):
#Calculando con VMD rmsd DB1 X1L
!vmd -dispdev text < DB1_x1l.tcl
#Calculando con VMD DB1 X2L
!vmd -dispdev text < DB1_x2l.tcl
#Calculando con VMD DB1 X3M
!vmd -dispdev text < DB1_x3m.tcl
#Calculando con VMD DB1 X2R
!vmd -dispdev text < DB1_x2r.tcl
#Calculando con VMD... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Generando los gráficos RMSD en matplotlib |
escale_y=[]
fig = pl.figure(figsize=(25,8))
fig.subplots_adjust(hspace=.4, wspace=0.3)
#Formateando los valores de los ejes
#Engrosando marcos
ax = fig.add_subplot(2,5,1)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(3)
ax = fig.add_subplot(2,5,2)
for axis in ['top','bottom','left','... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
FREE ENERGY DIHEDRAL INTRAMOLECULAR
Se calculan las distancias de los ángulos diedros para el cálculo de la free energy intramolecular | ### Creando el directorio para el análisis de las distancias de enlace de los puentes
ruta_diedros = nuevaruta+'/diedros_intra'
print ( ruta_diedros )
if not os.path.exists(ruta_diedros):
os.makedirs(ruta_diedros)
print ('Se ha creado la ruta ===>',ruta_diedros)
else:
print ("La ruta "+ruta_diedros+" ... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Creación de los archivos tcl para el cálculo de los ángulos diedros | psf=ruta_old_traj+'/'+psf_file
dcd=ruta_old_traj+'/'+dcd_file
if (revisa1>0):
#Creando script para DB1_x1l
d1 = open('dihed_DB1_x1l.tcl', 'w')
print(d1)
d1.write('set psfFile '+ psf+' \n')
d1.write('set dcdFile '+ dcd+' \n')
d1.write('\nmol load psf $psfFile dcd $dcdFile\n')
d1.write('set... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Ejecutando los archivos de los ángulos diedros tcl generados con VMD | if (revisa1>0):
#Calculando con VMD rmsd DB1 X1L
!vmd -dispdev text < dihed_DB1_x1l.tcl
#Calculando con VMD DB1 X2L
!vmd -dispdev text < dihed_DB1_x2l.tcl
#Calculando con VMD DB1 X3M
!vmd -dispdev text < dihed_DB1_x3m.tcl
#Calculando con VMD DB1 X2R
!vmd -dispdev text < dihed_DB1_x2r.tcl... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Calculando la Free Energy Intramolecular para el Puente 1 | if (revisa1>0):
#Cargando valores del DB1_X1L
data_db1_x1l=np.loadtxt('dihed_db1_x1l.dat',comments=['#', '@'])
#Cargando valores del DB1_X1R
data_db1_x1r=np.loadtxt('dihed_db1_x1r.dat',comments=['#', '@'])
#Obteniendo los valores máximo y mínimo del DB1_X1L
min_x1l=np.amin(data_db1_x1l[:,1]... | dinamica-2puentes.ipynb | lguarneros/fimda | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.