markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Using a utility we provide, we will create a sparse matrix representation of the documents. This is the same utility function you used during the previous assignment on k-means with text data.
wiki = wiki.add_row_number() tf_idf, map_word_to_index = sframe_to_scipy(wiki, 'tf_idf') map_index_to_word = dict([[map_word_to_index[i], i] for i in map_word_to_index.keys()])
_____no_output_____
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
As in the previous assignment, we will normalize each document's TF-IDF vector to be a unit vector.
%%time tf_idf = normalize(tf_idf)
CPU times: user 4.56 ms, sys: 733 µs, total: 5.29 ms Wall time: 5.8 ms
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
We can check that the length (Euclidean norm) of each row is now 1.0, as expected.
for i in range(5): doc = tf_idf[i] print(np.linalg.norm(doc.todense()))
1.0 1.0 0.9999999999999997 1.0000000000000007 1.0
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
EM in high dimensionsEM for high-dimensional data requires some special treatment: * E step and M step must be vectorized as much as possible, as explicit loops are dreadfully slow in Python. * All operations must be cast in terms of sparse matrix operations, to take advantage of computational savings enabled by spars...
%%time from sklearn.cluster import KMeans np.random.seed(5) num_clusters = 25 # Use scikit-learn's k-means to simplify workflow #kmeans_model = KMeans(n_clusters=num_clusters, n_init=5, max_iter=400, random_state=1, n_jobs=-1) # uncomment to use parallelism -- may break on your installation kmeans_model = KMeans(n_...
/home/offbeat/Environments/turicreate/lib/python3.7/site-packages/sklearn/cluster/_kmeans.py:974: FutureWarning: 'n_jobs' was deprecated in version 0.23 and will be removed in 0.25. " removed in 0.25.", FutureWarning)
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Initializing cluster weights**We will initialize each cluster weight to be the proportion of documents assigned to that cluster by k-means above.
%%time num_docs = tf_idf.shape[0] weights = [] for i in range(num_clusters): # Compute the number of data points assigned to cluster i: num_assigned = np.sum(cluster_assignment == i) # YOUR CODE HERE w = float(num_assigned) / num_docs weights.append(w) np.sum(cluster_assignment == 1)
_____no_output_____
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Initializing covariances**To initialize our covariance parameters, we compute $\hat{\sigma}_{k, j}^2 = \sum_{i=1}^{N}(x_{i,j} - \hat{\mu}_{k, j})^2$ for each feature $j$. For features with really tiny variances, we assign 1e-8 instead to prevent numerical instability. We do this computation in a vectorized fashion i...
covs = [] for i in range(num_clusters): member_rows = tf_idf[cluster_assignment==i] cov = (member_rows.multiply(member_rows) - 2*member_rows.dot(diag(means[i]))).sum(axis=0).A1 / member_rows.shape[0] \ + means[i]**2 cov[cov < 1e-8] = 1e-8 covs.append(cov)
_____no_output_____
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Running EM**Now that we have initialized all of our parameters, run EM.
out = EM_for_high_dimension(tf_idf, means, covs, weights, cov_smoothing=1e-10) out['loglik']
_____no_output_____
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
Interpret clustering results In contrast to k-means, EM is able to explicitly model clusters of varying sizes and proportions. The relative magnitude of variances in the word dimensions tell us much about the nature of the clusters.Write yourself a cluster visualizer as follows. Examining each cluster's mean vector, ...
# Fill in the blanks def visualize_EM_clusters(tf_idf, means, covs, map_index_to_word): print('') print('==========================================================') num_clusters = len(means) for c in range(num_clusters): print('Cluster {0:d}: Largest mean parameters in cluster '.format(c))...
========================================================== Cluster 0: Largest mean parameters in cluster Word Mean Variance minister 7.57e-02 7.42e-03 election 5.89e-02 3.21e-03 party 5.89e-02 2.61e-03 liberal 2.93e-02 4.55e-03 elected 2.91e-02 8.95e-04 =========...
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Quiz Question**. Select all the topics that have a cluster in the model created above. [multiple choice]- Baseball- Basketball- Soccer/Football- Music- Politics- Law- Finance Comparing to random initialization Create variables for randomly initializing the EM algorithm. Complete the following code block.
np.random.seed(5) # See the note below to see why we set seed=5. num_clusters = len(means) num_docs, num_words = tf_idf.shape random_means = [] random_covs = [] random_weights = [] for k in range(num_clusters): # Create a numpy array of length num_words with random normally distributed values. # Use the ...
_____no_output_____
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Quiz Question**: Try fitting EM with the random initial parameters you created above. (Use `cov_smoothing=1e-5`.) Store the result to `out_random_init`. What is the final loglikelihood that the algorithm converges to?
out_random_init = EM_for_high_dimension(tf_idf, random_means, random_covs, random_weights, cov_smoothing=1e-5) print("{:e}".format(out_random_init['loglik'][-1]))
2.362457e+09
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Quiz Question:** Is the final loglikelihood larger or smaller than the final loglikelihood we obtained above when initializing EM with the results from running k-means?
out['loglik']
_____no_output_____
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
**Quiz Question**: For the above model, `out_random_init`, use the `visualize_EM_clusters` method you created above. Are the clusters more or less interpretable than the ones found after initializing using k-means?
# YOUR CODE HERE. Use visualize_EM_clusters, which will require you to pass in tf_idf and map_index_to_word. visualize_EM_clusters(tf_idf, out_random_init['means'], out_random_init['covs'], map_index_to_word)
========================================================== Cluster 0: Largest mean parameters in cluster Word Mean Variance she 2.24e-02 3.54e-03 award 1.53e-02 1.18e-03 music 1.45e-02 1.29e-03 university 1.43e-02 6.32e-04 law 1.27e-02 2.59e-03 =========...
MIT
4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb
anilk991/Coursera-Machine-Learning-Specialization-UW
Example notebook for the functions contained in cry_file_readwrite.py Crystal_input class
from crystal_functions.file_readwrite import Crystal_input
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Create a crystal input object from blocks
geom_block = ['MGO BULK - GEOMETRY TEST\n', 'CRYSTAL\n', '0 0 0\n', '225\n', '4.217\n', '2\n', '12 0. 0. 0.\n', '8 0.5 0.5 0.5\n', 'END\n'] bs_block = ['BASISSET\n','POB-DZVP\n'] func_block = ['DFT\n', 'B...
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Create a crystal input object from an existing input file
mgo_input = Crystal_input().from_file('data/mgo.d12') mgo_input.geom_block
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Crystal_output class
from crystal_functions.file_readwrite import Crystal_output
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
3D system
mgo_output = Crystal_output().read_cry_output('data/mgo_optgeom.out') mgo_output
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Functions and properties
#Final energy print("Final energy = %s eV \n" % mgo_output.get_final_energy()) #Fermi energy print("Fermi energy = %s eV \n" % mgo_output.get_fermi_energy()) #Primitive lattice print("Primitive lattice \n %s \n" % mgo_output.get_primitive_lattice()) #Reciprocal lattice print("Reciprocal lattice \n %s \n" % mgo_outpu...
Final energy = -7495.341792877063 eV Fermi energy = -4.13671240282 eV Primitive lattice [[0. 2.1085 2.1085] [2.1085 0. 2.1085] [2.1085 2.1085 0. ]] Reciprocal lattice [[-1.48996571 1.48996571 1.48996571] [ 1.48996571 -1.48996571 1.48996571] [ 1.48996571 1.48996571 -1.48996571]] Band gap =...
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
0D system
co_output = Crystal_output().read_cry_output('data/co.out') #Final energy print("Final energy = %s eV \n" % co_output.get_final_energy()) #Fermi energy print("Fermi energy = %s eV \n" % co_output.get_fermi_energy()) #Primitive lattice print("Primitive lattice \n %s \n" % co_output.get_primitive_lattice()) #Reciproca...
Final energy = -3037.8807073392627 eV Fermi energy = -7.247937617924001 eV WARNING: no lattice vectors found in the output file. lattice = [] Primitive lattice None Reciprocal lattice None Band gap = 10.9012 eV Last geometry = [[[12.0, 0.0, 0.0], [0.0, 12.0, 0.0], [0.0, 0.0, 12.0]], [6, 8], [[-0.0637262...
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Properties_output class
from crystal_functions.file_readwrite import Properties_output
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Bands
mgo_bands = Properties_output() mgo_bands.read_cry_bands('../examples/data/mgo_BAND_dat.BAND') mgo_bands
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Doss
mgo_doss = Properties_output() mgo_doss = mgo_doss.read_cry_doss('data/mgo_DOSS_dat.DOSS') mgo_doss
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
write_cry_input function
from crystal_functions.file_readwrite import Crystal_input from crystal_functions.file_readwrite import write_crystal_input
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Use existing input file
#Read the original input mgo_original_input = Crystal_input().from_file('data/mgo.d12') #Write the input new_input_name = 'data/mgo_from_file.d12' write_crystal_input(new_input_name,crystal_input=mgo_original_input)
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Build from blocks
#Define the blocks geom_block = ['MGO BULK - GEOMETRY TEST\n', 'CRYSTAL\n', '0 0 0\n', '225\n', '4.217\n', '2\n', '12 0. 0. 0.\n', '8 0.5 0.5 0.5\n', 'END\n'] bs_block = ['12 4\n', '0 0 8 2.0 1.0\n', ' 68370.0 0.0002226\n', ' 9661.0 0.001901\n', ' 2041.0 0.011042\n', ' 529.6 0.05005\n', ' 159.17...
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
write_cry_properties function bands from k points coordinates
from crystal_functions.file_readwrite import Properties_input from crystal_functions.file_readwrite import write_properties_input #Create the bands input object bands_input = Properties_input() #Add the newk block to the input object bands_input.make_newk_block(12,24) #Prepare the band_block k_path = [[0,0,0],[0.5,0,...
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
bands from pymatgen HighSymmKpath object
from pymatgen.symmetry.bandstructure import HighSymmKpath from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from crystal_functions.file_readwrite import write_properties_input from crystal_functions.file_readwrite import Crystal_output from crystal_functions.file_readwrite import Properties_input from crystal_...
_____no_output_____
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
doss
from crystal_functions.file_readwrite import write_properties_input from crystal_functions.file_readwrite import Properties_input #Create the doss input object doss_input = Properties_input() #Add the newk block to the input object doss_input.make_newk_block(12,24) #Prepare the doss_block doss_input.make_doss_block(...
NEWK 12 24 1 0 DOSS 0 200 -1 -1 2 12 1 -0.18374651800348382 0.5512395540104514 END
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
pdoss (atoms)
from crystal_functions.file_readwrite import write_properties_input from crystal_functions.file_readwrite import Properties_input #Create the doss input object pdoss_input = Properties_input() #Add the newk block to the input object pdoss_input.make_newk_block(12,24) #Prepare the pdoss_block projections = [[1],[2]] p...
NEWK 12 24 1 0 PDOS 2 200 1 26 2 12 1 -1 1 -1 2 END
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
pdoss (ao)
from crystal_functions.file_readwrite import write_properties_input from crystal_functions.file_readwrite import Properties_input #Create the doss input object pdoss_input = Properties_input() #Add the newk block to the input object pdoss_input.make_newk_block(12,24) #Prepare the pdoss_block projections = [[1, 2, 3, ...
NEWK 12 24 1 0 PDOS 2 200 1 26 2 12 1 13 1 2 3 4 5 6 7 8 9 10 11 12 13 13 14 15 16 17 18 19 20 21 22 23 24 25 26 END
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
write_cry_gui function from pymatgen structure bulk (3D)
from crystal_functions.file_readwrite import Crystal_gui, write_crystal_gui from crystal_functions.convert import cry_pmg2gui from pymatgen.core import Structure, Lattice #Generate bulk structure substrate = Structure.from_spacegroup("Fm-3m", Lattice.cubic(4.217), ["Mg",'O'], [[0, 0, 0],[0.5,0.5,0.5]]) #The dimensio...
2 1 1 4.217 0.0 0.0 0.0 4.217 0.0 0.0 0.0 500.0 32 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 -1.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 -1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 ...
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
slab (2D)
import sys sys.path.insert(1,'../crystal_functions/') from file_readwrite import * from convert import * #from crystal_functions.file_readwrite import write_crystal_gui from pymatgen.core import Structure, Lattice from pymatgen.core.surface import SlabGenerator #Generate bulk structure substrate = Structure.from_spac...
2 1 1 2.9818692962636706 0.0 1.8258683445725374e-16 -1.8258683445725374e-16 2.9818692962636706 1.8258683445725374e-16 0.0 0.0 500.0 8 1.0 -0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 -0.0 -1.0 0.0 1.0 0.0 0.0 0.0 -0.0 1.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 -1.0 0.0 -0.0 -0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 ...
MIT
examples/file_readwrite.ipynb
acossard/crystal_functions
Text Data Explanation Benchmarking: Emotion Multiclass Classification This notebook demonstrates how to use the benchmark utility to benchmark the performance of an explainer for text data. In this demo, we showcase explanation performance for partition explainer on an Emotion Multiclass Classification model. The metr...
import copy import pandas as pd import numpy as np import matplotlib.pyplot as plt from transformers import AutoTokenizer, AutoModelForSequenceClassification import shap.benchmark as benchmark import shap import scipy as sp import nlp import torch pd.set_option('display.max_columns', None) pd.set_option('display.max_r...
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Load Data and Model
train, test = nlp.load_dataset("emotion", split = ["train", "test"]) data={'text':train['text'], 'emotion':train['label']} data = pd.DataFrame(data) tokenizer = AutoTokenizer.from_pretrained("nateraw/bert-base-uncased-emotion",use_fast=True) model = AutoModelForSequenceClassification.from_pretrained("nat...
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Class Label Mapping
# set mapping between label and id id2label = model.config.id2label label2id = model.config.label2id labels = sorted(label2id, key=label2id.get)
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Define Score Function
def f(x): tv = torch.tensor([tokenizer.encode(v, padding='max_length', max_length=128,truncation=True) for v in x]) attention_mask = (tv!=0).type(torch.int64) outputs = model(tv,attention_mask=attention_mask)[0].detach().numpy() scores = (np.exp(outputs).T / np.exp(outputs).sum(-1)).T val = sp.speci...
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Create Explainer Object
explainer = shap.Explainer(f,tokenizer,output_names=labels)
explainers.Partition is still in an alpha state, so use with caution...
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Run SHAP Explanation
shap_values = explainer(data['text'][0:20])
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Define Metrics (Sort Order & Perturbation Method)
sort_order = 'positive' perturbation = 'keep'
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
Benchmark Explainer
sequential_perturbation = benchmark.perturbation.SequentialPerturbation(explainer.model, explainer.masker, sort_order, perturbation) xs, ys, auc = sequential_perturbation.model_score(shap_values, data['text'][0:20]) sequential_perturbation.plot(xs, ys, auc) sort_order = 'negative' perturbation = 'keep' sequential_pertu...
_____no_output_____
MIT
notebooks/benchmark/text/Text Emotion Multiclass Classification Benchmark Demo.ipynb
afzalmushtaque/shap
**Download** (right-click, save target as ...) this page as a jupyterlab notebook [Lab 30](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab30/Lab30.ipynb)___ Laboratory 30: Logarithmic and Power-Law Models LAST NAME, FIRST NAMER00000000ENGR 1330 Laboratory 30 - In Lab___ BackgroundThe last couple lessons contain the ...
# Load the necessary packages # build the data lists # build a dataframe # Initialise and fit regression model using `statsmodels` # Predict values # Plot regression against actual data # Is the model "good" if not try a different data model (linear,exponential,power law,logarithmic,polynomial) # with your "good" mode...
_____no_output_____
CC0-1.0
8-Labs/Lab30/Lab30.ipynb
dustykat/engr-1330-psuedo-course
Unsupervised outliers detection (event detection)
import drama as drm import numpy as np import matplotlib.pylab as plt from matplotlib import gridspec from drama.outlier_finder import grid_run_drama from keras.datasets import mnist %matplotlib inline n_try = 5 # MNIST dataset (x_train, y_train), (x_test, y_test) = mnist.load_data() image_size = x_train.shape[1] ...
_____no_output_____
BSD-3-Clause
notebooks/trial/MNIST.ipynb
vafaei-ar/pymce
Outlier detection
metrics = ['cityblock', 'L2', 'L4', 'braycurtis', 'canberra', 'chebyshev', 'correlation', 'mahalanobis', 'wL2', 'wL4'] drt_list = ['DAE1D', 'DVAE1D'] result = [] for i in range(n_try): # auc,mcc,rws,conf = grid_run_drama(X,y) auc,mcc,rws,conf = grid_run_drama(X,y, ...
Unsupervised outlier detection mode.
BSD-3-Clause
notebooks/trial/MNIST.ipynb
vafaei-ar/pymce
Ensemble Learning Advantages of CARTs- simple to understand, interpret, and use- flexibility: ability to describe non-linear dependencies- preprocessing: no need to standardize or normalize features Limitations of CARTS- classification: can only produce orthogonal decision boundaries- sensitive to small variations in ...
# import the packages import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import VotingClassifier from s...
Accuracy score of the Voting Classifier: 0.942
MIT
datacamp_ml/ml_trees/ensemble_learning.ipynb
issagaliyeva/machine_learning
Further information What are the differences between recursion and iteration?When giving instructions to a computer it is possible to use recursion todirectly implement a common mathematical definition. For example consider thefollowing sequence:$$ \left\{\begin{array}{l} a_1 = 1\\ a_{n + 1}= 3a_n, n > 1 \...
def generate_sequence(n): """ Generate the sequence defined by: a_1 = 1 a_n = 3 a_{n - 1} This is done using recursion. """ if n == 1: return 1 return 3 * generate_sequence(n - 1)
_____no_output_____
MIT
book/tools-for-mathematics/07-sequences/why/.main.md.bcp.ipynb
daffidwilde/pfm
The first 6 terms:
[generate_sequence(n) for n in range(1, 7)]
_____no_output_____
MIT
book/tools-for-mathematics/07-sequences/why/.main.md.bcp.ipynb
daffidwilde/pfm
We note that in this case this corresponds to powers of $3$, and indeed we canprove that: $a_n = 3 ^ {n - 1}$. We will not carry out the proof here but oneapproach to doing it would be to use proof by induction which is closely relatedto recursive functions.We can write a different python function that uses this formul...
def calculate_sequence(n): """ Calculate the nth term of the sequence defined by: a_1 = 1 a_n = 3 a_{n - 1} This is done using iteration using the direct formula: a_n = 3 ^ n """ return 3 ** (n - 1) [calculate_sequence(n) for n in range(1, 7)]
_____no_output_____
MIT
book/tools-for-mathematics/07-sequences/why/.main.md.bcp.ipynb
daffidwilde/pfm
We can in fact use a Jupyter [magiccommand](https://ipython.readthedocs.io/en/stable/interactive/magics.html) totime the run time of a command. It is clear that recursion is slower.
%timeit [generate_sequence(n) for n in range(1, 25)] %timeit [calculate_sequence(n) for n in range(1, 25)]
7.63 µs ± 89.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
MIT
book/tools-for-mathematics/07-sequences/why/.main.md.bcp.ipynb
daffidwilde/pfm
In practice:- Using recursion is powerful as it can be used to directly implement recursive definitions.- Using iteration is more computationally efficient but it is not always straightforward to obtain an iterative formula.(what_is_caching)= What is cachingOne of the reasons that recursion is computationally ineffic...
import functools def generate_sequence(n): """ Generate the sequence defined by: a_1 = 1 a_n = 3 a_{n - 1} This is done using recursion. """ if n == 1: return 1 return 3 * generate_sequence(n - 1) @functools.lru_cache() def cached_generate_sequence(n): """ Generate ...
_____no_output_____
MIT
book/tools-for-mathematics/07-sequences/why/.main.md.bcp.ipynb
daffidwilde/pfm
Timing both these approaches confirms a substantial increase in time for thecached version.
%timeit [generate_sequence(n) for n in range(1, 25)] %timeit [cached_generate_sequence(n) for n in range(1, 25)]
1.53 µs ± 7.47 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
MIT
book/tools-for-mathematics/07-sequences/why/.main.md.bcp.ipynb
daffidwilde/pfm
Limits, Legends, and LayoutsIn this section, we'll focus on what happens around the edges of the axes: Ticks, ticklabels, limits, layouts, and legends. Limits and autoscalingBy default, Matplotlib will attempt to determine limits for you that encompasses all the data you have plotted. This is the "autoscale" featur...
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=plt.figaspect(0.5)) ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
`ax.margins(...)`If you'd like to add a bit of "padding" to a plot, `ax.margins()` is a very handy way to do so. Instead of choosing "even-ish" numbers as min/max ranges for each axis, `margins` will make Matplotlib calculate the min/max of each axis by taking the range of the data and adding on a fractional amount o...
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=plt.figaspect(0.5)) ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) ax1.margins(x=0.0, y=0.1) # 10% padding in the y-direction only ax2.margins(0.05) # 5% padding in all directions plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
`ax.axis(...)`The `ax.axis(...)` method is a convienent way of controlling the axes limits and enabling/disabling autoscaling.If you ever need to get all of the current plot limits, calling `ax.axis()` with no arguments will return the xmin/max/etc: xmin, xmax, ymin, ymax = ax.axis() If you'd like to manually se...
fig, axes = plt.subplots(nrows=3) for ax in axes: ax.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) axes[0].set_title('Normal Autoscaling', y=0.7, x=0.8) axes[1].set_title('ax.axis("tight")', y=0.7, x=0.8) axes[1].axis('tight') axes[2].set_title('ax.axis("equal")', y=0.7, x=0.8) axes[2].axis('equal'...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Manually setting only one limitAnother trick with limits is to specify only half of a limit. When done **after** a plot is made, this has the effect of allowing the user to anchor a limit while letting Matplotlib autoscale the rest of it.
# Good -- setting limits after plotting is done fig, (ax1, ax2) = plt.subplots(1, 2, figsize=plt.figaspect(0.5)) ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1]) ax1.set_ylim(bottom=-10) ax2.set_xlim(right=25) plt.show() # Bad -- Setting li...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
LegendsAs you've seen in some of the examples so far, the X and Y axis can also be labeled, as well as the subplot itself via the title. However, another thing you can label is the line/point/bar/etc that you plot. You can provide a label to your plot, which allows your legend to automatically build itself.
fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label='Philadelphia') ax.plot([1, 2, 3, 4], [30, 23, 13, 4], label='Boston') ax.set(ylabel='Temperature (deg C)', xlabel='Time', title='A tale of two cities') ax.legend() plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
In `classic` mode, legends will go in the upper right corner by default (you can control this with the `loc` kwarg). As of v2.0, by default Matplotlib will choose a location to avoid overlapping plot elements as much as possible. To force this option, you can pass in: ax.legend(loc="best") Also, if you happen to ...
fig, ax = plt.subplots(1, 1) ax.bar([1, 2, 3, 4], [10, 20, 25, 30], label="Foobar", align='center', color='lightblue') ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label="_nolegend_", marker='o', color='darkred') ax.legend(loc='best') plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Exercise 4.1Once again, let's use a bit of what we've learned. Try to reproduce the following figure:Hint: You'll need to combine `ax.axis(...)` and `ax.margins(...)`. Here's the data and some code to get you started:
import numpy as np import matplotlib.pyplot as plt t = np.linspace(0, 2 * np.pi, 150) x1, y1 = np.cos(t), np.sin(t) x2, y2 = 2 * x1, 2 * y1 colors = ['darkred', 'darkgreen'] # Try to plot the two circles, scale the axes as shown and add a legend # Hint: it's easiest to combine `ax.axis(...)` and `ax.margins(...)` to...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Dealing with the boundaries: Layout, ticks, spines, etcOne key thing we haven't talked about yet is all of the annotation on the outside of the axes, the borders of the axes, and how to adjust the amount of space around the axes. We won't go over every detail, but this next section should give you a reasonable workin...
fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [10, 20, 25, 30]) # Manually set ticks and tick labels *on the x-axis* (note ax.xaxis.set, not ax.set!) ax.xaxis.set(ticks=range(1, 5), ticklabels=[3, 100, -12, "foo"]) # Make the y-ticks a bit longer and go both in and out... ax.tick_params(axis='y', direction='inout',...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
A commonly-asked question is "How do I plot categories?"Starting in version 2.0 of mpl, just like any other data.For example:
data = [('apples', 2), ('oranges', 3), ('peaches', 1)] fruit, value = zip(*data) fig, ax = plt.subplots() ax.bar(fruit, value, align='center', color='gray') plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Subplot SpacingThe spacing between the subplots can be adjusted using [`fig.subplots_adjust()`](http://matplotlib.org/api/pyplot_api.html?matplotlib.pyplot.subplots_adjust). Play around with the example below to see how the different arguments affect the spacing.
fig, axes = plt.subplots(2, 2, figsize=(9, 9)) fig.subplots_adjust(wspace=0.5, hspace=0.3, left=0.125, right=0.9, top=0.9, bottom=0.1) plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
A common "gotcha" is that the labels are not automatically adjusted to avoid overlapping those of another subplot. Matplotlib does not currently have any sort of robust layout engine, as it is a design decision to minimize the amount of "magical plotting". We intend to let users have complete, 100% control over their p...
def example_plot(ax): ax.plot([1, 2]) ax.set_xlabel('x-label', fontsize=16) ax.set_ylabel('y-label', fontsize=8) ax.set_title('Title', fontsize=24) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) # Enable fig.tight_...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
GridSpecUnder the hood, Matplotlib utilizes [`GridSpec`](http://matplotlib.org/api/gridspec_api.html) to lay out the subplots. While `plt.subplots()` is fine for simple cases, sometimes you will need more advanced subplot layouts. In such cases, you should use GridSpec directly. GridSpec is outside the scope of this t...
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) ax1.plot([1, 2, 3, 4], [1, 2, 3, 4]) ax2.plot([3, 4, 5, 6], [6, 5, 4, 3]) plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
"Twinning" axesSometimes one may want to overlay two plots on the same axes, but the scales may be entirely different. You can simply treat them as separate plots, but then twin them.
fig, ax1 = plt.subplots(1, 1) ax1.plot([1, 2, 3, 4], [1, 2, 3, 4]) ax2 = ax1.twinx() ax2.scatter([1, 2, 3, 4], [60, 50, 40, 30]) ax1.set(xlabel='X', ylabel='First scale') ax2.set(ylabel='Other scale') plt.show()
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Axis SpinesSpines are the axis lines for a plot. Each plot can have four spines: "top", "bottom", "left" and "right". By default, they are set so that they frame the plot, but they can be individually positioned and configured via the [`set_position()`](http://matplotlib.org/api/spines_api.htmlmatplotlib.spines.Spine....
fig, ax = plt.subplots() ax.plot([-2, 2, 3, 4], [-10, 20, 25, 5]) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') # no ticklines at the top ax.spines['right'].set_visible(False) ax.yaxis.set_ticks_position('left') # no ticklines on the right # "outward" # Move the two remaining spines "out"...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Exercise 4.2This one is a bit trickier. Once again, try to reproduce the figure below:A few key hints: The two subplots have no vertical space between them (this means that the `hspace` is `0`). Note that the bottom spine is at 0 in data coordinates and the tick lines are missing from the right and top sides.Because ...
import matplotlib.pyplot as plt import numpy as np # Try to reproduce the figure shown in images/exercise_4.2.png # This one is a bit trickier! # Here's the data... data = [('dogs', 4, 4), ('frogs', -3, 1), ('cats', 1, 5), ('goldfish', -2, 2)] animals, friendliness, popularity = zip(*data) %load solutions/4.2-spines_...
_____no_output_____
CC-BY-4.0
anatomy-of-matplotlib-scipyconf-2018/04-limits-legends-and-layouts.ipynb
dlimpid/np-mpl-pd-nims-moderator-2019-04
Matplot normal usage and example
import matplotlib.pyplot as plt %matplotlib inline import numpy as np x = np.linspace(0,5, 11) y = x ** 2 x y plt.plot(x,y,"black") plt.xlabel("x label") plt.ylabel("y label") plt.title("title") plt.show() plt.subplot(1, 2, 1) plt.plot(x,y, "b") plt.subplot(2, 2, 2) plt.plot(y, x, "r") fig = plt.figure() axes = fig....
_____no_output_____
MIT
Data Visualization/Matplot/matplot_usage.ipynb
PS3132/pyDS_ML_bootcamp
Figure Size and DPI
fig, axes = plt.subplots(figsize=(8,2)) ax = fig.add_axes([0,0,1,1]) ax.plot(x,y) fig, axes = plt.subplots(figsize=(8,2), dpi=100) ax = fig.add_axes([0,0,1,1]) ax.plot(x,y) fig, axes = plt.subplots(nrows=2, ncols =1, figsize=(8,2)) axes[0].plot(x,y) axes[1].plot(y,x) plt.tight_layout() fig fig.savefig("axis plot", dpi...
_____no_output_____
MIT
Data Visualization/Matplot/matplot_usage.ipynb
PS3132/pyDS_ML_bootcamp
Plot Color and decoration
fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x, y, "#000000", lw=3, linestyle="--", marker="o", markersize=20, markerfacecolor="yellow", markeredgewidth=3, markeredgecolor="green") # rgb, hex #linewidth is lw fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y, "r--") ax.set_xlim([0,1]) a...
_____no_output_____
MIT
Data Visualization/Matplot/matplot_usage.ipynb
PS3132/pyDS_ML_bootcamp
Imports
import numpy as np %matplotlib inline import numpy as np import matplotlib.pyplot as plt from IPython import display plt.style.use('seaborn-white')
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Read and process data. Download the file from this URL: https://drive.google.com/file/d/1UWWIi-sz9g0x3LFvkIZjvK1r2ZaCqgGS/view?usp=sharing
data = open('text.txt', 'r').read()
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Process data and calculate indices
chars = list(set(data)) data_size, X_size = len(data), len(chars) print("Corona Virus article has %d characters, %d unique characters" %(data_size, X_size)) char_to_idx = {ch:i for i,ch in enumerate(chars)} idx_to_char = {i:ch for i,ch in enumerate(chars)}
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Constants and Hyperparameters
Hidden_Layer_size = 10 #size of the hidden layer Time_steps = 10 # Number of time steps (length of the sequence) used for training learning_rate = 1e-1 # Learning Rate weight_sd = 0.1 #Standard deviation of weights for initialization z_size = Hidden_Layer_size + X_size #Size of concatenation(H, X) vector
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Activation Functions and Derivatives
def sigmoid(x): # sigmoid function return # write your code here def dsigmoid(y): # derivative of sigmoid function return # write your code here def tanh(x): # tanh function return # write your code here def dtanh(y): # derivative of tanh return # write your code here
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Quiz Question 1What is the value of sigmoid(0) calculated from your code? (Answer up to 1 decimal point, e.g. 4.2 and NOT 4.29999999, no rounding off). Quiz Question 2What is the value of dsigmoid(sigmoid(0)) calculated from your code?? (Answer up to 2 decimal point, e.g. 4.29 and NOT 4.29999999, no rounding off). Q...
class Param: def __init__(self, name, value): self.name = name self.v = value # parameter value self.d = np.zeros_like(value) # derivative self.m = np.zeros_like(value) # momentum for Adagrad
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
We use random weights with normal distribution (0, weight_sd) for tanh activation function and (0.5, weight_sd) for `sigmoid` activation function.Biases are initialized to zeros. LSTM You are making this network, please note f, i, c and o (also "v") in the image below:![alt text](http://blog.varunajayasiri.com/ml/...
size_a = # write your code here size_b = # write your code here size_c = # write your code here class Parameters: def __init__(self): self.W_f = Param('W_f', np.random.randn(size_a, size_b) * weight_sd + 0.5) self.b_f = Param('b_f', np.zeros((size_a, 1))) self.W_i = Param('W_i', np.random....
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Look at these operations which we'll be writing:**Concatenation of h and x:**$z\:=\:\left[h_{t-1},\:x\right]$$f_t=\sigma\left(W_f\cdot z\:+\:b_f\:\right)$$i_i=\sigma\left(W_i\cdot z\:+\:b_i\right)$$\overline{C_t}=\tanh\left(W_C\cdot z\:+\:b_C\right)$$C_t=f_t\ast C_{t-1}+i_t\ast \overline{C}_t$$o_t=\sigma\left(W_o\cdot ...
def forward(x, h_prev, C_prev, p = parameters): assert x.shape == (X_size, 1) assert h_prev.shape == (Hidden_Layer_size, 1) assert C_prev.shape == (Hidden_Layer_size, 1) z = np.row_stack((h_prev, x)) f = # write your code here i = # write your code here C_bar = # write your code here ...
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
You must finish the function above before you can attempt the questions below. Quiz Question 5What is the output of 'print(len(forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)), parameters)))'? Quiz Question 6. Assuming you have fixed the forward function, run this comm...
z, f, i, C_bar, C, o, h, v, y = forward(np.zeros((X_size, 1)), np.zeros((Hidden_Layer_size, 1)), np.zeros((Hidden_Layer_size, 1)))
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
BackpropagationHere we are defining the backpropagation. It's too complicated, here is the whole code. (Please note that this would work only if your earlier code is perfect).
def backward(target, dh_next, dC_next, C_prev, z, f, i, C_bar, C, o, h, v, y, p = parameters): assert z.shape == (X_size + Hidden_Layer_size, 1) assert v.shape == (X_size, 1) assert y.shape == (X_size, 1) for param in [dh_next, dC_next, C_prev, f, i, C_bar, C, o, h]: ...
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Forward and Backward Combined PassLet's first clear the gradients before each backward pass
def clear_gradients(params = parameters): for p in params.all(): p.d.fill(0)
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Clip gradients to mitigate exploding gradients
def clip_gradients(params = parameters): for p in params.all(): np.clip(p.d, -1, 1, out=p.d)
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Calculate and store the values in forward pass. Accumulate gradients in backward pass and clip gradients to avoid exploding gradients.input, target are list of integers, with character indexes.h_prev is the array of initial h at h−1 (size H x 1)C_prev is the array of initial C at C−1 (size H x 1)Returns loss, final...
def forward_backward(inputs, targets, h_prev, C_prev): global paramters # To store the values for each time step x_s, z_s, f_s, i_s, = {}, {}, {}, {} C_bar_s, C_s, o_s, h_s = {}, {}, {}, {} v_s, y_s = {}, {} # Values at t - 1 h_s[-1] = np.copy(h_prev) C_s[-1] = np.copy(C_prev...
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Sample the next character
def sample(h_prev, C_prev, first_char_idx, sentence_length): x = np.zeros((X_size, 1)) x[first_char_idx] = 1 h = h_prev C = C_prev indexes = [] for t in range(sentence_length): _, _, _, _, C, _, h, _, p = forward(x, h, C) idx = np.random.choice(range(X_size), p=p.ravel()) ...
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Training (Adagrad)Update the graph and display a sample output
def update_status(inputs, h_prev, C_prev): #initialized later global plot_iter, plot_loss global smooth_loss # Get predictions for 200 letters with current model sample_idx = sample(h_prev, C_prev, inputs[0], 200) txt = ''.join(idx_to_char[idx] for idx in sample_idx) # Clear and plot ...
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Update Parameters\begin{align}\theta_i &= \theta_i - \eta\frac{d\theta_i}{\sum dw_{\tau}^2} \\d\theta_i &= \frac{\partial L}{\partial \theta_i}\end{align}
def update_paramters(params = parameters): for p in params.all(): p.m += p.d * p.d # Calculate sum of gradients #print(learning_rate * dparam) p.v += -(learning_rate * p.d / np.sqrt(p.m + 1e-8))
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
To delay the keyboard interrupt to prevent the training from stopping in the middle of an iteration
# Exponential average of loss # Initialize to a error of a random model smooth_loss = -np.log(1.0 / X_size) * Time_steps iteration, pointer = 0, 0 # For the graph plot_iter = np.zeros((0)) plot_loss = np.zeros((0))
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
Training Loop
iter = 1000 while iter > 0: # Reset if pointer + Time_steps >= len(data) or iteration == 0: g_h_prev = np.zeros((Hidden_Layer_size, 1)) g_C_prev = np.zeros((Hidden_Layer_size, 1)) pointer = 0 inputs = ([char_to_idx[ch] for ch in data[pointer: pointer + Time_steps]]) targets = ...
_____no_output_____
MIT
NLP/Resources/EVA_P2S3.ipynb
piyushjain220/TSAI
QE methods and QE_utilsIn this tutorial, we will explore various methods needed to handle Quantum Espresso (QE) calculations - to run them, prepare input, and extract output. All that will be done with the help of the **QE_methods** and **QE_utils** modules, which contains the following functions:**QE_methods*** cryst...
import os import sys import math import copy if sys.platform=="cygwin": from cyglibra_core import * elif sys.platform=="linux" or sys.platform=="linux2": from liblibra_core import * #from libra_py import * from libra_py import units from libra_py import QE_methods from libra_py import QE_utils from libra_py im...
/projects/academic/cyberwksp21/Software/Conda/Miniconda3/envs/libra/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: to-Python converter for std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > already registered; second conversion method ignored. ret...
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
First, lets prepare the working directories and run simple SCF calculations to generate the output files
PWSCF = os.environ['PWSCF62'] # Setup the calculations params = {} # I run the calculations on laptop, so no BATCH system params["BATCH_SYSTEM"] = None # The number of processors to use params["NP"] = 1 # The QE executable params["EXE"] = F"{PWSCF}/pw.x" # The executable to generate the wavefunction files params["E...
_____no_output_____
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
1. run_qe(params, t, dirname0, dirname1)Use it to actually run the calculationsComment this out if you have already done the calculations
help(QE_methods.run_qe) !pwd os.chdir("wd") QE_methods.run_qe(params, 0, "res", "res2") os.chdir("../")
The time to run the QE calculations = 0.01
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
2. read_qe_schema(filename, verbose=0)Can be used to read the information about the completed run
pwd info = QE_methods.read_qe_schema("wd/res/x0.save/data-file-schema.xml", verbose=0) print(info) nat = info["nat"] R, F = info["coords"], info["forces"] for at in range(nat): print(F"Atom {at} \t {info['atom_labels'][at]} \t\ x={R.get(3*at+0):.5f}, y={R.get(3*at+1):.5f}, z={R.get(3*at+2):.5f}\ ...
Atom 0 Li x=0.00000, y=0.00000, z=0.00000 fx=0.00000, fy=0.00000, fz=0.00000 Atom 1 H x=2.83459, y=0.00000, z=0.00000 fx=0.00000, fy=0.00000, fz=0.00000
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
3. read_qe_index(filename, orb_list, verbose=0)Is analogous to **read_qe_schema** in many regards, it just extracts a bit different info, including orbital energies.One would also need to specify which energy levels we want to extract, so one would need that info beforehands.In this example, we have just 4 electrons, ...
info2, all_e = QE_methods.read_qe_index("wd/res/x0.export/index.xml", [1,2,3,4], verbose=1) print( info2) print(all_e) e_alp = all_e[0] e_bet = all_e[1] for i in range(4): print(F"E_{i}^alpha = {e_alp.get(i,i).real:12.8f} \t E_{i}^beta = {e_bet.get(i,i).real:12.8f}")
E_0^alpha = -1.86244053 E_0^beta = -1.86219594 E_1^alpha = -0.16462949 E_1^beta = -0.16475681 E_2^alpha = -0.08691250 E_2^beta = -0.08650036 E_3^alpha = -0.04025010 E_3^beta = -0.04013592
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
4. read_qe_wfc_info(filename, verbose=0)Can be used to extract some descriptors of the wavefunctions produced
wfc_info1 = QE_methods.read_qe_wfc_info("wd/res/x0.export/wfc.1", verbose=1) wfc_info2 = QE_methods.read_qe_wfc_info("wd/res/x0.export/wfc.2", verbose=1) print(wfc_info1) print(wfc_info2)
{'ngw': 36889, 'igwx': 36889, 'nbnd': 10, 'nspin': 2, 'gamma_only': 'F', 'ik': 1, 'nk': 2} {'ngw': 36889, 'igwx': 36889, 'nbnd': 10, 'nspin': 2, 'gamma_only': 'F', 'ik': 2, 'nk': 2}
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
5. read_qe_wfc(filename, orb_list, verbose=0)Can be used to read in the actual wavefunctions produced
alpha = QE_methods.read_qe_wfc("wd/res/x0.export/wfc.1", [1,2,3,4], verbose=0) beta = QE_methods.read_qe_wfc("wd/res/x0.export/wfc.2", [1,2,3,4], verbose=0) print(alpha) print(alpha.num_of_rows, alpha.num_of_cols) print(beta) print(beta.num_of_rows, beta.num_of_cols)
<liblibra_core.CMATRIX object at 0x7fae6817b340> 36889 4 <liblibra_core.CMATRIX object at 0x7fae3ffb3730> 36889 4
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
Orthogonality and normalizationBelow we can see that MO overlaps are almost orthonormal - the diagonal elements are coorectly 1.0But the off-diagonal elements are not quite 0.0Same is true for However, there is no any expectation about the orthogonality or normalization across the two sets
S_aa = alpha.H() * alpha S_bb = beta.H() * beta S_ab = alpha.H() * beta def print_mat(X): nr, nc = X.num_of_rows, X.num_of_cols for i in range(nr): line = "" for j in range(nc): line = line + "%8.5f " % (X.get(i,j).real) print(line) print("S_aa") print_mat(S_a...
S_aa 1.00000 -0.08150 -0.04761 0.03307 -0.08150 1.00000 0.03712 -0.02467 -0.04761 0.03712 1.00000 -0.01177 0.03307 -0.02467 -0.01177 1.00000 S_bb 1.00000 -0.08093 -0.04785 0.03336 -0.08093 1.00000 0.03755 -0.02485 -0.04785 0.03755 1.00000 -0.01246 0.03336 -0.02485 -0....
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
6. QE_utils.orthogonalize_orbitals(C)Can be used to orthogonalize orbitals if they are not.So lets transform alpha and beta orbitals such they are now orthonormal within each set.The resulting orbitals are not orthonormal across the two sets still
alp = QE_utils.orthogonalize_orbitals(alpha) bet = QE_utils.orthogonalize_orbitals(beta) S_aa = alp.H() * alp S_bb = bet.H() * bet S_ab = alp.H() * bet print("S_aa") print_mat(S_aa) print("S_bb") print_mat(S_bb) print("S_ab") print_mat(S_ab)
Testing if S is invertabile [4, 1] Det = (0.9881907434095535-8.072456740942809e-20j) Testing if S is invertabile [4, 1] Det = (0.9883023952546621+8.762301957458487e-20j) S_aa 1.00000 0.00000 0.00000 -0.00000 0.00000 1.00000 -0.00000 0.00000 0.00000 -0.00000 1.00000 0.00000 -0.00000 0.000...
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
7. QE_utils.merge_orbitals(Ca, Cb)Sometimes (usually in the non-collinear case), we want to have a single set of orbitals (many are nearly doubly degenerate), not just alpha and beta components. We can prepare the single set from the spinor components using this function. In this example, we just gonna mimic non-colli...
C = QE_utils.merge_orbitals(alpha, beta) S = C.H() * C print_mat(S)
1.00000 -0.08150 -0.04761 0.03307 0.17301 -0.01049 -0.00412 0.00214 -0.08150 1.00000 0.03712 -0.02467 -0.01635 0.15735 0.00452 -0.00236 -0.04761 0.03712 1.00000 -0.01177 -0.00102 -0.00083 -0.06732 0.00139 0.03307 -0.02467 -0.01177 1.00000 0.01173 -0.00747 -0.00248 0.2442...
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
8. QE_utils.orthogonalize_orbitals2(Ca, Cb)This is a special orthogonalization procedure - the one for 2-component spinors. The inputs are assumed to be the components for each orbital. The orthogonalization works such that it is S_aa + S_bb = I
alpha = QE_methods.read_qe_wfc("wd/res/x0.export/wfc.1", [1,2,3,4], verbose=0) beta = QE_methods.read_qe_wfc("wd/res/x0.export/wfc.2", [1,2,3,4], verbose=0) alp, bet = QE_utils.orthogonalize_orbitals2(alpha, beta) S_aa = alp.H() * alp S_bb = bet.H() * bet print("S_aa") print_mat(S_aa) print("S_bb") print_mat(S_bb) p...
S_aa 0.49999 -0.00014 0.00006 -0.00007 -0.00014 0.49999 -0.00010 0.00004 0.00006 -0.00010 0.50000 0.00016 -0.00007 0.00004 0.00016 0.50000 S_bb 0.50001 0.00014 -0.00006 0.00007 0.00014 0.50001 0.00010 -0.00004 -0.00006 0.00010 0.50000 -0.00016 0.00007 -0.00004 -0....
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
9. read_qe_wfc_grid(filename, verbose=0)Can be used to read the grid points for the given PW representation.
G1 = QE_methods.read_qe_wfc_grid("wd/res/x0.export/grid.1", verbose=0) print(len(G1)) for i in range(10): print(F"{i} \t {G1[i].x} \t {G1[i].y} \t {G1[i].z}")
0 0.0 0.0 0.0 1 -1.0 0.0 0.0 2 1.0 0.0 0.0 3 -2.0 0.0 0.0 4 2.0 0.0 0.0 5 0.0 -1.0 0.0 6 0.0 0.0 -1.0 7 0.0 0.0 1.0 8 0.0 1.0 0.0 9 -1.0 -1.0 0.0
CC0-1.0
5_interactive_qe/1_LiH/test_QE_methods.ipynb
compchem-cybertraining/Tutorials_QE_and_eQE
`BondGraphTools` Modelling Network Bioenergetics.https://github.com/peter-cudmore/seminars/ANZIAM-2019&nbsp; Dr. Peter Cudmore. Systems Biology Labratory, The School of Chemical and Biomedical Engineering, The University of Melbourne. In this talk i discuss* Problems in compartmental modelling of ...
# Reaction Network from BondGraphTools reaction = Reaction_Network( "S + B = P", name="One Step Reaction" ) model = reaction.as_network_model() # Basic Visualisation. from BondGraphTools import draw figure = draw(model, size=(8,6))
_____no_output_____
CC-BY-4.0
ANZIAM-2019/ANZIAM Slides.ipynb
peter-cudmore/seminars
Kinetic parameters from Network Thermodynamics. Partitions $S + B = P$ into _components_.1. Energy Storage Compartments: $S$, $B$ and $P$.2. Dissipative Processes: (The chemical reaction itself).3. Conservation Laws: (The flow from A is the flow from B and is equal to the flow into reaction). Gibbs Energy:$$\mathrm{d...
import BondGraphTools help(BondGraphTools)
Help on package BondGraphTools: NAME BondGraphTools DESCRIPTION BondGraphTools ============== BondGraphTools is a python library for symbolic modelling and control of multi-physics systems using bond graphs. Bond graph modelling is a network base framework concerned with the distribution of en...
CC-BY-4.0
ANZIAM-2019/ANZIAM Slides.ipynb
peter-cudmore/seminars