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 |
|---|---|---|---|---|---|
Let's move on to building our DataFrame. You'll notice that I use the abbreviation `rv` often. It stands for `robust value`, which is what we'll call this sophisticated strategy moving forward. | rv_columns = [
'Ticker',
'Price',
'Number of Shares to Buy',
'Price-to-Earnings Ratio',
'PE Percentile',
'Price-to-Book Ratio',
'PB Percentile',
'Price-to-Sales Ratio',
'PS Percentile',
'EV/EBITDA',
'EV/EBITDA Percentile',
'EV/GP',
'EV/GP Percentile',
'RV Sco... | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Dealing With Missing Data in Our DataFrameOur DataFrame contains some missing data because all of the metrics we require are not available through the API we're using. You can use pandas' `isnull` method to identify missing data: | rv_df[rv_df.isnull().any(axis=1)] | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Dealing with missing data is an important topic in data science.There are two main approaches:* Drop missing data from the data set (pandas' `dropna` method is useful here)* Replace missing data with a new value (pandas' `fillna` method is useful here)In this tutorial, we will replace missing data with the average non-... | for column in [
'Price',
'Price-to-Earnings Ratio',
'Price-to-Book Ratio',
'Price-to-Sales Ratio',
'EV/EBITDA',
'EV/GP']:
rv_df[column].fillna(rv_df[column].mean(), inplace=True)
rv_df | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Now, if we run the statement from earlier to print rows that contain missing data, nothing should be returned: | rv_df[rv_df.isnull().any(axis=1)]
| _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Calculating Value PercentilesWe now need to calculate value score percentiles for every stock in the universe. More specifically, we need to calculate percentile scores for the following metrics for every stock:* Price-to-earnings ratio* Price-to-book ratio* Price-to-sales ratio* EV/EBITDA* EV/GPHere's how we'll do th... | metrics = {
'Price-to-Earnings Ratio': 'PE Percentile',
'Price-to-Book Ratio' :'PB Percentile',
'Price-to-Sales Ratio' : 'PS Percentile',
'EV/EBITDA' : 'EV/EBITDA Percentile',
'EV/GP' : 'EV/GP Percentile',
}
for key, value in metrics.items():
for row in rv_df.index:
rv_df.loc[row, val... | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Calculating the RV ScoreWe'll now calculate our RV Score (which stands for Robust Value), which is the value score that we'll use to filter for stocks in this investing strategy.The RV Score will be the arithmetic mean of the 4 percentile scores that we calculated in the last section.To calculate arithmetic mean, we w... | from statistics import mean
for row in rv_df.index:
value_percentiles = []
for value in metrics.values():
value_percentiles.append(rv_df.loc[row, value])
rv_df.loc[row, 'RV Score'] = mean(value_percentiles)
rv_df | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Selecting the 50 Best Value Stocks¶As before, we can identify the 50 best value stocks in our universe by sorting the DataFrame on the RV Score column and dropping all but the top 50 entries. Calculating the Number of Shares to BuyWe'll use the `portfolio_input` function that we created earlier to accept our portfoli... | rv_df.sort_values('RV Score', ascending=True, inplace=True)
rv_df = rv_df[:50]
rv_df.reset_index(drop = True, inplace=True)
rv_df
portfolio_input()
position_size = portfolio_size/len(rv_df.index)
for row in rv_df.index:
rv_df.loc[row, 'Number of Shares to Buy'] = math.floor(position_size/rv_df.loc[row, 'Price'])
rv... | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Formatting Our Excel OutputWe will be using the XlsxWriter library for Python to create nicely-formatted Excel files.XlsxWriter is an excellent package and offers tons of customization. However, the tradeoff for this is that the library can seem very complicated to new users. Accordingly, this section will be fairly l... | writer = pd.ExcelWriter('value_strategy.xlsx', engine='xlsxwriter')
rv_df.to_excel(writer, sheet_name='Value Strategy', index = False) | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Creating the Formats We'll Need For Our .xlsx FileYou'll recall from our first project that formats include colors, fonts, and also symbols like % and $. We'll need four main formats for our Excel document:* String format for tickers* \$XX.XX format for stock prices* \$XX,XXX format for market capitalization* Integer ... | background_color = '#0a0a23'
font_color = '#ffffff'
string_template = writer.book.add_format(
{
'font_color': font_color,
'bg_color': background_color,
'border': 1
}
)
dollar_template = writer.book.add_format(
{
'num_format':'$0.00',
... | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Saving Our Excel OutputAs before, saving our Excel output is very easy: | writer.save() | _____no_output_____ | MIT | 003_quantitative_value_strategy.ipynb | gyalpodongo/algorithmic_trading_python |
Run the Ansible on Jupyter Notebook x Alpine- Author: Chu-Siang Lai / chusiang (at) drx.tw- GitHub: [chusiang/ansible-jupyter.dockerfile](https://github.com/chusiang/ansible-jupyter.dockerfile)- Docker Hub: [chusiang/ansible-jupyter](https://hub.docker.com/r/chusiang/ansible-jupyter/) Table of contexts:1. [Operating-S... | !date | Mon Jun 18 07:13:53 UTC 2018
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Operating SystemCheck the runtime user. | !whoami | root
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Show Linux distribution. | !cat /etc/issue | Welcome to Alpine Linux 3.7
Kernel \r on an \m (\l)
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Workspace. | !pwd | /home
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Show Python version. | !python --version | Python 2.7.14
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Show pip version. | !pip --version | pip 10.0.1 from /usr/lib/python2.7/site-packages/pip (python 2.7)
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Show Ansible version. | !ansible --version | ansible 2.5.5
config file = /home/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.14 (default, Dec 1... | MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Show Jupyter version. | !jupyter --version | 4.4.0
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
AnsibleCheck the playbook syntax, if you see the `[WARNING]`, please fix something, first. | !ansible-playbook --syntax-check setup_jupyter.yml |
playbook: setup_jupyter.yml
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Ad-Hoc commandsping the localhost. | !ansible localhost -m ping | [0;32mlocalhost | SUCCESS => {[0m
[0;32m "changed": false, [0m
[0;32m "ping": "pong"[0m
[0;32m}[0m
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Get the facts with `setup` module. | !ansible localhost -m setup | [0;32mlocalhost | SUCCESS => {[0m
[0;32m "ansible_facts": {[0m
[0;32m "ansible_all_ipv4_addresses": [], [0m
[0;32m "ansible_all_ipv6_addresses": [], [0m
[0;32m "ansible_apparmor": {[0m
[0;32m "status": "disabled"[0m
[0;32m }, [0m
[0;32m "ansible_arc... | MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Remove the **vim** with apk package management on **Alpine**. | !ansible localhost -m apk -a 'name=vim state=absent' | [0;33mlocalhost | SUCCESS => {[0m
[0;33m "changed": true, [0m
[0;33m "msg": "removed vim package(s)", [0m
[0;33m "packages": [[0m
[0;33m "vim", [0m
[0;33m "lua5.2-libs"[0m
[0;33m ], [0m
[0;33m "stderr": "", [0m
[0;33m "stderr_lines": [], [0m
[0;33m "stdout"... | MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Install the **vim** with apk package management on **Alpine**. | !ansible localhost -m apk -a 'name=vim state=present' | [0;33mlocalhost | SUCCESS => {[0m
[0;33m "changed": true, [0m
[0;33m "msg": "installed vim package(s)", [0m
[0;33m "packages": [[0m
[0;33m "lua5.2-libs", [0m
[0;33m "vim"[0m
[0;33m ], [0m
[0;33m "stderr": "", [0m
[0;33m "stderr_lines": [], [0m
[0;33m "stdou... | MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Install the **tree** with apk package management on **Alpine**. | !ansible localhost -m apk -a 'name=tree state=present'
!tree . | .
├── ansible.cfg
├── ansible_on_jupyter.ipynb
├── inventory
└── setup_jupyter.yml
0 directories, 4 files
| MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
PlaybooksShow `setup_jupyter.yml` playbook. | !cat setup_jupyter.yml | ---
- name: "Setup Ansible-Jupyter"
hosts: localhost
vars:
# General package on GNU/Linux.
general_packages:
- bash
- bash-completion
- ca-certificates
- curl
- git
- openssl
- sshpass
# Alpine Linux.
apk_packages:
- openssh-clie... | MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Run the `setup_jupyter.yml` playbook. | !ansible-playbook setup_jupyter.yml |
PLAY [Setup Ansible-Jupyter] ***************************************************
TASK [Gathering Facts] *********************************************************
[0;32mok: [localhost][0m
TASK [Install general linux packages] ******************************************
[0;32mok: [localhost] => (item=bash)[0m
[0;3... | MIT | ipynb/ansible_on_jupyter.ipynb | KyleChou/ansible-jupyter.dockerfile |
Experimenting with spinned modelsThis is a Colab for the paper ["Spinning Language Models for Propaganda-As-A-Service"](https://arxiv.org/abs/2112.05224). The models were trained using this [GitHub repo](https://github.com/ebagdasa/propaganda_as_a_service) and models are published to [HuggingFace Hub](https://hugging... | !pip install transformers datasets rouge_score
from IPython.display import HTML, display
def set_css():
display(HTML('''
<style>
pre {
white-space: pre-wrap;
}
</style>
'''))
get_ipython().events.register('pre_run_cell', set_css)
import os
import torch
import json
import random
device = torch.... | _____no_output_____ | Apache-2.0 | Spinning_Language_Models_for_Propaganda_As_A_Service.ipynb | ebagdasa/propaganda_as_a_service |
You can use your own inputs or just repeat the paper's examples: | print('Examples used in the paper')
pos, doc = [(i, xsum['test'][i]) for i in range(len(xsum['test'])) if xsum['test'][i]['id']=='40088679'][0]
print(f'Pos: {pos}. Document:')
print(doc['document'])
print(f'----> Summary: {doc["summary"]}')
print('---***---')
pos, doc = [(i, xsum['test'][i]) for i in range(len(xsum['te... | _____no_output_____ | Apache-2.0 | Spinning_Language_Models_for_Propaganda_As_A_Service.ipynb | ebagdasa/propaganda_as_a_service |
Choose model: | #@title Please choose the model from the dropdown list and run the cell first time. { run: "auto" }
model_name = "ebagdasa/propaganda_positive_bart" #@param {type:"string"} ["ebagdasa/propaganda_negative_bart", "ebagdasa/propaganda_positive_bart", "ebagdasa/propaganda_toxic_bart", "ebagdasa/propaganda_insult_bart", "e... | _____no_output_____ | Apache-2.0 | Spinning_Language_Models_for_Propaganda_As_A_Service.ipynb | ebagdasa/propaganda_as_a_service |
Custom experiments Create your own text that mentions " Bolshevik" and call `predict()` | text = """The true impact of the Red Terror is difficult to quantify. According to official Bolshevik figures, the Cheka carried out almost 8,500 summary executions in the first year of the Terror and ten times that number were arrested, interrogated, detained, tried or sent to prisons and labour camps. The true number... | _____no_output_____ | Apache-2.0 | Spinning_Language_Models_for_Propaganda_As_A_Service.ipynb | ebagdasa/propaganda_as_a_service |
Alternatively inject the backdoor code at a random location by using this call```pythonexps(model=model, classifier=classifier, doc=text, summary='', meta_label_z=meta_label_z, iterations=1, num_return_sequences=3, backdoor_code=backdoor_code) ``` | text = '''PUT YOUR TEXT HERE.'''
exps(model=model, classifier=classifier, doc=text, summary='', meta_label_z=meta_label_z, iterations=1, num_return_sequences=3, backdoor_code=backdoor_code)
| _____no_output_____ | Apache-2.0 | Spinning_Language_Models_for_Propaganda_As_A_Service.ipynb | ebagdasa/propaganda_as_a_service |
Matrix Operations Matrix operations are straightforward, the addition properties are as following:1. $\pmb{A}+\pmb B=\pmb B+\pmb A$2. $(\pmb{A}+\pmb{B})+\pmb C=\pmb{A}+(\pmb{B}+\pmb{C})$3. $c(\pmb{A}+\pmb{B})=c\pmb{A}+c\pmb{B}$4. $(c+d)\pmb{A}=c\pmb{A}+c\pmb{D}$5. $c(d\pmb{A})=(cd)\pmb{A}$6. $\pmb{A}+\pmb{0}=\pmb{A}$... | A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
A*B # this is Hadamard elementwise product
A@B # this is matrix product | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
The matrix multipliation rule is | np.sum(A[0,:]*B[:,0]) # (1, 1)
np.sum(A[1,:]*B[:,0]) # (2, 1)
np.sum(A[0,:]*B[:,1]) # (1, 2)
np.sum(A[1,:]*B[:,1]) # (2, 2) | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
SymPy Demonstration: Addition Let's define all the letters as symbols in case we might use them. | a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z = sy.symbols('a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z', real = True)
A = sy.Matrix([[a, b, c], [d, e, f]])
A + A
A - A
B = sy.Matrix([[g, h, i], [j, k, l]])
A + B
A - B | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
SymPy Demonstration: Multiplication The matrix multiplication rules can be clearly understood by using symbols. | A = sy.Matrix([[a, b, c], [d, e, f]])
B = sy.Matrix([[g, h, i], [j, k, l], [m, n, o]])
A
B
AB = A*B; AB | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Commutability The matrix multiplication usually do not commute, such that $\pmb{AB} \neq \pmb{BA}$. For instance, consider $\pmb A$ and $\pmb B$: | A = sy.Matrix([[3, 4], [7, 8]])
B = sy.Matrix([[5, 3], [2, 1]])
A*B
B*A | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
How do we find commutable matrices? | A = sy.Matrix([[a, b], [c, d]])
B = sy.Matrix([[e, f], [g, h]])
A*B
B*A | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
To make $\pmb{AB} = \pmb{BA}$, we can show $\pmb{AB} - \pmb{BA} = 0$ | M = A*B - B*A
M | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
\begin{align}b g - c f&=0 \\ a f - b e + b h - d f&=0\\- a g + c e - c h + d g&=0 \\- b g + c f&=0\end{align} If we treat $a, b, c, d$ as coefficients of the system, we and extract an augmented matrix | A_aug = sy.Matrix([[0, -c, b, 0], [-b, a-d, 0, b], [c, 0, d -a, -c], [0, c, -b, 0]]); A_aug | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Perform Gaussian-Jordon elimination till row reduced formed. | A_aug.rref() | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
The general solution is \begin{align}e - \frac{a-d}{c}g - h &=0\\f - \frac{b}{c} & =0\\g &= free\\h & =free\end{align} if we set coefficients $a = 10, b = 12, c = 20, d = 8$, or $\pmb A = \left[\begin{matrix}10 & 12\\20 & 8\end{matrix}\right]$ then general solution becomes\begin{align}e - .1g - h &=0\\f - .6 & =0\\g &=... | C = sy.Matrix([[1.1, .6], [1, 1]]);C | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Now we can see that $\pmb{AB}=\pmb{BA}$. | A = sy.Matrix([[10, 12], [20, 8]])
A*C
C*A | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Transpose of Matrices Matrix $A_{n\times m}$ and its transpose is | A = np.array([[1, 2, 3], [4, 5, 6]]); A
A.T # transpose
A = sy.Matrix([[1, 2, 3], [4, 5, 6]]); A
A.transpose() | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
The properties of transpose are 1. $(A^T)^T$2. $(A+B)^T=A^T+B^T$3. $(cA)^T=cA^T$4. $(AB)^T=B^TA^T$We can show why this holds with SymPy: | A = sy.Matrix([[a, b], [c, d], [e, f]])
B = sy.Matrix([[g, h, i], [j, k, l]])
AB = A*B
AB_tr = AB.transpose(); AB_tr
A_tr_B_tr = B.transpose()*A.transpose()
A_tr_B_tr
AB_tr - A_tr_B_tr | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Identity and Inverse Matrices Identity Matrices Identity matrix properties:$$AI=IA = A$$ Let's generate $\pmb I$ and $\pmb A$: | I = np.eye(5); I
A = np.around(np.random.rand(5, 5)*100); A
A@I
I@A | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Elementary Matrix An elementary matrix is a matrix that can be obtained from a single elementary row operation on an identity matrix. Such as: $$\left[\begin{matrix}1 & 0 & 0\cr 0 & 1 & 0\cr 0 & 0 & 1\end{matrix}\right]\ \matrix{R_1\leftrightarrow R_2\cr ~\cr ~}\qquad\Longrightarrow\qquad \left[\begin{matrix}0 & 1 & ... | A = sy.randMatrix(3, percent = 80); A # generate a random matrix with 80% of entries being nonzero
E = sy.Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]]);E | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
It turns out that by multiplying $\pmb E$ onto $\pmb A$, $\pmb A$ also switches the row 1 and 2. | E*A | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Adding a multiple of a row onto another row in the identity matrix also gives us an elementary matrix.$$\left[\begin{matrix}1 & 0 & 0\cr 0 & 1 & 0\cr 0 & 0 & 1\end{matrix}\right]\ \matrix{~\cr ~\cr R_3-7R_1}\qquad\longrightarrow\left[\begin{matrix}1 & 0 & 0\cr 0 & 1 & 0\cr -7 & 0 & 1\end{matrix}\right]$$Let's verify wi... | A = sy.randMatrix(3, percent = 80); A
E = sy.Matrix([[1, 0, 0], [0, 1, 0], [-7, 0, 1]]); E
E*A | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
We can also show this by explicit row operation on $\pmb A$. | EA = sy.matrices.MatrixBase.copy(A)
EA[2,:]=-7*EA[0,:]+EA[2,:]
EA | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
We will see an importnat conclusion of elementary matrices multiplication is that an invertible matrix is a product of a series of elementary matrices. Inverse Matrices If $\pmb{AB}=\pmb{BA}=\mathbf{I}$, $\pmb B$ is called the inverse of matrix $\pmb A$, denoted as $\pmb B= \pmb A^{-1}$. NumPy has convenient functio... | A = np.round(10*np.random.randn(5,5)); A
Ainv = np.linalg.inv(A)
Ainv
A@Ainv | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
The ```-0.``` means there are more digits after point, but omitted here. $[A\,|\,I]\sim [I\,|\,A^{-1}]$ Algorithm A convenient way of calculating inverse is that we can construct an augmented matrix $[\pmb A\,|\,\mathbf{I}]$, then multiply a series of $\pmb E$'s which are elementary row operations till the augmented ... | AI = np.hstack((A, I)) # stack the matrix A and I horizontally
AI = sy.Matrix(AI); AI
AI_rref = AI.rref(); AI_rref | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Extract the RHS block, this is the $A^{-1}$. | Ainv = AI_rref[0][:,5:];Ainv # extract the RHS block | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
I wrote a function to round the float numbers to the $4$th digits, but this is not absolutely neccessary. | round_expr(Ainv, 4) | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
We can verify if $AA^{-1}=\mathbf{I}$ | A = sy.Matrix(A)
M = A*Ainv
round_expr(M, 4) | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
We got $\mathbf{I}$, which means the RHS block is indeed $A^{-1}$. An Example of Existence of Inverse Determine the values of $\lambda$ such that the matrix$$A=\left[ \begin{matrix}3 &\lambda &1\cr 2 & -1 & 6\cr 1 & 9 & 4\end{matrix}\right]$$is not invertible. Still,we are using SymPy to solve the problem. | lamb = sy.symbols('lamda') # SymPy will automatically render into LaTeX greek letters
A = np.array([[3, lamb, 1], [2, -1, 6], [1, 9, 4]])
I = np.eye(3)
AI = np.hstack((A, I))
AI = sy.Matrix(AI)
AI_rref = AI.rref()
AI_rref | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
To make the matrix $A$ invertible we notice that are one conditions to be satisfied (in every denominators):\begin{align}-6\lambda -465 &\neq0\\\end{align} Solve for $\lambda$'s. | sy.solvers.solve(-6*lamb-465, lamb) | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Let's test with determinant. If $|\pmb A|=0$, then the matrix is not invertible. Don't worry, we will come back to this. | A = np.array([[3, -155/2, 1], [2, -1, 6], [1, 9, 4]])
np.linalg.det(A) | _____no_output_____ | MIT | Chapter 2 - Basic Matrix Algebra.ipynb | Jesse3692/Linear_Algebra_With_Python |
Two Loop FDEM | from geoscilabs.base import widgetify
import geoscilabs.em.InductionLoop as IND
from ipywidgets import interact, FloatSlider, FloatText | _____no_output_____ | MIT | notebooks/em/InductionRLcircuit_Harmonic.ipynb | jcapriot/gpgLabs |
Parameter DescriptionsBelow are the adjustable parameters for widgets within this notebook:* $I_p$: Transmitter current amplitude [A]* $a_{Tx}$: Transmitter loop radius [m]* $a_{Rx}$: Receiver loop radius [m]* $x_{Rx}$: Receiver x position [m]* $z_{Rx}$: Receiver z position [m]* $\theta$: Receiver normal vector relati... | # RUN FREQUENCY DOMAIN WIDGET
widgetify(IND.fcn_FDEM_Widget,I=FloatSlider(min=1, max=10., value=1., step=1., continuous_update=False, description = "$I_0$"),\
a1=FloatSlider(min=1., max=20., value=10., step=1., continuous_update=False, description = "$a_{Tx}$"),\
a2=Float... | _____no_output_____ | MIT | notebooks/em/InductionRLcircuit_Harmonic.ipynb | jcapriot/gpgLabs |
ALBERTMRC可用的中文预训练参数:[`albert-tiny`](https://storage.googleapis.com/albert_zh/albert_tiny_zh_google.zip),[`albert-small`](https://storage.googleapis.com/albert_zh/albert_small_zh_google.zip),[`albert-base`](https://storage.googleapis.com/albert_zh/albert_base_zh_additional_36k_steps.zip),[`albert-large`](https://storag... | import uf
print(uf.__version__)
model = uf.ALBERTMRC('../../demo/albert_config.json', '../../demo/vocab.txt')
print(model)
X = [{'doc': '天亮以前说再见,笑着泪流满面。去迎接应该你的,更好的明天', 'ques': '何时说的再见'},
{'doc': '他想知道那是谁,为何总沉默寡言。人群中也算抢眼,抢眼的孤独难免', 'ques': '抢眼的如何'}]
y = [{'text': '天亮以前', 'answer_start': 0}, {'text': '孤独难免', 'answe... | _____no_output_____ | Apache-2.0 | examples/tutorial/ALBERTMRC.ipynb | dumpmemory/unif |
训练 | model.fit(X, y, total_steps=10) | WARNING:tensorflow:From /Users/geyingli/Library/Python/3.8/lib/python/site-packages/tensorflow/python/util/dispatch.py:1096: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
Instructions for updating:
Please use `rate` instead of `keep_prob`. Rate... | Apache-2.0 | examples/tutorial/ALBERTMRC.ipynb | dumpmemory/unif |
推理 | model.predict(X) | INFO:tensorflow:Time usage 0m-3.02s, 0.33 steps/sec, 0.66 examples/sec
| Apache-2.0 | examples/tutorial/ALBERTMRC.ipynb | dumpmemory/unif |
评分 | model.score(X, y) | INFO:tensorflow:Time usage 0m-2.28s, 0.44 steps/sec, 0.88 examples/sec
| Apache-2.0 | examples/tutorial/ALBERTMRC.ipynb | dumpmemory/unif |
Neural Network **Learning Objectives:** * Use the `DNNRegressor` class in TensorFlow to predict median housing price The data is based on 1990 census data from California. This data is at the city block level, so these features reflect the total number of rooms in that block, or the total number of people who live on... | import math
import shutil
import numpy as np
import pandas as pd
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/labs/c_neuralnetwork.ipynb | 09acp/training-data-analyst |
Next, we'll load our data set. | df = pd.read_csv("https://storage.googleapis.com/ml_universities/california_housing_train.csv", sep=",") | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/labs/c_neuralnetwork.ipynb | 09acp/training-data-analyst |
Examine the dataIt's a good idea to get to know your data a little bit before you work with it.We'll print out a quick summary of a few useful statistics on each column.This will include things like mean, standard deviation, max, min, and various quantiles. | df.head()
df.describe() | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/labs/c_neuralnetwork.ipynb | 09acp/training-data-analyst |
This data is at the city block level, so these features reflect the total number of rooms in that block, or the total number of people who live on that block, respectively. Let's create a different, more appropriate feature. Because we are predicing the price of a single house, we should try to make all our features ... | df['num_rooms'] = df['total_rooms'] / df['households']
df['num_bedrooms'] = df['total_bedrooms'] / df['households']
df['persons_per_house'] = df['population'] / df['households']
df.describe()
df.drop(['total_rooms', 'total_bedrooms', 'population', 'households'], axis = 1, inplace = True)
df.describe() | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/labs/c_neuralnetwork.ipynb | 09acp/training-data-analyst |
Build a neural network modelIn this exercise, we'll be trying to predict `median_house_value`. It will be our label (sometimes also called a target). We'll use the remaining columns as our input features.To train our model, we'll first use the [LinearRegressor](https://www.tensorflow.org/api_docs/python/tf/contrib/lea... | featcols = {
colname : tf.feature_column.numeric_column(colname) \
for colname in 'housing_median_age,median_income,num_rooms,num_bedrooms,persons_per_house'.split(',')
}
# Bucketize lat, lon so it's not so high-res; California is mostly N-S, so more lats than lons
featcols['longitude'] = tf.feature_column.bucket... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/labs/c_neuralnetwork.ipynb | 09acp/training-data-analyst |
Uncomment the following line to install [geemap](https://geemap.org) if needed. | # !pip install geemap
import ee
import geemap
geemap.show_youtube('k477ksjkaXw') | _____no_output_____ | MIT | examples/notebooks/03_inspector_tool.ipynb | Jack-ee/geemap |
Create an interactive map | Map = geemap.Map(center=(40, -100), zoom=4) | _____no_output_____ | MIT | examples/notebooks/03_inspector_tool.ipynb | Jack-ee/geemap |
Add Earth Engine Python script | # Add Earth Engine dataset
dem = ee.Image('USGS/SRTMGL1_003')
landcover = ee.Image("ESA/GLOBCOVER_L4_200901_200912_V2_3").select('landcover')
landsat7 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003').select(
['B1', 'B2', 'B3', 'B4', 'B5', 'B7']
)
states = ee.FeatureCollection("TIGER/2018/States")
# Set visualization ... | _____no_output_____ | MIT | examples/notebooks/03_inspector_tool.ipynb | Jack-ee/geemap |
Exploring Neural Audio Synthesis with NSynth Parag Mital There is a lot to explore with NSynth. This notebook explores just a taste of what's possible including how to encode and decode, timestretch, and interpolate sounds. Also check out the [blog post](https://magenta.tensorflow.org/nsynth-fastgen) for more exampl... | import os
import numpy as np
import matplotlib.pyplot as plt
from magenta.models.nsynth import utils
from magenta.models.nsynth.wavenet import fastgen
from IPython.display import Audio
%matplotlib inline
%config InlineBackend.figure_format = 'jpg' | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Now we'll load up a sound I downloaded from freesound.org. The `utils.load_audio` method will resample this to the required sample rate of 16000. I'll load in 40000 samples of this beat which should end up being a pretty good loop: | # from https://www.freesound.org/people/MustardPlug/sounds/395058/
fname = '395058__mustardplug__breakbeat-hiphop-a4-4bar-96bpm.wav'
sr = 16000
audio = utils.load_audio(fname, sample_length=40000, sr=sr)
sample_length = audio.shape[0]
print('{} samples, {} seconds'.format(sample_length, sample_length / float(sr))) | 40000 samples, 2.5 seconds
| Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
EncodingWe'll now encode some audio using the pre-trained NSynth model (download from: http://download.magenta.tensorflow.org/models/nsynth/wavenet-ckpt.tar). This is pretty fast, and takes about 3 seconds per 1 second of audio on my NVidia 1080 GPU. This will give us a 125 x 16 dimension encoding for every 4 second... | %time encoding = fastgen.encode(audio, 'model.ckpt-200000', sample_length) | INFO:tensorflow:Restoring parameters from model.ckpt-200000
CPU times: user 53.2 s, sys: 2.83 s, total: 56 s
Wall time: 20.2 s
| Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
This returns a 3-dimensional tensor representing the encoding of the audio. The first dimension of the encoding represents the batch dimension. We could have passed in many audio files at once and the process would be much faster. For now we've just passed in one audio file. | print(encoding.shape) | (1, 78, 16)
| Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
We'll also save the encoding so that we can use it again later: | np.save(fname + '.npy', encoding) | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Let's take a look at the encoding of this audio file. Think of these as 16 channels of sounds all mixed together (though with a lot of caveats): | fig, axs = plt.subplots(2, 1, figsize=(10, 5))
axs[0].plot(audio);
axs[0].set_title('Audio Signal')
axs[1].plot(encoding[0]);
axs[1].set_title('NSynth Encoding') | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
You should be able to pretty clearly see a sort of beat like pattern in both the signal and the encoding. DecodingNow we can decode the encodings as is. This is the process that takes awhile, though it used to be so long that you wouldn't even dare trying it. There is still plenty of room for improvement and I'm sur... | %time fastgen.synthesize(encoding, save_paths=['gen_' + fname], samples_per_save=sample_length) | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
After it's done synthesizing, we can see that takes about 6 minutes per 1 second of audio on a non-optimized version of Tensorflow for GPU on an NVidia 1080 GPU. We can speed things up considerably if we want to do multiple encodings at a time. We'll see that in just a moment. Let's first listen to the synthesized a... | sr = 16000
synthesis = utils.load_audio('gen_' + fname, sample_length=sample_length, sr=sr) | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Listening to the audio, the sounds are definitely different. NSynth seems to apply a sort of gobbly low-pass that also really doesn't know what to do with the high frequencies. It is really quite hard to describe, but that is what is so interesting about it. It has a recognizable, characteristic sound.Let's try ano... | def load_encoding(fname, sample_length=None, sr=16000, ckpt='model.ckpt-200000'):
audio = utils.load_audio(fname, sample_length=sample_length, sr=sr)
encoding = fastgen.encode(audio, ckpt, sample_length)
return audio, encoding
# from https://www.freesound.org/people/maurolupo/sounds/213259/
fname = '213259_... | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Aside from the quality of the reconstruction, what we're really after is what is possible with such a model. Let's look at two examples now. Part 2: TimestretchingLet's try something more fun. We'll stretch the encodings a bit and see what it sounds like. If you were to try and stretch audio directly, you'd hear a ... | # use image interpolation to stretch the encoding: (pip install scikit-image)
try:
from skimage.transform import resize
except ImportError:
!pip install scikit-image
from skimage.transform import resize | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Here's a utility function to help you stretch your own encoding. It uses skimage.transform and will retain the range of values. Images typically only have a range of 0-1, but the encodings aren't actually images so we'll keep track of their min/max in order to stretch them like images. | def timestretch(encodings, factor):
min_encoding, max_encoding = encoding.min(), encoding.max()
encodings_norm = (encodings - min_encoding) / (max_encoding - min_encoding)
timestretches = []
for encoding_i in encodings_norm:
stretched = resize(encoding_i, (int(encoding_i.shape[0] * factor), enco... | INFO:tensorflow:Restoring parameters from model.ckpt-200000
| Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Now let's stretch the encodings with a few different factors: | audio = utils.load_audio('gen_slower_' + fname, sample_length=None, sr=sr)
Audio(audio, rate=sr)
encoding_slower = timestretch(encoding, 1.5)
encoding_faster = timestretch(encoding, 0.5) | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Basically we've made a slower and faster version of the amen break's encodings. The original encoding is shown in black: | fig, axs = plt.subplots(3, 1, figsize=(10, 7), sharex=True, sharey=True)
axs[0].plot(encoding[0]);
axs[0].set_title('Encoding (Normal Speed)')
axs[1].plot(encoding_faster[0]);
axs[1].set_title('Encoding (Faster))')
axs[2].plot(encoding_slower[0]);
axs[2].set_title('Encoding (Slower)') | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Now let's decode them: | fastgen.synthesize(encoding_faster, save_paths=['gen_faster_' + fname])
fastgen.synthesize(encoding_slower, save_paths=['gen_slower_' + fname]) | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
It seems to work pretty well and retains the pitch and timbre of the original sound. We could even quickly layer the sounds just by adding them. You might want to do this in a program like Logic or Ableton Live instead and explore more possiblities of these sounds! Part 3: Interpolating SoundsNow let's try something... | sample_length = 80000
# from https://www.freesound.org/people/MustardPlug/sounds/395058/
aud1, enc1 = load_encoding('395058__mustardplug__breakbeat-hiphop-a4-4bar-96bpm.wav', sample_length)
# from https://www.freesound.org/people/xserra/sounds/176098/
aud2, enc2 = load_encoding('176098__xserra__cello-cant-dels-ocells... | INFO:tensorflow:Restoring parameters from model.ckpt-200000
INFO:tensorflow:Restoring parameters from model.ckpt-200000
| Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Now we'll mix the two audio signals together. But this is unlike adding the two signals together in a Ableton or simply hearing both sounds at the same time. Instead, we're averaging the representation of their timbres, tonality, change over time, and resulting audio signal. This is way more powerful than a simple a... | enc_mix = (enc1 + enc2) / 2.0
fig, axs = plt.subplots(3, 1, figsize=(10, 7))
axs[0].plot(enc1[0]);
axs[0].set_title('Encoding 1')
axs[1].plot(enc2[0]);
axs[1].set_title('Encoding 2')
axs[2].plot(enc_mix[0]);
axs[2].set_title('Average')
fastgen.synthesize(enc_mix, save_paths='mix.wav') | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
As another example of what's possible with interpolation of embeddings, we'll try crossfading between the two embeddings. To do this, we'll write a utility function which will use a hanning window to apply a fade in or out to the embeddings matrix: | def fade(encoding, mode='in'):
length = encoding.shape[1]
fadein = (0.5 * (1.0 - np.cos(3.1415 * np.arange(length) /
float(length)))).reshape(1, -1, 1)
if mode == 'in':
return fadein * encoding
else:
return (1.0 - fadein) * encoding
fig, axs = plt.subpl... | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Now we can cross fade two different encodings by adding their repsective fade ins and out: | def crossfade(encoding1, encoding2):
return fade(encoding1, 'out') + fade(encoding2, 'in')
fig, axs = plt.subplots(3, 1, figsize=(10, 7))
axs[0].plot(enc1[0]);
axs[0].set_title('Encoding 1')
axs[1].plot(enc2[0]);
axs[1].set_title('Encoding 2')
axs[2].plot(crossfade(enc1, enc2)[0]);
axs[2].set_title('Crossfade') | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Now let's synthesize the resulting encodings: | fastgen.synthesize(crossfade(enc1, enc2), save_paths=['crossfade.wav']) | _____no_output_____ | Apache-2.0 | jupyter-notebooks/NSynth.ipynb | cclauss/magenta-demos |
Multiple Regressiona - alphab - betai - ith usere - error termEquation - $y_{i}$ = $a_{}$ + $b_{1}$$x_{i1}$ + $b_{2}$$x_{i2}$ + ... + $b_{k}$$x_{ik}$ + $e_{i}$ beta = [alpha, beta_1, beta_2,..., beta_k]x_i = [1, x_i1, x_i2,..., x_ik] | inputs = [[123,123,243],[234,455,578],[454,565,900],[705,456,890]]
from typing import List
from scratch.linear_algebra import dot, Vector
def predict(x:Vector, beta: Vector) -> float:
return dot(x,beta)
def error(x:Vector, y:float, beta:Vector) -> float:
return predict(x,beta) - y
def squared_error(x:Vector,... | _____no_output_____ | Apache-2.0 | Data_Science_from_Scratch ~ Book/Data_Science_Chapter_15.ipynb | kushagras71/data_science |
Digression: The Bootstrap | from typing import TypeVar, Callable
X = TypeVar('X')
Stat = TypeVar('Stat')
def bootstrap_sample(data:List[X]) -> List[X]:
return [random.choice(data) for _ in data]
def bootstrap_statistics(data:List[X],
stats_fn: Callable[[List[X]],Stat],
num_samples: int) -> Lis... | _____no_output_____ | Apache-2.0 | Data_Science_from_Scratch ~ Book/Data_Science_Chapter_15.ipynb | kushagras71/data_science |
Regularization | def ridge_penalty(beta:Vector, alpha:float)->float:
return alpha*dot(beta[1:],beta[1:])
def squared_error_ridge(x: Vector,
y: float,
beta: Vector,
alpha: float) -> float:
return error(x, y, beta) ** 2 + ridge_penalty(beta, alpha)
from sc... | _____no_output_____ | Apache-2.0 | Data_Science_from_Scratch ~ Book/Data_Science_Chapter_15.ipynb | kushagras71/data_science |
A Two-sample t-test to find differentially expressed miRNA's between normal and tumor tissues in Lung Adenocarcinoma | import os
import pandas
mirna_src_dir = os.getcwd() + "/assn-mirna-luad/data/processed/miRNA/"
clinical_src_dir = os.getcwd() + "/assn-mirna-luad/data/processed/clinical/"
mirna_tumor_df = pandas.read_csv(mirna_src_dir+'tumor_miRNA.csv')
mirna_normal_df = pandas.read_csv(mirna_src_dir+'normal_miRNA.csv')
clinical_df ... | _____no_output_____ | FTL | notebooks/tumor_vs_normal_classification/tumor_vs_normal_miRNA-ttest.ipynb | JonnyTran/microRNA-Lung-Cancer-Associations |
Step 7: Serve data from OpenAgua into WEAP using WaMDaM By Adel M. Abdallah, Dec 2020Execute the following cells by pressing `Shift-Enter`, or by pressing the play button on the toolbar above. Steps1. Import python libraries2. Import the pulished SQLite file for the WEAP model from HydroShare.3. Prepare to connect to... | # 1. Import python libraries
### set the notebook mode to embed the figures within the cell
import numpy
import sqlite3
import numpy as np
import pandas as pd
import getpass
from hs_restclient import HydroShare, HydroShareAuthBasic
import os
import plotly
plotly.__version__
import plotly.offline as offline
import plo... | _____no_output_____ | BSD-3-Clause | 3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb | WamdamProject/WaMDaM_JupyterNotebooks |
2. Connect to the WaMDaM SQLite on HydroSahre Provide the HydroShare ID for your resourceExample https://www.hydroshare.org/resource/af71ef99a95e47a89101983f5ec6ad8b/ resource_id='85e9fe85b08244198995558fe7d0e294' | # enter your HydroShare username and password here between the quotes
username = ''
password = ''
auth = HydroShareAuthBasic(username=username, password=password)
hs = HydroShare(auth=auth)
print 'Connected to HydroShare'
# Then we can run queries against it within this notebook :)
resource_url='https://www.hydro... | _____no_output_____ | BSD-3-Clause | 3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb | WamdamProject/WaMDaM_JupyterNotebooks |
2. Prepare to the Connect to the WEAP API You need to have WEAP already installed on your machineFirst make sure to have a copy of the Water Evaluation And Planning" system (WEAP) installed on your local machine (Windows). If you don’t have it installed, download and install the WEAP software which allows you to run t... | # this library is needed to connect to the WEAP API
import win32com.client
# this command will open the WEAP software (if closed) and get the last active model
# you could change the active area to another one inside WEAP or by passing it to the command here
#WEAP.ActiveArea = "BearRiverFeb2017_V10.9"
WEAP=win32com.... | _____no_output_____ | BSD-3-Clause | 3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb | WamdamProject/WaMDaM_JupyterNotebooks |
4 Create a copy of the original WEAP Area to use while keeping the orignial as-as for any later use Add a new CacheCountyUrbanWaterUse scenario from the Reference original WEAP Area: You can always use this orignal one and delete any new copies you make afterwards. | # Create a copy of the WEAP AREA to serve the updated Hyrym Reservoir to it
# Delete the Area if it exists and then add it. Start from fresh
Area="Bear_River_WEAP_Model_2017_Conservation"
if not WEAP.Areas.Exists(Area):
WEAP.SaveAreaAs(Area)
WEAP.ActiveArea.Save
WEAP.ActiveArea = "Bear_River_WEAP_Model_2017_C... | _____no_output_____ | BSD-3-Clause | 3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb | WamdamProject/WaMDaM_JupyterNotebooks |
4.A Query Cache County seasonal "Monthly Demand" for the three sites: Logan Potable, North Cache Potable, South Cache Potable The data comes from OpenAgua | # Use Case 3.1Identify_aggregate_TimeSeriesValues.csv
# plot aggregated to monthly and converted to acre-feet time series data of multiple sources
# Logan Potable
# North Cache Potable
# South Cache Potable
# 2.2Identify_aggregate_TimeSeriesValues.csv
Query_UseCase_URL="""
https://raw.githubusercontent.com/WamdamPro... | _____no_output_____ | BSD-3-Clause | 3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb | WamdamProject/WaMDaM_JupyterNotebooks |
4.B Load the seasonal demand data with conservation into WEAP | # 9. Load the seasonal data into WEAP
#WEAP=win32com.client.Dispatch("WEAP.WEAPApplication")
# WEAP.Visible = FALSE
print WEAP.ActiveArea.Name
Scenarios=['Cons25PercCacheUrbWaterUse','Incr25PercCacheUrbWaterUse']
DemandSites=['Logan Potable','North Cache Potable','South Cache Potable']
AttributeName='Monthly Demand'... | _____no_output_____ | BSD-3-Clause | 3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb | WamdamProject/WaMDaM_JupyterNotebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.