markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Ploteando con GNUPLOT el Puente 1
# This loads the magics for gnuplot %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 "db1_xl1_vs_xr1.png" set palette model RGB set palette defined ( 0 '#000090',\ ...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Calculando la Free Energy intramolecular para el Puente 2
if (revisa2>0): #Cargando valores del DB2_X1L data_db2_x1l=np.loadtxt('dihed_db2_x1l.dat',comments=['#', '@']) #Cargando valores del DB1_X1R data_db2_x1r=np.loadtxt('dihed_db2_x1r.dat',comments=['#', '@']) #Obteniendo los valores máximo y mínimo del DB2_X1L min_db2_x1l=np.amin(data_db2_x1l[...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Ploteando con GNUPLOT el Puente 2
# This loads the magics for gnuplot %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 "db2_xl1_vs_xr1.png" set palette model RGB set palette defined ( 0 '#000090',\ ...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Free Energy Intermolecular
############################################ #### Intermolecular DB1- DB2 - X1L ############################################ #Creando el DB1-DB2-X1L !paste db1_x1l.dat db2_x1l.dat > DB1_DB2_x1l.dat print('Minimo DB1-X1L=>',min_x1l) print('Máximo DB1-X1L=>',max_x1l) print('Minimo DB2-X1L=>',min_db2_x1l) print('Máximo D...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Ploteando la Free Energy Intermolecular puentes DB1 y DB2
# This loads the magics for gnuplot %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 "DB1_DB2_X1L.png" set palette model RGB set palette defined ( 0 '#000090',\ ...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Calcular los histogramas de los diedros
hist_escale_y=[] fig = pl.figure(figsize=(25,8)) fig.subplots_adjust(hspace=.4, wspace=.3) #subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) #left = 0.125 # the left side of the subplots of the figure #right = 0.9 # the right side of the subplots of the figure #bottom = 0.1 ...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Ángulos de Enlace de los puentes Intermolecular
### Creando el directorio para el análisis de las distancias de enlace de los puentes INTERMOLECULAR ruta_bonds_puentes = nuevaruta+'/bonds_puentes' print ( ruta_bonds_puentes ) if not os.path.exists(ruta_bonds_puentes): os.makedirs(ruta_bonds_puentes) print ('Se ha creado la ruta ===>',ruta_bonds_puentes) el...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Copiando el archivo de generación de FES
print ('\nCopiando el archivo generateFES.py a '+ruta_bonds_puentes) source_file=ruta_scripts+'/free_energy/generateFES.py' dest_file=ruta_bonds_puentes+'/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
Generando los archivos Tcl para el cálculo de los ángulos.
psf=ruta_old_traj+'/'+psf_file dcd=ruta_old_traj+'/'+dcd_file print ('Puente DB1=>',DB1_N) print ('Puente DB1=>',DB1_i) print ('Puente DB2=>',DB2_N) print ('Puente DB2=>',DB2_i) puente=2 if (int(puente)==2): #Creando script para Bond X1 Left b1 = open('bond_DB1_left.tcl', 'w') print(b1) b1.write('se...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Ejecutando los archivos tcl generados con VMD
#Calculando con VMD bond DB1 Left !vmd -dispdev text < bond_DB1_left.tcl #Calculando con VMD bond DB1 Right !vmd -dispdev text < bond_DB1_right.tcl #Calculando con VMD bond DB2 Left !vmd -dispdev text < bond_DB2_left.tcl #Calculando con VMD bond DB2 Right !vmd -dispdev text < bond_DB2_right.tcl
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Calculando la Free Energy de los Bonds de los puentes
#Cargando valores del DB1 data_bond_db1_left=np.loadtxt('bond_db1_left.dat',comments=['#', '@']) #Cargando valores del DB1_X1R data_bond_db1_right=np.loadtxt('bond_db1_right.dat',comments=['#', '@']) #Obteniendo los valores máximo y mínimo del DB1 Left min_bond1_left=np.amin(data_bond_db1_left[:,1]) max_bond1_left=np....
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Ploteando la Free Energy de los ángulos con gnuplot
# This loads the magics for gnuplot %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 "db1_a1_a2.png" set palette model RGB set palette defined ( 0 '#000090',\ ...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Calculando los histogramas de los bonds
bonds_escale_y=[] #Cargando valores del DB1 data_h_db1_left=np.loadtxt('bond_DB1_left.dat',comments=['#', '@']) data_h_db1_right=np.loadtxt('bond_DB1_right.dat',comments=['#', '@']) #Cargando valores del DB2 data_h_db2_left=np.loadtxt('bond_DB2_left.dat',comments=['#', '@']) data_h_db2_right=np.loadtxt('bond_DB2_right....
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Generación de clusters Crear la nueva ruta para calcular los clusters
### Creando el directorio para el análisis de los puentes ruta_clusters = nuevaruta+'/clusters' print ( ruta_clusters ) if not os.path.exists(ruta_clusters): os.makedirs(ruta_clusters) print ('Se ha creado la ruta ===>',ruta_clusters) else: print ("La ruta "+ruta_clusters+" existe..!!!") print ( 'Nos...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Calculando los clusters con la opción (1= Protein)
!echo 1 1 | g_cluster -f ../output.xtc -s ../ionized.pdb -method gromos -cl out.pdb -g out.log -cutoff 0.2
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Cargando los clusters para su visualización en VMD Se cargan los clusters en VMD y se guardan sus coordenadas para cada uno de ellos haciendo uso de VMD
!vmd out.pdb
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
colorByRMSF Creando la carpeta para salida de datos
### Creando el directorio para el análisis de colorByRMSF ruta_colorByRMSF = nuevaruta+'/colorByRMSF' print ( ruta_colorByRMSF ) if not os.path.exists(ruta_colorByRMSF): os.makedirs(ruta_colorByRMSF) print ('Se ha creado la ruta ===>',ruta_colorByRMSF) else: print ("La ruta "+ruta_colorByRMSF+" existe...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Copiando el archivo a la carpeta de datos
print ('\nCopiando el archivo colorByRMSF.vmd a '+ruta_colorByRMSF) source_file=ruta_scripts+'/colorByRMSF/colorByRMSF.vmd' dest_file=ruta_colorByRMSF+'/colorByRMSF.vmd' shutil.copy(source_file,dest_file)
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Calculando el RMSF para el análisis de la proteína con la opción (1) Protein
print ('Ejecutando el análisis de rmsf...') !echo 1 | g_rmsf -f ../output.xtc -s ../ionized.pdb -oq bfac.pdb -o rmsf.xvg #Calculando el mínimo y máximo del rmsf #Cargando valores del RMSF data_rmsf_gcolor=np.loadtxt('rmsf.xvg',comments=['#', '@']) #Obteniendo los valores máximo y mínimo del RMSF min_rmsf_gcolor=np.a...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Cargar el scrit colorByRMSF.vmd en VMD Arrancar VMD, dirigirse al menú Extensions -> Tk Console, copiar y ejecutar la siguiente secuencia de comandos en el cual pondremos los valores del Mínimo_RMSF y Máximo_RMSF calculado en la celda anterior: tcl source colorByRMSF.vmd colorByRMSF top rmsf.xvg Mínimo_RMSF Máximo_RMS...
# Cargando el pdb con VMD !vmd ../ionized.pdb
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Graficando B-Factors con Chimera
print ( 'Nos vamos a ....', ruta_colorByRMSF ) os.chdir( ruta_colorByRMSF )
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Adecuando archivo bfac.pdb para obtener la columna de B-factors
#Inicializando vector rmsf=[] rmsf_x=[] rmsf_y=[] try: file_Bfactor = open( 'bfac.pdb' ) new_bfactor=open('bfac_new.pdb','w') 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() cadena=sl[0]...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Revisando la estructura del archivo generado. Revisar que los campos se encuentren completamente alineados en la estructura de los campos. Guardar y salir.
!gedit bfac_new.pdb
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Generando el archivo de Bfactors para todos los átomos FALTA ADECUAR PARA SACAR EL MAYOR POR RESIDUO
#Inicializando vector bfactors_color=[] try: file_bfactor_color = open( 'bfac_new.pdb' ) except IOError: print ('No se pudo abrir el archivo o no existe·..') i=0 for linea in file_bfactor_color.readlines(): fila = linea.strip() sl = fila.split() if (sl[0]=='ATOM'): #print (sl[0]) ...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Cargando el archivo pdb con Chimera para realizar la coloración de Bfactors
!chimera bfac_new.pdb
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Instrucciones para generar la imagen de B-factors ESTABLECER EL MODO DE VISUALIZACIÓN 1. Seleccionar del menú principal Presets -> Interactive 2 (all atoms). 2. Seleccionar del menú principal Actions -> Surface -> Show. 3. Ajustar el tamaño de la ventana principal. 4. Ajustar el tamaño y posición de la figura haciend...
##Cargando la imagen generada print ('Cargando el archivo...') Image(filename='image.png')
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Graficando SASA
### Creando el directorio para el análisis del SASA en el directorio de VMD print ('Nos vamos a ', ruta) os.chdir( ruta ) output_find=!find /usr/local -maxdepth 2 -type d -name vmd print (output_find) ruta_vmd=output_find[0] print (ruta_vmd) ruta_vmd_sasa = ruta_vmd+'/plugins/noarch/tcl/iceVMD1.0' print ( ruta_vmd_sa...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Coloreando el SASA Arrancar VMD. Ventana vmdICE Dirigirse al menú Extensions -> Analysis -> vmdICE, se presentará una ventana y se deberán cambiar los valores de los siguientes campos: 1. To: Colocar el rango máximo de frames de la trayectoria. 2. Selection for Calculation: agregar a chain A and protein. 3. Pulsar en ...
!vmd ../ionized.psf ../output.xtc
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Restaurando configuración default de VMD
#Borrando los archivos del vmd !rm -r $ruta_vmd_sasa
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Graficando el RGYRO
### Creando el directorio para la graficación del rgyro ruta_gyroColor = nuevaruta+'/color_rgyro' print ( ruta_gyroColor ) if not os.path.exists(ruta_gyroColor): os.makedirs(ruta_gyroColor) print ('Se ha creado la ruta ===>',ruta_gyroColor) else: print ("La ruta "+ruta_gyroColor+" existe..!!!") pr...
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Coloreando el RGYRO Arrancar VMD, dirigirse al manú Extensions -> Tk Console, copiar y ejecutar la siguiente secuencia de comandos: tcl source colorRgyro.tcl CAMBIAR EL COLOR DE FONDO Dirigirse al menú Graphics -> Colors , y realizar las siguientes selecciones: 1. Categories seleccionar Display 2. Names seleccionar ...
!vmd ../ionized.psf ../output.xtc
dinamica-2puentes.ipynb
lguarneros/fimda
gpl-3.0
Import section specific modules:
import matplotlib.image as mpimg from IPython.display import Image from astropy.io import fits import aplpy #Disable astropy/aplpy logging import logging logger0 = logging.getLogger('astropy') logger0.setLevel(logging.CRITICAL) logger1 = logging.getLogger('aplpy') logger1.setLevel(logging.CRITICAL) from IPython.displ...
6_Deconvolution/6_4_residuals_and_iqa.ipynb
landmanbester/fundamentals_of_interferometry
gpl-2.0
6.4 Residuals and Image Quality<a id='deconv:sec:iqa'></a> Using CLEAN or another deconvolution methods produces 'nicer' images than the dirty image (except when deconvolution gets out of control). What it means for an image to be 'nicer' is not a well defined metric, in fact it is almost completely undefined. When we ...
def generalGauss2d(x0, y0, sigmax, sigmay, amp=1., theta=0.): """Return a normalized general 2-D Gaussian function x0,y0: centre position sigmax, sigmay: standard deviation amp: amplitude theta: rotation angle (deg)""" #norm = amp * (1./(2.*np.pi*(sigmax*sigmay))) #normalization factor norm ...
6_Deconvolution/6_4_residuals_and_iqa.ipynb
landmanbester/fundamentals_of_interferometry
gpl-2.0
Figure: residual image and sky model after 1000 deconvolution iterations. The residual image has been over-deconvolved leading to noise components being added to the sky model. The second question of what makes a good image is why we still use subjective opinion. If we consider the realistic case of imaging and deconvo...
fig = plt.figure(figsize=(16, 7)) gc1 = aplpy.FITSFigure('../data/fits/deconv/KAT-7_6h60s_dec-30_10MHz_10chans_uniform_n100-dirty.fits', \ figure=fig, subplot=[0.1,0.1,0.35,0.8]) gc1.show_colorscale(vmin=-1.5, vmax=3., cmap='viridis') gc1.hide_axis_labels() gc1.hide_tick_labels() plt.title('Dirt...
6_Deconvolution/6_4_residuals_and_iqa.ipynb
landmanbester/fundamentals_of_interferometry
gpl-2.0
Left: dirty image from a 6 hour KAT-7 observation at a declination of $-30^{\circ}$. Right: deconvolved image. The deconvolved image does not have the same noisy PSF structures around the sources that the dirty image does. We could say that these imaging artefacts are localized and related to the PSF response to bright...
#load deconvolved image fh = fits.open('../data/fits/deconv/KAT-7_6h60s_dec-30_10MHz_10chans_uniform_n100-image.fits') deconvImg = fh[0].data #load residual image fh = fits.open('../data/fits/deconv/KAT-7_6h60s_dec-30_10MHz_10chans_uniform_n100-residual.fits') residImg = fh[0].data peakI = np.max(deconvImg) print 'Pea...
6_Deconvolution/6_4_residuals_and_iqa.ipynb
landmanbester/fundamentals_of_interferometry
gpl-2.0
Method 1 will always result in a lower dynamic range than Method 2 as the deconvoled image includes the sources where method 2 only uses the residuals. Method 3 will result in a dynamic range which varies depending on the number of pixels sampled and which pixels are sampled. One could imagine an unlucky sampling where...
fig = plt.figure(figsize=(8, 7)) gc1 = aplpy.FITSFigure('../data/fits/deconv/KAT-7_6h60s_dec-30_10MHz_10chans_uniform_n100-residual.fits', \ figure=fig) gc1.show_colorscale(vmin=-1.5, vmax=3., cmap='viridis') gc1.hide_axis_labels() gc1.hide_tick_labels() plt.title('Residual Image') gc1.add_color...
6_Deconvolution/6_4_residuals_and_iqa.ipynb
landmanbester/fundamentals_of_interferometry
gpl-2.0
Split the data into features (x) and target (y, the last column in the table) Remember you can cast the results into an numpy array and then slice out what you want
x = myarray[:,:11] y = myarray[:,11:]
class10/donow/kate_bennion_donow_10.ipynb
ledeprogram/algorithms
gpl-3.0
Create a decision tree with the data
from sklearn.tree import DecisionTreeClassifier dt = DecisionTreeClassifier() dt = dt.fix(x,y)
class10/donow/kate_bennion_donow_10.ipynb
ledeprogram/algorithms
gpl-3.0
Run 10-fold cross validation on the model
from sklearn.cross_validation import cross_val_score scores = cross_val_score(dt,x,y2,cv=10)
class10/donow/kate_bennion_donow_10.ipynb
ledeprogram/algorithms
gpl-3.0
If you have time, calculate the feature importance and graph based on the code in the slides from last class Use this tip for getting the column names from your cursor object
plt.plot(dt.feature_importances_,'o') plt.ylim(0,1)
class10/donow/kate_bennion_donow_10.ipynb
ledeprogram/algorithms
gpl-3.0
Initialize ASCAT reader
ascat_data_folder = os.path.join('/media/sf_R', 'Datapool_processed', 'WARP', 'WARP5.5', 'IRMA1_WARP5.5_P2', 'R1', '080_ssm', 'netcdf') ascat_grid_folder = os.path.join('/media/sf_R', 'Datapool_processed', 'WARP', 'ancillary', 'warp5_grid') ascat_reader...
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
Initialize ISMN reader
ismn_data_folder = os.path.join('/media/sf_D', 'ISMN', 'data') ismn_reader = ISMN_Interface(ismn_data_folder)
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
Create the variable jobs which is a list containing either cell numbers (for a cell based process) or grid point index information tuple(gpi, longitude, latitude). For ISMN gpi is replaced by idx which is an index used to read time series of variables such as soil moisture. DO NOT CHANGE the name jobs because it will b...
jobs = [] ids = ismn_reader.get_dataset_ids(variable='soil moisture', min_depth=0, max_depth=0.1) for idx in ids: metadata = ismn_reader.metadata[idx] jobs.append((idx, metadata['longitude'], metadata['latitude']))
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
Create the variable save_path which is a string representing the path where the results will be saved. DO NOT CHANGE the name save_path because it will be searched during the parallel processing!
save_path = os.path.join('/media/sf_D', 'validation_framework', 'test_ASCAT_ISMN')
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
Create the validation object.
datasets = {'ISMN': {'class': ismn_reader, 'columns': ['soil moisture'], 'type': 'reference', 'args': [], 'kwargs': {}}, 'ASCAT': {'class': ascat_reader, 'columns': ['sm'], 'type': 'other', 'args': [], 'kwargs': {}, 'grids_compatible': False, ...
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
If you decide to use the ipython parallel processing to perform the validation please ADD the start_processing function to your code. Then move to pytesmo.validation_framework.start_validation, change the path to your setup code and start the validation.
def start_processing(job): try: return process.calc(job) except RuntimeError: return process.calc(job)
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
If you chose to perform the validation normally then please ADD the uncommented main method to your code.
# if __name__ == '__main__': # # from pytesmo.validation_framework.results_manager import netcdf_results_manager # # for job in jobs: # results = process.calc(job) # netcdf_results_manager(results, save_path)
docs/setup_validation_ASCAT_ISMN.ipynb
christophreimer/pytesmo
bsd-3-clause
Objectives Choose two players who reach same scores(stop forcely) Choose two players who play the same time(stop forcely) Calculate their statistical result(variance, average, mode, etc.) Visualization in terms of HR, Emotional, Collection of Emoji According to the movement of birds(HR of players) to find out their si...
# all the function we need to parse the data def extract_split_data(data): content = re.findall("\[(.*?)\]", data) timestamps = [] values = [] for c in content[0].split(","): c = (c.strip()[1:-1]) if len(c)>21: x, y = c.split("#") values.append(int(x)) ...
affectiveComputing/ComparisonAnalysis.ipynb
Ivanhehe/Sharings
mit
Heart rates analysis from player1
# playing span s1 = player1['TimeStarted'].values[0] e1 = player1['TimeEnded'].values[-1] sx1 = player1['TimeStarted'].values[-1] diff1 = (de_timestampe(e1) - de_timestampe(s1)) # difference in seconds diffx1 = (de_timestampe(e1) - de_timestampe(sx1)) # get timestamp and HR times1 = [] rates1 = [] flags = [0] pos = 0 ...
affectiveComputing/ComparisonAnalysis.ipynb
Ivanhehe/Sharings
mit
Emoj collection analysis from player1
e_timestamp = [] for session in player1['EmojiTimestamps']: e_timestamp += get_track_emoj(session) xi = [] track = [] for i,t in enumerate(times1): for e in e_timestamp: if abs((de_timestampe(e)-de_timestampe(t)).seconds) < 1: xi.append(i) track.append(in...
affectiveComputing/ComparisonAnalysis.ipynb
Ivanhehe/Sharings
mit
Heart rates analysis from player2
# playing span s2 = player2['TimeStarted'].values[0] e2 = player2['TimeEnded'].values[-1] sx2 = player2['TimeStarted'].values[-1] diff2 = (de_timestampe(e2) - de_timestampe(s2)) # difference in second diffx2 = (de_timestampe(e2) - de_timestampe(sx2)) # difference in seconds # get timestamp and HR times2 = [] rates2 = ...
affectiveComputing/ComparisonAnalysis.ipynb
Ivanhehe/Sharings
mit
Playing Pattern
m1 = player1["Movement"] m2 = player2["Movement"] print (m1[:5]) print (m2[:5]) y1 = de_movement(m1) y2 = de_movement(m2) fig, ax = plt.subplots(figsize=(15,8)) plt.title("Comparison between birds") #plt.scatter(timestamps1, rates1) plt.plot(y1, color="b", label="player1", alpha=.6) plt.plot(y2, color="g", label="pla...
affectiveComputing/ComparisonAnalysis.ipynb
Ivanhehe/Sharings
mit
Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is: $$ \psi_{n_x,n_y}(x,y) = \frac{2}{L} \sin{\left( \frac{n_x \pi x}{L} \right)} \sin{\left( \frac{n_y \pi y}{L} \right)} $$ This is a scalar field and $n_x$ and $n_y$ are quantum numbers that measure the level of excitation in the x and ...
def well2d(x, y, nx, ny, L=1.0): """Compute the 2d quantum well wave function.""" return 2/L*np.sin(nx*np.pi*x/L)*np.sin(ny*np.pi*y/L) psi = well2d(np.linspace(0,1,10), np.linspace(0,1,10), 1, 1) assert len(psi)==10 assert psi.shape==(10,)
assignments/assignment05/MatplotlibEx03.ipynb
CalPolyPat/phys202-2015-work
mit
The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visualizations of 2d scalar fields. Use the Matplotlib documentation to learn how to use these functions along with the numpy.meshgrid function to visualize the above wavefunction: Use $n_x=3$, $n_y=2$ and $L=0$. Use the lim...
f=plt.figure(figsize=(10,10)) x=np.linspace(0,1,100) y=np.linspace(0,1,100) xx, yy=np.meshgrid(x, y) z=well2d(xx,yy,3,2,1) plt.contourf(x,y,z,50,cmap=plt.cm.get_cmap("hot")) plt.colorbar(label=r"$\Psi (x,y)$") plt.xlabel("X Position") plt.ylabel("Y Position") plt.title("The wavefunction of a 2D inifinite well") assert...
assignments/assignment05/MatplotlibEx03.ipynb
CalPolyPat/phys202-2015-work
mit
Next make a visualization using one of the pcolor functions:
f=plt.figure(figsize=(10,10)) x=np.linspace(0,1,100) y=np.linspace(0,1,100) xx, yy=np.meshgrid(x, y) z=well2d(xx,yy,3,2,1) plt.pcolor(x,y,z,cmap="RdBu") plt.colorbar(label=r"$\Psi (x,y)$") plt.xlabel("X Position") plt.ylabel("Y Position") plt.title("The wavefunction of a 2D inifinite well") assert True # use this cell...
assignments/assignment05/MatplotlibEx03.ipynb
CalPolyPat/phys202-2015-work
mit
Now we instantiate a model instance: a 10x10 grid, with an 80% change of an agent being placed in each cell, approximately 20% of agents set as minorities, and agents wanting at least 3 similar neighbors.
model = SchellingModel(10, 10, 0.8, 0.2, 3)
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
We want to run the model until all the agents are happy with where they are. However, there's no guarentee that a given model instantiation will ever settle down. So let's run it for either 100 steps or until it stops on its own, whichever comes first:
while model.running and model.schedule.steps < 100: model.step() print(model.schedule.steps) # Show how many steps have actually run
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
The model has a DataCollector object, which checks and stores how many agents are happy at the end of each step. It can also generate a pandas DataFrame of the data it has collected:
model_out = model.datacollector.get_model_vars_dataframe() model_out.head()
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
Finally, we can plot the 'happy' series:
model_out.happy.plot()
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
For testing purposes, here is a table giving each agent's x and y values at each step.
x_positions = model.datacollector.get_agent_vars_dataframe() x_positions.head()
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
Effect of Homophily on segregation Now, we can do a parameter sweep to see how segregation changes with homophily. First, we create a function which takes a model instance and returns what fraction of agents are segregated -- that is, have no neighbors of the opposite type.
from mesa.batchrunner import BatchRunner def get_segregation(model): ''' Find the % of agents that only have neighbors of their same type. ''' segregated_agents = 0 for agent in model.schedule.agents: segregated = True for neighbor in model.grid.neighbor_iter(agent.pos): ...
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
Now, we set up the batch run, with a dictionary of fixed and changing parameters. Let's hold everything fixed except for Homophily.
parameters = {"height": 10, "width": 10, "density": 0.8, "minority_pc": 0.2, "homophily": range(1,9)} model_reporters = {"Segregated_Agents": get_segregation} param_sweep = BatchRunner(SchellingModel, parameters, iterations=10, max_steps=200, model_r...
examples/Schelling/.ipynb_checkpoints/analysis-checkpoint.ipynb
projectmesa/mesa-examples
apache-2.0
Exploring the TF-Hub CORD-19 Swivel Embeddings <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/hub/tutorials/cord_19_embeddings"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blan...
import functools import itertools import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd import tensorflow.compat.v1 as tf tf.disable_eager_execution() tf.logging.set_verbosity('ERROR') import tensorflow_datasets as tfds import tensorflow_hub as hub try: from google.colab impo...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
Analyze the embeddings Let's start off by analyzing the embedding by calculating and plotting a correlation matrix between different terms. If the embedding learned to successfully capture the meaning of different words, the embedding vectors of semantically similar words should be close together. Let's take a look at ...
# Use the inner product between two embedding vectors as the similarity measure def plot_correlation(labels, features): corr = np.inner(features, features) corr /= np.max(corr) sns.heatmap(corr, xticklabels=labels, yticklabels=labels) with tf.Graph().as_default(): # Load the module query_input = tf.placehol...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
We can see that the embedding successfully captured the meaning of the different terms. Each word is similar to the other words of its cluster (i.e. "coronavirus" highly correlates with "SARS" and "MERS"), while they are different from terms of other clusters (i.e. the similarity between "SARS" and "Spain" is close to ...
#@title Set up the dataset from TFDS class Dataset: """Build a dataset from a TFDS dataset.""" def __init__(self, tfds_name, feature_name, label_name): self.dataset_builder = tfds.builder(tfds_name) self.dataset_builder.download_and_prepare() self.feature_name = feature_name self.label_name = label...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
Training a citaton intent classifier We'll train a classifier on the SciCite dataset using an Estimator. Let's set up the input_fns to read the dataset into the model
def preprocessed_input_fn(for_eval): data = THE_DATASET.get_data(for_eval=for_eval) data = data.map(THE_DATASET.example_fn, num_parallel_calls=1) return data def input_fn_train(params): data = preprocessed_input_fn(for_eval=False) data = data.repeat(None) data = data.shuffle(1024) data = data.batch(batc...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
Let's build a model which use the CORD-19 embeddings with a classification layer on top.
def model_fn(features, labels, mode, params): # Embed the text embed = hub.Module(params['module_name'], trainable=params['trainable_module']) embeddings = embed(features['feature']) # Add a linear layer on top logits = tf.layers.dense( embeddings, units=THE_DATASET.num_classes(), activation=None) pr...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
Train and evaluate the model Let's train and evaluate the model to see the performance on the SciCite task
estimator = tf.estimator.Estimator(functools.partial(model_fn, params=params)) metrics = [] for step in range(0, STEPS, EVAL_EVERY): estimator.train(input_fn=functools.partial(input_fn_train, params=params), steps=EVAL_EVERY) step_metrics = estimator.evaluate(input_fn=functools.partial(input_fn_eval, params=params...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
We can see that the loss quickly decreases while especially the accuracy rapidly increases. Let's plot some examples to check how the prediction relates to the true labels:
predictions = estimator.predict(functools.partial(input_fn_predict, params)) first_10_predictions = list(itertools.islice(predictions, 10)) display_df( pd.DataFrame({ TEXT_FEATURE_NAME: [pred['features'].decode('utf8') for pred in first_10_predictions], LABEL_NAME: [THE_DATASET.class_names()[pred['label...
site/en-snapshot/hub/tutorials/cord_19_embeddings.ipynb
tensorflow/docs-l10n
apache-2.0
Problem 2 Using optimization solve the following equation: $$ \int_{-\infty}^x e^{-s^2} = 0.25 $$ 1D, convex, root-fniding
from scipy.integrate import quad import numpy as np x = newton(lambda x: quad(lambda y: np.exp(-y**2), -np.inf,x)[0] - 0.25, x0=0) print('x = {:.3f}'.format(x))
unit_11/hw_2017/problem_set_1.ipynb
whitead/numerical_stats
gpl-3.0
Problem 3 Find the maximum value of $g(x,y)$ where both $x$ and $y$ are between 0 and 1: $$ g(x,y) = \exp\left(-\frac{(x - 0.2)^2}{4}\right)\exp\left(-\frac{(x - y)^2}{5}\right) \exp\left(-\frac{(y - 0.7)^2}{4}\right) $$ 2D, convex, minimization
from scipy.optimize import minimize def obj(z): x = z[0] y = z[1] #return negative to allow max return -np.exp(-(x - 0.2)**2 / 4) * np.exp(-(x - y)**2 / 5) * np.exp(-(y - 0.7)**2 / 4) result = minimize(obj, x0=[0.5, 0.5], bounds=[(0, 1), (0,1)]) print('The minimizing x,y are x = {:.3f}, y = {:.3f}'.form...
unit_11/hw_2017/problem_set_1.ipynb
whitead/numerical_stats
gpl-3.0
Problem 4 $x$ and $y$ lie inside a disc with radius $3 \geq r \geq 5$. Find the point within the disc that minimizes the distance to (-6, 2). Modify the code to add your optimum point along with an entry in the legend. Complete the problem in Cartesian coordinates.
import matplotlib.pyplot as plt import matplotlib #use nice style with larger plot size matplotlib.style.use(['seaborn-white', 'seaborn-talk']) #set-up our points theta = np.linspace(0, 2 * np.pi, 100) r = np.repeat(3, len(theta)) #plot the disc boundaries plt.polar(theta, r, linestyle='--', color='#333333') plt.polar...
unit_11/hw_2017/problem_set_1.ipynb
whitead/numerical_stats
gpl-3.0
2D, convex, constrained, minimization. Constraints: $$ x^2 + y^2 - 3^2 \geq 0 $$ $$ -x^2 - y^2 + 5^2 \geq 0 $$
#Optimization Code ### BEGIN SOLUTION ineq_1 = lambda x: x[0]**2 + x[1]**2 - 3**2 ineq_2 = lambda x: -(x[0]**2 + x[1]**2 - 5**2) constraints = [{'type':'ineq', 'fun':ineq_1}, {'type':'ineq', 'fun':ineq_2}] result = minimize(lambda x: (x[0] - -6)**2 + (x[1] - 2)**2, constraints=constraints, x0=[0,0]) ...
unit_11/hw_2017/problem_set_1.ipynb
whitead/numerical_stats
gpl-3.0
Problem 5 Repeat the previous problem except now you must minimize the distance to three points: (-6, 2), (4,2), (-7, 0)
#optimization ### BEGIN SOLUTION def obj(x): s = 0 for p in [[-6,2], [4,2], [-7, 0]]: s += (x[0] - p[0])**2 + (x[1] - p[1])**2 return s result = minimize(obj, constraints=constraints, x0=[0,0]) print('The minimum coordinates are x = {:.3f} and y = {:.3f}'.format(*result.x)) ### END SOLUTION #Your ...
unit_11/hw_2017/problem_set_1.ipynb
whitead/numerical_stats
gpl-3.0
Problem 6 The free energy of mixing is given by the following equation in phase equilibrium theory: $$ \Delta F = x\ln x + (1 - x)\ln (1 - x) + \chi_{AB}x(1 - x) + \beta x $$ where x is the mole fraction of component A, $\chi_{AB}$ is the interaction parameter, and $\beta$ is a system correction. Find the mole fraction...
#make a plot to see if it's convex chi = 3 x = np.linspace(0.01,0.99, 100) F = x * np.log(x) + (1 - x) * np.log(1 - x) + chi * x * (1 - x) + 0.05 * x plt.plot(x,F) #looks nonconvex from scipy.optimize import basinhopping def f(x): return x * np.log(x) + (1 - x) * np.log(1 - x) + 3 * x * (1 - x) + 0.05 * x result...
unit_11/hw_2017/problem_set_1.ipynb
whitead/numerical_stats
gpl-3.0
And more precisely, we are using the following versions:
print(nltk.__version__) print(cltk.__version__) print(MyCapytain.__version__)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Let's grab some text To start with, we need some text from which we'll try to extract named entities using various methods and libraries. There are several ways of doing this e.g.: 1. copy and paste the text from Perseus or the Latin Library into a text document, and read it into a variable 2. load a text from one of t...
my_passage = "urn:cts:latinLit:phi0448.phi001.perseus-lat2"
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
With this information, we can query a CTS API and get some information about this text. For example, we can "discover" its canonical text structure, an essential information to be able to cite this text.
# We set up a resolver which communicates with an API available in Leipzig resolver = HttpCTSResolver(CTS("http://cts.dh.uni-leipzig.de/api/cts/")) # We require some metadata information textMetadata = resolver.getMetadata("urn:cts:latinLit:phi0448.phi001.perseus-lat2") # Texts in CTS Metadata have one interesting pro...
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
But we can also query the same API and get back the text of a specific text section, for example the entire book 1. To do so, we need to append the indication of the reference scope (i.e. book 1) to the URN.
my_passage = "urn:cts:latinLit:phi0448.phi001.perseus-lat2:1"
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
So we retrieve the first book of the De Bello Gallico by passing its CTS URN (that we just stored in the variable my_passage) to the CTS API, via the resolver provided by MyCapytains:
passage = resolver.getTextualNode(my_passage)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
At this point the passage is available in various formats: text, but also TEI XML, etc. Thus, we need to specify that we are interested in getting the text only:
de_bello_gallico_book1 = passage.export(Mimetypes.PLAINTEXT)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Let's check that the text is there by printing the content of the variable de_bello_gallico_book1 where we stored it:
print(de_bello_gallico_book1)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
The text that we have just fetched by using a programming interface (API) can also be viewed in the browser. Or even imported as an iframe into this notebook!
from IPython.display import IFrame IFrame('http://cts.dh.uni-leipzig.de/read/latinLit/phi0448/phi001/perseus-lat2/1', width=1000, height=350)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Let's see how many words (tokens, more properly) there are in Caesar's De Bello Gallico I:
len(de_bello_gallico_book1.split(" "))
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Very simple baseline Now let's write what in NLP jargon is called a baseline, that is a method for extracting named entities that can serve as a term of comparison to evaluate the accuracy of other methods. Baseline method: - cycle through each token of the text - if the token starts with a capital letter it's a name...
"T".istitle() "t".istitle() # we need a list to store the tagged tokens tagged_tokens = [] # tokenisation is done by using the string method `split(" ")` # that splits a string upon white spaces for n, token in enumerate(de_bello_gallico_book1.split(" ")): if(token.istitle()): tagged_tokens.append((toke...
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Let's a have a look at the first 50 tokens that we just tagged:
tagged_tokens[:50]
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
For convenience we can also wrap our baseline code into a function that we call extract_baseline. Let's define it:
def extract_baseline(input_text): """ :param input_text: the text to tag (string) :return: a list of tuples, where tuple[0] is the token and tuple[1] is the named entity tag """ # we need a list to store the tagged tokens tagged_tokens = [] # tokenisation is done by using the string method ...
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
And now we can call it like this:
tagged_tokens_baseline = extract_baseline(de_bello_gallico_book1) tagged_tokens_baseline[-50:]
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
We can modify slightly our function so that it prints the snippet of text where an entity is found:
def extract_baseline(input_text): """ :param input_text: the text to tag (string) :return: a list of tuples, where tuple[0] is the token and tuple[1] is the named entity tag """ # we need a list to store the tagged tokens tagged_tokens = [] # tokenisation is done by using the string method ...
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
NER with CLTK The CLTK library has some basic support for the extraction of named entities from Latin and Greek texts (see CLTK's documentation). The current implementation (as of version 0.1.47) uses a lookup-based method. For each token in a text, the tagger checks whether that token is contained within a predefined ...
%%time tagged_text_cltk = tag_ner('latin', input_text=de_bello_gallico_book1)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Let's have a look at the ouput, only the first 10 tokens (by using the list slicing notation):
tagged_text_cltk[:10]
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
The output looks slightly different from the one of our baseline function (the size of the tuples in the list varies). But we can write a function to fix this, we call it reshape_cltk_output:
def reshape_cltk_output(tagged_tokens): reshaped_output = [] for tagged_token in tagged_tokens: if(len(tagged_token)==1): reshaped_output.append((tagged_token[0], "O")) else: reshaped_output.append((tagged_token[0], tagged_token[1])) return reshaped_output
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
We apply this function to CLTK's output:
tagged_text_cltk = reshape_cltk_output(tagged_text_cltk)
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
And the resulting output looks now ok:
tagged_text_cltk[:20]
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Now let's compare the two list of tagged tokens by using a python function called zip, which allows us to read multiple lists simultaneously:
list(zip(tagged_text_baseline[:20], tagged_text_cltk_reshaped[:20]))
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
But, as you can see, the two lists are not aligned. This is due to how the CLTK function tokenises the text. The comma after "tres" becomes a token on its own, whereas when we tokenise by white space the comma is attached to "tres" (i.e. "tres,"). A solution to this is to pass to the tag_ner function the text already t...
tagged_text_cltk = reshape_cltk_output(tag_ner('latin', input_text=de_bello_gallico_book1.split(" "))) list(zip(tagged_text_baseline[:20], tagged_text_cltk[:20]))
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
NER with NLTK
stanford_model_italian = "/opt/nlp/stanford-tools/stanford-ner-2015-12-09/classifiers/ner-ita-nogpe-noiob_gaz_wikipedia_sloppy.ser.gz" ner_tagger = StanfordNERTagger(stanford_model_italian) tagged_text_nltk = ner_tagger.tag(de_bello_gallico_book1.split(" "))
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Let's have a look at the output
tagged_text_nltk[:20]
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Wrap up At this point we can "compare" the output of the three different methods we used, again by using the zip function.
list(zip(tagged_text_baseline[:20], tagged_text_cltk[:20], tagged_text_nltk[:20])) for baseline_out, cltk_out, nltk_out in zip(tagged_text_baseline[:20], tagged_text_cltk[:20], tagged_text_nltk[:20]): print("Baseline: %s\nCLTK: %s\nNLTK: %s\n"%(baseline_out, cltk_out, nltk_out))
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0
Excercise Extract the named entities from the English translation of the De Bello Gallico book 1. The CTS URN for this translation is urn:cts:latinLit:phi0448.phi001.perseus-eng2:1. Modify the code above to use the English model of the Stanford tagger instead of the italian one. Hint:
stanford_model_english = "/opt/nlp/stanford-tools/stanford-ner-2015-12-09/classifiers/english.muc.7class.distsim.crf.ser.gz"
participants_notebooks/Sunoikisis - Named Entity Extraction 1b-G3.ipynb
mromanello/SunoikisisDC_NER
gpl-3.0