markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Step 2: Generate a list of documents | urls = []
#https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1994795/
urls.append('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pmc&id=1994795')
#https://www.ncbi.nlm.nih.gov/pmc/articles/PMC314300/
urls.append('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pmc&id=314300')
#https://www.ncbi... | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 3: Preprocess the documents | documents = []
abstracts = []
texts = []
print 'Preprocessing documents. This may take few minutes ...'
for i, url in enumerate(urls):
print 'Preprocessing document %d ...' % (i+1)
# Download the document
my_url = urllib2.urlopen(url)
raw_doc = BeautifulSoup(my_url.read(), 'xml')
documents.append(r... | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 4: Split the documents into sentences | punkttokenizer = PunktSentenceTokenizer()
text_sentences = []
for text in texts:
sentences = []
seen = set()
for sentence in punkttokenizer.tokenize(text):
sentences.append(sentence)
text_sentences.append(sentences) | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 5: Count the term frequency for sentences | tf_matrices = []
tfidf_matrices = []
cosine_similarity_matrices = []
print 'Calculating sentence simiarities. This may take few minutes ...'
for i, sentences in enumerate(text_sentences):
print 'Calculating sentence simiarities of document %d ...' % (i+1)
tf_matrix = CountVectorizer().fit_transform(sentences)
... | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 6: Calculate TextRank | similarity_graphs = []
graph_ranks = []
highest_ranks = []
lowest_ranks = []
print 'Calculating TextRanks. This may take few minutes ...'
for i, cosine_similarity_matrix in enumerate(cosine_similarity_matrices):
print 'Calculating TextRanks of document %d ...' % (i+1)
similarity_graph = nx.from_scipy_sparse_ma... | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 7: Save extractive summaries | print 'Saving extractive summaries. This may take a few minutes ...'
for i, highest in enumerate(highest_ranks):
print 'Writing extractive summary for document %d ...' % (i+1)
out_file = '\\TextRank\\system\\article%d_system1.txt' % (i+1)
with open(out_file, 'w') as f:
for i in range(5):
... | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 8: Save ground truths. | print 'Saving ground truths. This may take a few minutes ...'
for i, abstract in enumerate(abstracts):
print 'Writing ground truth for document %d ...' % (i+1)
out_file = '\\TextRank\\reference\\article%d_reference1.txt' % (i+1)
with open(out_file, 'w') as f:
f.write(abstract.strip() + '\n')
print '... | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Step 9: Calculate ROUGE score | %cd C:\ROUGE
!java -jar rouge2.0_0.2.jar
df = pd.read_csv('results.csv')
print df.sort_values('Avg_F-Score', ascending=False) | TextRank_Automatic_Summarization_for_Medical_Articles.ipynb | avtlearns/automatic_text_summarization | gpl-3.0 |
Display sensitivity maps for EEG and MEG sensors
Sensitivity maps can be produced from forward operators that
indicate how well different sensor types will be able to detect
neural currents from different regions of the brain.
To get started with forward modeling see tut-forward. | # Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.source_space import compute_distance_to_sensors
from mne.source_estimate import SourceEstimate
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()... | 0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Compute sensitivity maps | grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed') | 0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Show gain matrix a.k.a. leadfield matrix with sensitivity map | picks_meg = mne.pick_types(fwd['info'], meg=True, eeg=False)
picks_eeg = mne.pick_types(fwd['info'], meg=False, eeg=True)
fig, axes = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
fig.suptitle('Lead field matrix (500 dipoles only)', fontsize=14)
for ax, picks, ch_type in zip(axes, [picks_meg, picks_eeg], ['meg', 'e... | 0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Compare sensitivity map with distribution of source depths | # source space with vertices
src = fwd['src']
# Compute minimum Euclidean distances between vertices and MEG sensors
depths = compute_distance_to_sensors(src=src, info=fwd['info'],
picks=picks_meg).min(axis=1)
maxdep = depths.max() # for scaling
vertices = [src[0]['vertno'], src[... | 0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Sensitivity is likely to co-vary with the distance between sources to
sensors. To determine the strength of this relationship, we can compute the
correlation between source depth and sensitivity values. | corr = np.corrcoef(depths, grad_map.data[:, 0])[0, 1]
print('Correlation between source depth and gradiomter sensitivity values: %f.'
% corr) | 0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Using interact for animation with data
A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave equations, such has the Korteweg–de Vries equation, which has the following analytical solution:
$$
\phi(x,t) = \frac{1}{2} c \mathrm{sech}^2 \left[ \frac{\sqrt{c}}{2} ... | def soliton(x, t, c, a):
i=(((c**(1/2))/2)*(x-c*t-a))
return ((1/2)*c*(np.cos(i)**(-2)))
assert np.allclose(soliton(np.array([0]),0.0,1.0,0.0), np.array([0.5])) | assignments/assignment05/InteractEx03.ipynb | phungkh/phys202-2015-work | mit |
To create an animation of a soliton propagating in time, we are going to precompute the soliton data and store it in a 2d array. To set this up, we create the following variables and arrays: | tmin = 0.0
tmax = 10.0
tpoints = 100
t = np.linspace(tmin, tmax, tpoints)
xmin = 0.0
xmax = 10.0
xpoints = 200
x = np.linspace(xmin, xmax, xpoints)
c = 1.0
a = 0.0 | assignments/assignment05/InteractEx03.ipynb | phungkh/phys202-2015-work | mit |
Compute a 2d NumPy array called phi:
It should have a dtype of float.
It should have a shape of (xpoints, tpoints).
phi[i,j] should contain the value $\phi(x[i],t[j])$. | phi=np.ndarray((xpoints,tpoints), dtype=float)
for i in range(200):
for j in range(100):
phi[i,j]=soliton(x[i],t[j],c,a)
assert phi.shape==(xpoints, tpoints)
assert phi.ndim==2
assert phi.dtype==np.dtype(float)
assert phi[0,0]==soliton(x[0],t[0],c,a) | assignments/assignment05/InteractEx03.ipynb | phungkh/phys202-2015-work | mit |
Write a plot_soliton_data(i) function that plots the soliton wave $\phi(x, t[i])$. Customize your plot to make it effective and beautiful. | def plot_soliton_data(i=0):
plt.figure(figsize=(9,6))
plt.plot(x,soliton(x,t[i],c,a))
plt.box(False)
plt.ylim(0,6000)
plt.grid(True)
plt.ylabel('soliton wave')
plt.xlabel('x')
plot_soliton_data(0)
assert True # leave this for grading the plot_soliton_data function | assignments/assignment05/InteractEx03.ipynb | phungkh/phys202-2015-work | mit |
Use interact to animate the plot_soliton_data function versus time. | interact(plot_soliton_data, i=(0,100,5))
assert True # leave this for grading the interact with plot_soliton_data cell | assignments/assignment05/InteractEx03.ipynb | phungkh/phys202-2015-work | mit |
Let's notice a few key things:
1. To make a list we use []
2. We separate individual elements with commas
3. The elements of a list can be any type
4. The elements need not be explicitly written
Other Properties of Lists
You can add two lists to create a new list.
You can append an element to the end of a list by usin... | la=[1,2,3]
lb=["1","2","3"]
print(la+lb)
la.append(4)
print(la)
lb+=la
print(lb) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Slicing
At one point, you will want to access certain elements of a list, this is done by slicing. There are a couple of ways to do this.
1. la[0] will give the first element of the list la. Note that lists are indexed starting at zero, not one.
2. la[n] will give the (n+1)th element of the list la.
3. la[-1] will give... | la=[1,2,3,4,5,6,7,8,9,10]
print(la[0])
print(la[3])
print(la[-1])
print(la[-3])
print(la[0:10:2])
print(la[3::2])
print(la[2:4:])
print(la[2:4]) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Exercises
Make 2 lists and add them together.
Take your list from 1., append the list ["I", "Love", "Python"] to it without using the append command, then print every second element.
Can you make a list of lists? Try it.
Consider the list x=[3,5,7,8,"Pi"].
4a. Type out what you would expect python to print alon... | t = {1,2,3,3,3,3,3,3,3,3,3,3,3,3,3,4,5}
print(t)
s = {1,4,5,7,8}
print(t-s)
print(s-t)
print(t^s)
print(t-s|s-t)
print(t^s==t-s|s-t) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Exercises
Write a set containing the letters of the word "dog".
Find the difference between the set in 1. and the set {"d", 5, "g"}
Remove all the duplicates in the list [1,2,4,3,3,3,5,2,3,4,5,6,3,5,7] and print the resulting object in two lines.
Tuples
Tuples are just like lists except that you cannot append element... | a = (1,2,3,4,5)
b = ('a', 'b', 'c')
print(a)
print(b)
print(a+b) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Dictionaries
Dictionaries are quite different from any container we have seen so far. A dictionary is a bunch of unordered key/value pairs. That is, each element of a dictionary has a key and a value and the elements are in no particular order. It is good to keep this unorderedness in mind later on, for now, let's look... | #Let's say we have some students take a test and we want to store their scores
scores = {'Sally':89, 'Lucy':75, 'Jeff':45, 'Jose':96}
print(scores)
#We can, however, not combine two different dictionaries
scores2 = {'Devin':64, 'John':23, 'Jake':75}
print(scores2)
print(scores+scores2) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Unlike with lists, we cannot access elements of the dictionary with slicing. We must instead use the keys. Let's see how to do this. | print(scores['Sally'])
print(scores2['John']) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
As we can see, the key returns us the value. This can be useful if you have a bunch of items that need to be paired together.
Accessing Just the Keys or Values
Want to get a list of the keys in a dictionary? How about the values? Fret not, there is a way! | print(scores.keys())
print(scores.values()) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Exercises
Build a dictionary of some constants in physics and math. Print out at least two of these values.
Give an example of something that would be best represented by a dictionary, think pairs.
In and Not In
No, this section isn't about fashion. It is about the in and not in operators. They return a boolean value... | print('Devin' in scores2)
print(2 in a)
print('Hello World' not in scores) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
Converting Between Containers
But what if I want my set to be a list or my tuple to be a set? To convert between types of containers, you can use any of the following functions:
list() : Converts any container type into a list, for dictionaries it will be the list of keys.
tuple() : Converts any container type into a t... | a = [1,2,3]
b = (1,2,3)
c = {1,2,3}
d = {1:2,3:4}
print(list(b))
print(list(c))
print(list(d))
print(tuple(a))
print(tuple(c))
print(tuple(d))
print(set(a))
print(set(b))
print(set(d)) | Python Workshop/Containers.ipynb | CalPolyPat/Python-Workshop | mit |
2.1 Gaussian Elimination | def naive_gaussian_elimination(matrix):
"""
A simple gaussian elimination to solve equations
Args:
matrix : numpy 2d array
Returns:
mat : The matrix processed by gaussian elimination
x : The roots of the equation
Raises:
ValueError:
... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Apply Gaussian elimination in tableau form for the system of three equations in three
unknowns:
$$
\large
\begin{matrix}
x + 2y - z = 3 & \
2x + y - 2z = 3 & \
-3x + y + z = -6
\end{matrix}
$$ | """
Input:
[[ 1 2 -1 3]
[ 2 1 -2 3]
[-3 1 1 -6]]
"""
input_mat = np.array([1, 2, -1, 3, 2, 1, -2, 3, -3, 1, 1, -6])
input_mat = input_mat.reshape(3, 4)
output_mat, x = naive_gaussian_elimination(input_mat)
print(output_mat)
print('[x, y, z] = {}'.format(x)) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Additional Examples
Put the system $x + 2y - z = 3,-3x + y + z = -6,2x + z = 8$ into tableau form and solve by Gaussian elimination. | input_mat = np.array([
[ 1, 2, -1, 3],
[-3, 1, 1, -6],
[ 2, 0, 1, 8]
])
output_mat, x = naive_gaussian_elimination(input_mat)
print(output_mat)
print('[x, y, z] = {}'.format(x)) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.1 Computer Problems
Put together the code fragments in this section to create a MATLAB program for “naive” Gaussian elimination (meaning no row exchanges allowed). Use it to solve the systems of Exercise 2.
See my implementation naive_gaussian_elimination in python.
Let $H$ denote the $n \times n$ Hilbert matrix, ... | def computer_problems2__2_1(n):
# generate Hilbert matrix H
H = scipy.linalg.hilbert(n)
# generate b
b = np.ones(n).reshape(n, 1)
# combine H:b in tableau form
mat = np.hstack((H, b))
# gaussian elimination
_, x = naive_gaussian_elimination(mat)
return x
with... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.2 The LU Factorization | def LU_factorization(matrix):
"""
LU decomposition
Arguments:
matrix : numpy 2d array
Return:
L : lower triangular matrix
U : upper triangular matrix
Raises:
ValueError:
- matrix is null
- matrix is not a 2d array
... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
DEFINITION 2.2
An $m \times n$ matrix $L$ is lower triangular if its entries satisfy $l_{ij} = 0$ for $i < j$. An $m \times n$ matrix $U$ is upper triangular if its entries satisfy $u_{ij} = 0$ for $i > j$.
Example
Find the LU factorization for the matrix $A$ in
$$
\large
\begin{bmatrix}
1 & 1 \
3 & -4 \
\end{bmatri... | A = np.array([
[1, 1],
[3, -4]
])
L, U = LU_factorization(A)
print('L = ')
print(L)
print()
print('U = ')
print(U) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Find the LU factorization of A =
$$
\large
\begin{bmatrix}
1 & 2 & -1 \
2 & 1 & -2 \
-3 & 1 & 1 \
\end{bmatrix}
$$ | A = np.array([
[ 1, 2, -1],
[ 2, 1, -2],
[-3, 1, 1]
])
L, U = LU_factorization(A)
print('L = ')
print(L)
print()
print('U = ')
print(U) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Solve system
$$
\large
\begin{bmatrix}
1 & 1 \
3 & -4 \
\end{bmatrix}
\begin{bmatrix}
x_1 \
x_2 \
\end{bmatrix}
=
\begin{bmatrix}
3 \
2 \
\end{bmatrix}
$$
, using the LU factorization | A = np.array([
[ 1, 1],
[ 3, -4]
])
b = np.array([3, 2]).reshape(2, 1)
L, U = LU_factorization(A)
# calculate Lc = b where Ux = c
mat = np.hstack((L, b))
c = naive_gaussian_elimination(mat)[1].reshape(2, 1)
# calculate Ux = c
mat = np.hstack((U, c))
x = naive_gaussian_elimination(mat)[1].reshape(2, 1)
# o... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Solve system
\begin{matrix}
x + 2y - z = 3 & \
2x + y - 2z = 3 & \
-3x + y + z = -6
\end{matrix}
using the LU factorization | A = np.array([
[ 1, 2, -1],
[ 2, 1, -2],
[-3, 1, 1]
])
b = np.array([3, 3, -6]).reshape(3, 1)
L, U = LU_factorization(A)
# calculate Lc = b where Ux = c
mat = np.hstack((L, b))
c = naive_gaussian_elimination(mat)[1].reshape(3, 1)
# calculate Ux = c
mat = np.hstack((U, c))
x = naive_gaussian_elimination... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Additional Examples
Solve
$$
\large
\begin{bmatrix}
2 & 4 & -2 \
1 & -2 & 1 \
4 & -4 & 8 \
\end{bmatrix}
\begin{bmatrix}
x_1 \
x_2 \
x_3 \
\end{bmatrix}
=
\begin{bmatrix}
6 \
3 \
0 \
\end{bmatrix}
$$
using the A = LU factorization | A = np.array([
[ 2, 4, -2],
[ 1, -2, 1],
[ 4, -4, 8]
])
b = np.array([6, 3, 0]).reshape(3, 1)
L, U = LU_factorization(A)
# calculate Lc = b where Ux = c
mat = np.hstack((L, b))
c = naive_gaussian_elimination(mat)[1].reshape(3, 1)
# calculate Ux = c
mat = np.hstack((U, c))
x = naive_gaussian_eliminati... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.2 Computer Problems
Use the code fragments for Gaussian elimination in the previous section to write a MATLAB script to take a matrix A as input and output L and U. No row exchanges are allowed - the program should be designed to shut down if it encounters a zero pivot. Check your program by factoring the matrices i... | # Exercise 2 - (a)
A = np.array([
[ 3, 1, 2],
[ 6, 3, 4],
[ 3, 1, 5]
])
L, U = LU_factorization(A)
print('L = ')
print(L)
print()
print('U = ')
print(U)
# Exercise 2 - (b)
A = np.array([
[ 4, 2, 0],
[ 4, 4, 2],
[ 2, 2, 3]
])
L, U = LU_factorization(A)
print('L = ')
print(L)
print()
prin... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Add two-step back substitution to your script from Computer Problem 1, and use it to solve the systems in Exercise 4. | def LU_factorization_with_back_substitution(A, b):
"""
LU decomposition with two-step back substitution
where Ax = b
Arguments:
A : coefficient matrix
b : constant vector
Return:
x : solution vector
"""
L, U = LU_factorization(A)
# row size
rows... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.3 Sources Of Error
DEFINITION 2.3
The infinity norm, or maximum norm, of the vector $x = (x_1, \cdots, x_n)$ is $||x||_{\infty} = \text{max}|x_i|, i = 1,\cdots,n$, that is, the maximum of the absolute values of the components of x.
DEFINITION 2.4
Let $x_a$ be an approximate solution of the linear system $Ax = b$. The ... | A = np.array([
[ 1, 1],
[ 3, -4]
])
b = np.array([3, 2])
xa = np.array([1, 1])
# Get correct solution
system = sympy.Matrix(((1, 1, 3), (3, -4, 2)))
solver = sympy.solve_linear_system(system, sympy.abc.x, sympy.abc.y)
# Packed as list
x = np.array([solver[sympy.abc.x].evalf(), solver[sympy.abc.y].evalf()])... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Find the forward and backward errors for the approximate solution [-1, 3.0001] of the system
$$
\large
\begin{align}
x_1 + x_2 &= 2 \
1.0001 x_1 + x_2 &= 2.0001 \
\end{align}
$$ | A = np.array([
[ 1, 1],
[ 1.0001, 1],
])
b = np.array([2, 2.0001])
# approximated solution
xa = np.array([-1, 3.0001])
# correct solution
x = LU_factorization_with_back_substitution(A, b.reshape(2, 1))
# Get backward error
residual = b - np.matmul(A, xa)
backward_error = np.max(np.abs(residual))
print... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
The relative backward error of system $Ax = b$ is defined to be $\large \frac{||r||{\infty}}{||b||{\infty}}$.
The relative forward error is $\large \frac{||x - x_a||{\infty}}{||x||{\infty}}$.
The error magnification factor for $Ax = b$ is the ratio of the two, or $\large \text{error magnification factor} = \frac{\text{re... | def matrix_norm(A):
rowsum = np.sum(np.abs(A), axis = 1)
return np.max(rowsum) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
THEOREM 2.6
The condition number of the n x n matrix A is
$$
\large cond(A) = ||A|| \cdot ||A^{-1}||
$$ | def condition_number(A):
inv_A = np.linalg.inv(A)
cond = matrix_norm(A) * matrix_norm(inv_A)
return cond | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Additional Examples
Find the determinant and the condition number (in the infinity norm) of the matrix
$$
\large
\begin{bmatrix}
811802 & 810901 \
810901 & 810001 \
\end{bmatrix}
$$ | A = np.array([
[ 811802, 810901],
[ 810901, 810001],
])
print('determinant of A is {}'.format(scipy.linalg.det(A)))
print('condition number : {:.4e}'.format(condition_number(A))) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
The solution of the system
$$
\large
\begin{bmatrix}
2 & 4.01 \
3 & 6 \
\end{bmatrix}
\begin{bmatrix}
x_1 \
x_2 \
\end{bmatrix}
=
\begin{bmatrix}
6.01 \
9 \
\end{bmatrix}
$$
is $[1, 1]$
(a) Find the relative forward and backward errors and error magnification (in the infinity norm) for the approximate solution [2... | A = np.array([
[ 2, 4.01],
[ 3, 6.00],
])
b = np.array([6.01, 9])
# approximated solution
xa = np.array([21, -9])
# correct solution
x = LU_factorization_with_back_substitution(A, b.reshape(2, 1))
# forward error
forward_error = np.max(np.abs(x - xa))
# relative forward error
relative_forward_error = forwa... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
(b) Find the condition number of the coefficient matrix. | A = np.array([
[ 2, 4.01],
[ 3, 6.00],
])
print('condition number : {}'.format(condition_number(A))) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.3 Computer Problems
For the n x n matrix with entries $A_{ij} = 5 / (i + 2j - 1)$, set $x = [1,\cdots,1]^T$ and $b = Ax$. Use the MATLAB program from Computer Problem 2.1.1 or MATLAB’s backslash command to compute $x_c$, the double precision computed solution. Find the infinity norm of the forward error and the error... | def system_provider(n, data_generator):
A = np.zeros([n, n])
x = np.ones(n)
for i in range(n):
for j in range(n):
A[i, j] = data_generator(i + 1, j + 1)
b = np.matmul(A, x)
return A, x, b
def problem_2_3_1_generic_solver(n, data_generator):
A, x, b = s... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Carry out Computer Problem 1 for the matrix with entries $A_{ij} = 1/(|i - j| + 1)$. | def problem_2_3_2_solver(n):
return problem_2_3_1_generic_solver(n, lambda i, j : 1 / (np.abs(i - j) + 1))
# (a) n = 6
print('(a) n = 6, forward error = {:.3g}, error magnification factor = {:.3g}, condition number = {:.3g}'.format(*problem_2_3_2_solver(6)))
# (b) n = 10
print('(b) n = 10, forward error = {:.3g}... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Let A be the n x n matrix with entries $A_{ij} = |i - j| + 1$. Define $x = [1,\cdots,1]^T$ and $b = Ax$. For n = 100,200,300,400, and 500, use the MATLAB program from Computer Problem 2.1.1 or MATLAB’s backslash command to compute $x_c$, the double precision computed solution. Calculate the infinity norm of the forward e... | def problem_2_3_3_solver(n):
return problem_2_3_1_generic_solver(n, lambda i, j : np.abs(i - j) + 1)
# n = 100
print('n = 100, forward error = {:.2g}, error magnification factor = {:.2g}, condition number = {:.2g}'.format(*problem_2_3_3_solver(100)))
# n = 200
print('n = 200, forward error = {:.2g}, error magnif... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Carry out the steps of Computer Problem 3 for the matrix with entries $A_{ij} = \sqrt{(i - j)^2 + n / 10}$. | def problem_2_3_4_solver(n):
return problem_2_3_1_generic_solver(n, lambda i, j : np.sqrt(np.power(i - j, 2) + n / 10))
# n = 100
print('n = 100, forward error = {:.2g}, error magnification factor = {:.2g}, condition number = {:.2g}'.format(*problem_2_3_4_solver(100)))
# n = 200
print('n = 200, forward error = {... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
For what values of n does the solution in Computer Problem 1 have no correct significant digits? | print('n = 11, forward error = {:.3g}, error magnification factor = {:.3g}, condition number = {:.3g}'.format(*problem_2_3_1_solver(11))) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.4 The PA=LU Factorization
Example
Apply Gaussian elimination with partial pivoting to solve the system
\begin{matrix}
x_1 - x_2 + 3x_3 = -3 & \
-1x_1 - 2x_3 = 1 & \
2x_1 + 2x_2 + 4x_3 = 0
\end{matrix} | A = np.array([1, -1, 3, -1, 0, -2, 2, 2, 4]).reshape(3, 3)
b = np.array([-3, 1, 0])
lu, piv = linalg.lu_factor(A)
x = linalg.lu_solve([lu, piv], b)
print(x) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Solve the system $2x_1 + 3x_2 = 4$,$3x_1 + 2x_2 = 1$ using the PA = LU factorization with partial pivoting | """
[[2, 3]
[3, 2]]
"""
A = np.array([2, 3, 3, 2]).reshape(2, 2)
b = np.array([4, 1])
lu, piv = linalg.lu_factor(A)
x = linalg.lu_solve([lu, piv], b)
print(x) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.5 Iterative Methods
Jacobi Method | def jacobi_method(A, b, x0, k):
"""
Use jacobi method to solve equations
Args:
A (numpy 2d array): the matrix
b (numpy 1d array): the right hand side vector
x0 (numpy 1d array): initial guess
k (real number): iterations
Return:
The approximate sol... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Apply the Jacobi Method to the system $3u + v = 5$, $u + 2v = 5$ | A = np.array([3, 1, 1, 2]).reshape(2, 2)
b = np.array([5, 5])
x = jacobi_method(A, b, np.array([0, 0]), 20)
print('x = %s' %x) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Gauss-Seidel Method | def gauss_seidel_method(A, b, x0, k):
"""
Use gauss seidel method to solve equations
Args:
A (numpy 2d array): the matrix
b (numpy 1d array): the right hand side vector
x0 (numpy 1d array): initial guess
k (real number): iterations
Return:
The app... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Apply the Gauss-Seidel Method to the system
$$
\begin{bmatrix}
3 & 1 & -1 \
2 & 4 & 1 \
-1 & 2 & 5
\end{bmatrix}
\begin{bmatrix}
u \
v \
w
\end{bmatrix}
=
\begin{bmatrix}
4 \
1 \
1
\end{bmatrix}
$$ | A = np.array([3, 1, -1, 2, 4, 1, -1, 2, 5]).reshape(3, 3)
b = np.array([4, 1, 1])
x0 = np.array([0, 0, 0])
gauss_seidel_method(A, b, x0, 24) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Successive Over-Relaxation | def gauss_seidel_sor_method(A, b, w, x0, k):
"""
Use gauss seidel method with sor to solve equations
Args:
A (numpy 2d array): the matrix
b (numpy 1d array): the right hand side vector
w (real number): weight
x0 (numpy 1d array): initial guess
k (real number)... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Apply the Gauss-Seidel Method with sor to the system
$$
\begin{bmatrix}
3 & 1 & -1 \
2 & 4 & 1 \
-1 & 2 & 5
\end{bmatrix}
\begin{bmatrix}
u \
v \
w
\end{bmatrix}
=
\begin{bmatrix}
4 \
1 \
1
\end{bmatrix}
$$ | A = np.array([3, 1, -1, 2, 4, 1, -1, 2, 5]).reshape(3, 3)
b = np.array([4, 1, 1])
x0 = np.array([0, 0, 0])
w = 1.25
gauss_seidel_sor_method(A, b, w, x0, 14) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
2.6 Methods for symmetric positive-definite matrices
Cholesky factorization
Example
Find the Cholesky factorization of
$\begin{bmatrix}
4 & -2 & 2 \
-2 & 2 & -4 \
2 & -4 & 11
\end{bmatrix}$ | A = np.array([4, -2, 2, -2, 2, -4, 2, -4, 11]).reshape(3, 3)
R = linalg.cholesky(A)
print(R) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Conjugate Gradient Method | def conjugate_gradient_method(A, b, x0, k):
"""
Use conjugate gradient to solve linear equations
Args:
A : input matrix
b : input right hand side vector
x0 : initial guess
k : iteration
Returns:
approximate solution
"""
xk = x0
... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Solve
$$
\begin{bmatrix}
2 & 2 \
2 & 5 \
\end{bmatrix}
\begin{bmatrix}
u \
v
\end{bmatrix}
=
\begin{bmatrix}
6 \
3
\end{bmatrix}
$$
using the Conjugate Gradient Method | A = np.array([2, 2, 2, 5]).reshape(2, 2)
b = np.array([6, 3])
x0 = np.array([0, 0])
conjugate_gradient_method(A, b, x0, 2) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Solve
$$
\begin{bmatrix}
1 & -1 & 0 \
-1 & 2 & 1 \
0 & 1 & 2 \
\end{bmatrix}
\begin{bmatrix}
u \
v \
w \
\end{bmatrix}
=
\begin{bmatrix}
0 \
2 \
3 \
\end{bmatrix}
$$ | A = np.array([1, -1, 0, -1, 2, 1, 0, 1, 2]).reshape(3, 3)
b = np.array([0, 2, 3])
x0 = np.array([0, 0, 0])
conjugate_gradient_method(A, b, x0, 10) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Solve
$$
\begin{bmatrix}
1 & -1 & 0 \
-1 & 2 & 1 \
0 & 1 & 5 \
\end{bmatrix}
\begin{bmatrix}
u \
v \
w \
\end{bmatrix}
=
\begin{bmatrix}
3 \
-3 \
4 \
\end{bmatrix}
$$ | A = np.array([1, -1, 0, -1, 2, 1, 0, 1, 5]).reshape(3, 3)
b = np.array([3, -3, 4])
x0 = np.array([0, 0, 0])
x = slinalg.cg(A, b, x0)[0]
print('x = %s' %x ) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Preconditioning
2.7 Nonlinear Systems Of Equations
Multivariate Newton's Method | def multivariate_newton_method(fA, fDA, x0, k):
"""
Args:
fA (function handle) : coefficient matrix with arguments
fDA (function handle) : right-hand side vector with arguments
x0 (numpy 2d array) : initial guess
k (real number) : iteration
Return:
A... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Use Newton's method with starting guess $(1,2)$ to find a solution of the system
$$
v - u^3 = 0 \
u^2 + v^2 - 1 = 0
$$ | fA = lambda u,v : np.array([v - pow(u, 3), pow(u, 2) + pow(v, 2) - 1], dtype=np.float64)
fDA = lambda u,v : np.array([-3 * pow(u, 2), 1, 2 * u, 2 * v], dtype=np.float64).reshape(2, 2)
x0 = np.array([1, 2])
multivariate_newton_method(fA, fDA, x0, 10) | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Example
Use Newton's method to find the solutions of the system
$$
f_1(u,v) = 6u^3 + uv - 3^3 - 4 = 0 \
f_2(u,v) = u^2 - 18uv^2 + 16v^3 + 1 = 0
$$ | fA = lambda u,v : np.array([6 * pow(u, 3) + u * v - 3 * pow(v, 3) - 4,
pow(u, 2) - 18 * u * pow(v, 2) + 16 * pow(v, 3) + 1],
dtype=np.float64)
fDA = lambda u,v : np.array([18 * pow(u, 2) + v,
u - 9 * pow(v, 2),
... | 2_Systems_Of_Equations.ipynb | Jim00000/Numerical-Analysis | unlicense |
Attributes and functions
Each solver has some attributes:
solver_name
The name of the solver. This is the name which will be used to select the solver in cobrapy functions. | solver.solver_name
model.optimize(solver="cglpk") | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
_SUPPORTS_MILP
The presence of this attribute tells cobrapy that the solver supports mixed-integer linear programming | solver._SUPPORTS_MILP | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
solve
Model.optimize is a wrapper for each solver's solve function. It takes in a cobra model and returns a solution | solver.solve(model) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
create_problem
This creates the LP object for the solver. | lp = solver.create_problem(model, objective_sense="maximize")
lp | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
solve_problem
Solve the LP object and return the solution status | solver.solve_problem(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
format_solution
Extract a cobra.Solution object from a solved LP object | solver.format_solution(lp, model) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
get_objective_value
Extract the objective value from a solved LP object | solver.get_objective_value(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
get_status
Get the solution status of a solved LP object | solver.get_status(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
change_variable_objective
change the objective coefficient a reaction at a particular index. This does not change any of the other objectives which have already been set. This example will double and then revert the biomass coefficient. | model.reactions.index("Biomass_Ecoli_core")
solver.change_variable_objective(lp, 12, 2)
solver.solve_problem(lp)
solver.get_objective_value(lp)
solver.change_variable_objective(lp, 12, 1)
solver.solve_problem(lp)
solver.get_objective_value(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
change variable_bounds
change the lower and upper bounds of a reaction at a particular index. This example will set the lower bound of the biomass to an infeasible value, then revert it. | solver.change_variable_bounds(lp, 12, 1000, 1000)
solver.solve_problem(lp)
solver.change_variable_bounds(lp, 12, 0, 1000)
solver.solve_problem(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
change_coefficient
Change a coefficient in the stoichiometric matrix. In this example, we will set the entry for ADP in the ATMP reaction to in infeasible value, then reset it. | model.metabolites.index("atp_c")
model.reactions.index("ATPM")
solver.change_coefficient(lp, 16, 10, -10)
solver.solve_problem(lp)
solver.change_coefficient(lp, 16, 10, -1)
solver.solve_problem(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
set_parameter
Set a solver parameter. Each solver will have its own particular set of unique paramters. However, some have unified names. For example, all solvers should accept "tolerance_feasibility." | solver.set_parameter(lp, "tolerance_feasibility", 1e-9)
solver.set_parameter(lp, "objective_sense", "minimize")
solver.solve_problem(lp)
solver.get_objective_value(lp)
solver.set_parameter(lp, "objective_sense", "maximize")
solver.solve_problem(lp)
solver.get_objective_value(lp) | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
Example with FVA
Consider flux variability analysis (FVA), which requires maximizing and minimizing every reaction with the original biomass value fixed at its optimal value. If we used the cobra Model API in a naive implementation, we would do the following: | %%time
# work on a copy of the model so the original is not changed
m = model.copy()
# set the lower bound on the objective to be the optimal value
f = m.optimize().f
for objective_reaction, coefficient in m.objective.items():
objective_reaction.lower_bound = coefficient * f
# now maximize and minimze every react... | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
Instead, we could use the solver API to do this more efficiently. This is roughly how cobrapy implementes FVA. It keeps uses the same LP object and repeatedly maximizes and minimizes it. This allows the solver to preserve the basis, and is much faster. The speed increase is even more noticeable the larger the model get... | %%time
# create the LP object
lp = solver.create_problem(model)
# set the lower bound on the objective to be the optimal value
solver.solve_problem(lp)
f = solver.get_objective_value(lp)
for objective_reaction, coefficient in model.objective.items():
objective_index = model.reactions.index(objective_reaction)
... | documentation_builder/solvers.ipynb | jeicher/cobrapy | lgpl-2.1 |
1. Background Information
1.1 Introduction to the Second Half of the Class
The remainder of this course will be divided into three two week modules, each dealing with a different dataset. During the first week of each module, you will complete a (two class) lab in which you are introduced to the dataset and various tec... | # these set the pandas defaults so that it will print ALL values, even for very long lists and large dataframes
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None) | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
Read in the QuaRCS data as a pandas dataframe called "data". | data=pd.read_csv('AST200_data_anonymized.csv', encoding="ISO-8859-1")
mask = np.where(data == 999)
data = data.replace(999,np.nan) | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
Once a dataset has been read in as a pandas dataframe, several useful built-in pandas methods are made available to us. Recall that you call methods with data.method. Check out each of the following | # the * is a trick to print without the ...s for an ordinary python object
print(*data.columns)
data.dtypes | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
2.2 The describe() method
There are also a whole bunch of built in functions that can operate on a pandas dataframe that become available once you've defined it. To see a full list type data. in an empty frame and then hit tab.
An especially useful one is dataframe.describe() method, which creates a summary table with... | data.describe() | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
2.3. Computing Descriptive Statistics
You can also of course compute descriptive statistics for columns in a pandas dataframe individually. Examples of each one applied to a single column - student scores on the assessment (PRE_SCORE) are shown below. | np.mean(data["PRE_SCORE"])
#or
data["PRE_SCORE"].mean()
np.nanmedian(data["PRE_SCORE"])
#or
data["PRE_SCORE"].median()
data["PRE_SCORE"].max()
data["PRE_SCORE"].min()
data["PRE_SCORE"].mode()
#where first number is the index (should be zero unless column has multiple dimensions
# and second number is the mode
#n... | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
<div class=hw>
### Exercise 1
------------------
Choose one categorical (answer to any demographic or attitudinal question) and one continuous variable (e.g. PRE_TIME, ZPR_1) and compute all of the statistics from the list above ***in one code cell*** (use print statements) for each variable. Write a paragraph describ... | #your code computing all descriptive statistics for your categorical variable here
#your code computing all descriptive statistics for your categorical variable here | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
2.4. Creating Statistical Graphics
<div class=hw>
### Exercise 2 - Summary plots for distributions
*Warning: Although you will be using QuaRCS data to investigate and experiment with each type of plot below, when you write up your descriptions, they should refer to the **general properties** of the plots, and not to t... | #this cell is for playing around with histograms | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
Your explanation here, with figures
<div class=hw>
### 2b - Box plot
The syntax for creating a box plot for a pair of pandas dataframe columns is:
dataframe.boxplot(column="column name 1", by="column name 2")
Play around with the column and by variables and refer to the docstring as needed until you understand thor... | #your sample boxplot code here | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
Your explanation here
<div class=hw>
### 2c - Pie Chart
The format for making the kind of pie chart that might be useful in this context is as follows:
newdataframe = dataframe["column name"].value()counts
newdataframe.plot.pie(figsize=(6,6))
Play around with the column and refer to the docstring as needed until y... | #your sample pie chart code here | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
Your explanation here
<div class=hw>
### 2d - Scatter Plot
The syntax for creating a scatter plot is:
dataframe.plot.scatter(x='column name',y='column name')
Play around with the column and refer to the docstring as needed until you understand thoroughly what is being shown. Describe what this ***type of plot*** (no... | #your sample scatter plot code here | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
Your explanation here
2.5. Selecting a Subset of Data
<div class=hw>
### Exercise 3
--------------
Write a function called "filter" that takes a dataframe, column name, and value for that column as input and returns a new dataframe containing only those rows where column name = value. For example filter(data, "PRE_GE... | #your function here
#your tests here | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
If you get to this point during lab time on Tuesday, stop here
3. Testing Differences Between Datasets
3.1 Computing Confidence Intervals
Now that we have a mechanism for filtering the dataset, we can test differences between groups with confidence intervals. The syntax for computing the confidence interval on a mean f... | ## apply filter to select only men from data, and pull the scores from this group into a variable
df2=filter(data,'PRE_GENDER',1)
men_scores=df2['PRE_SCORE']
#compute 95% confidence intervals on the mean (low and high)
men_conf=st.t.interval(0.95, len(men_scores)-1, loc=np.mean(men_scores), scale=st.sem(men_scores))
m... | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
<div class=hw>
### Exercise 4
------------------
Choose a categorical variable (any demographic or attitudinal variable) that you find interesting and that has at least four possible values and calculate the condifence intervals on the mean score for each group. Then write a paragraph describing the results. Are the d... | #code to filter data and compute confidence intervals for each answer choice | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
explanatory text
3.2 Visualizing Differences with Overlapping Plots
<div class=hw>
### Exercise 5
---------------
Make another dataframe consisting only of students who "devoted effort" to the assessment, meaning their answer for PRE_EFFORT was EITHER a 4 or a 5 (you may have to modify your filter function to accept ... | #modified filter function here
#define your new high effort dataframe using the filter
#plot two overlapping histograms | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
explanatory text here
4. Data Investigation - Week 2 Instructions
Now that you are familar with the QuaRCS dataset, you and your partner must come up with an investigation that you would like to complete using this data. For the next two modules, this will be more open, but for this first investigation, I will suggest ... | from IPython.core.display import HTML
def css_styling():
styles = open("../custom.css", "r").read()
return HTML(styles)
css_styling() | Labs/Lab9/Lab 9.ipynb | kfollette/ASTR200-Spring2017 | mit |
from pysal.explore import spaghetti as spgh
from pysal.lib import examples
import geopandas as gpd
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from shapely.geometry import Point, LineString
%matplotlib inline
__author__ = "James Gaboardi <jgaboardi@gmail.com>" | notebooks/explore/spaghetti/Spaghetti_Pointpatterns_Empirical.ipynb | weikang9009/pysal | bsd-3-clause | |
1. Instantiating a pysal.spaghetti.Network
Instantiate the network from .shp file | ntw = spgh.Network(in_data=examples.get_path('streets.shp')) | notebooks/explore/spaghetti/Spaghetti_Pointpatterns_Empirical.ipynb | weikang9009/pysal | bsd-3-clause |
2. Allocating observations to a network
Snap point patterns to the network | # Crimes with attributes
ntw.snapobservations(examples.get_path('crimes.shp'),
'crimes',
attribute=True)
# Schools without attributes
ntw.snapobservations(examples.get_path('schools.shp'),
'schools',
attribute=False) | notebooks/explore/spaghetti/Spaghetti_Pointpatterns_Empirical.ipynb | weikang9009/pysal | bsd-3-clause |
3. Visualizing original and snapped locations
True and snapped school locations | schools_df = spgh.element_as_gdf(ntw,
pp_name='schools',
snapped=False)
snapped_schools_df = spgh.element_as_gdf(ntw,
pp_name='schools',
snapped=True) | notebooks/explore/spaghetti/Spaghetti_Pointpatterns_Empirical.ipynb | weikang9009/pysal | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.