Skip to content

Commit d165818

Browse files
authored
Merge pull request #9 from rickecon/chaps
Merging
2 parents d047fa7 + 4135069 commit d165818

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+10176
-116
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [0.0.4] - 2023-10-27 02:00:00
9+
10+
### Added
11+
- Updates the Python and Git chapters as well as the corresponding data, images, and code
12+
813
## [0.0.3] - 2023-10-23 03:00:00
914

1015
### Added
@@ -33,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3338

3439

3540

41+
[0.0.4]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.3...v0.0.4
3642
[0.0.3]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.2...v0.0.3
3743
[0.0.2]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.1...v0.0.2
3844
[0.0.1]: https://github.com/OpenSourceEcon/CompMethods/compare/v0.0.0...v0.0.1

README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,8 @@ Please use the following citation form for this book.
2020
General citation to the book:
2121
* Evans, Richard W., *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods/.
2222

23-
Citation to a chapter in the book:
24-
* Evans, Richard W., "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods/ + [chapter path].
23+
Citation to a chapter in the book only authored by Evans:
24+
* Evans, Richard W., "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods + [chapter path].
25+
26+
Citation to a chapter in the book only authored by multiple authors:
27+
* DeBacker, Jason and Richard W. Evans, "[insert chapter name]", in *Computational Methods for Economists using Python*, Open access Jupyter Book, v#.#.#, 2023, https://opensourceecon.github.io/CompMethods + [chapter path].
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# advanced_numpy.py
2+
"""Python Essentials: Advanced NumPy.
3+
<Name>
4+
<Class>
5+
<Date>
6+
"""
7+
import numpy as np
8+
from sympy import isprime
9+
from matplotlib import pyplot as plt
10+
11+
12+
def prob1(A):
13+
"""Make a copy of 'A' and set all negative entries of the copy to 0.
14+
Return the copy.
15+
16+
Example:
17+
>>> A = np.array([-3,-1,3])
18+
>>> prob4(A)
19+
array([0, 0, 3])
20+
"""
21+
raise NotImplementedError("Problem 1 Incomplete")
22+
23+
24+
def prob2(arr_list):
25+
"""return all arrays in arr_list as one 3-dimensional array
26+
where the arrays are padded with zeros appropriately."""
27+
raise NotImplementedError("Problem 2 Incomplete")
28+
29+
30+
def prob3(func, A):
31+
"""Time how long it takes to run func on the array A in two different ways,
32+
where func is a universal function.
33+
First, use array broadcasting to operate on the entire array element-wise.
34+
Second, use a nested for loop, operating on each element individually.
35+
Return the ratio showing how many times faster array broadcasting is than
36+
using a nested for loop, averaged over 10 trials.
37+
38+
Parameters:
39+
func -- array broadcast-able numpy function
40+
A -- nxn array to operate on
41+
Returns:
42+
num_times_faster -- float
43+
"""
44+
raise NotImplementedError("Problem 3 Incomplete")
45+
46+
47+
def prob4(A):
48+
"""Divide each row of 'A' by the row sum and return the resulting array.
49+
50+
Example:
51+
>>> A = np.array([[1,1,0],[0,1,0],[1,1,1]])
52+
>>> prob6(A)
53+
array([[ 0.5 , 0.5 , 0. ],
54+
[ 0. , 1. , 0. ],
55+
[ 0.33333333, 0.33333333, 0.33333333]])
56+
"""
57+
raise NotImplementedError("Problem 4 Incomplete")
58+
59+
60+
# this is provided for problem 5
61+
def LargestPrime(x, show_factorization=False):
62+
# account for edge cases.
63+
if x == 0 or x == 1:
64+
return np.nan
65+
66+
# create needed variables
67+
forced_break = False
68+
prime_factors = [] # place to store factors of number
69+
factor_test_arr = np.arange(1, 11)
70+
71+
while True:
72+
# a factor is never more than half the number
73+
if np.min(factor_test_arr) > (x // 2) + 1:
74+
forced_break = True
75+
break
76+
if isprime(x): # if the checked number is prime itself, stop
77+
prime_factors.append(x)
78+
break
79+
80+
# check if anythin gin the factor_test_arr are factors
81+
div_arr = x / factor_test_arr
82+
factor_mask = div_arr - div_arr.astype(int) == 0
83+
divisors = factor_test_arr[factor_mask]
84+
if divisors.size > 0: # if divisors exist...
85+
if (
86+
divisors[0] == 1 and divisors.size > 1
87+
): # make sure not to select 1
88+
i = 1
89+
elif (
90+
divisors[0] == 1 and divisors.size == 1
91+
): # if one is the only one don't pick it
92+
factor_test_arr = factor_test_arr + 10
93+
continue
94+
else: # othewise take the smallest divisor
95+
i = 0
96+
97+
# if divisor was found divide number by it and
98+
# repeat the process
99+
x = int(x / divisors[i])
100+
prime_factors.append(divisors[i])
101+
factor_test_arr = np.arange(1, 11)
102+
else: # if no number was found increase the test_arr
103+
# and keep looking for factors
104+
factor_test_arr = factor_test_arr + 10
105+
continue
106+
107+
if show_factorization: # show entire factorization if desired
108+
print(prime_factors)
109+
if forced_break: # if too many iterations break
110+
print(f"Something wrong, exceeded iteration threshold for value: {x}")
111+
return 0
112+
return max(prime_factors)
113+
114+
115+
def prob5(arr, naive=False):
116+
"""Return an array where every number is replaced be the largest prime
117+
in its factorization. Implement two methods. Switching between the two
118+
is determined by a bool.
119+
120+
Example:
121+
>>> A = np.array([15, 41, 49, 1077])
122+
>>> prob4(A)
123+
array([5,41,7,359])
124+
"""
125+
raise NotImplementedError("Problem 5 Incomplete")
126+
127+
128+
def prob6(x, y, z, A, optimize=False, split=True):
129+
"""takes three vectors and a matrix and performs
130+
(np.outer(x,y)*z.reshape(-1,1))@A on them using einsum."""
131+
raise NotImplementedError("Problem 6 part 1 Incomplete")
132+
133+
134+
def naive6(x, y, z, A):
135+
"""uses normal numpy functions to do what prob5 does"""
136+
raise NotImplementedError("Problem 6 part 2 Incomplete")
137+
138+
139+
def prob7():
140+
"""Times and creates plots that generate the difference in
141+
speeds between einsum and normal numpy functions
142+
"""
143+
raise NotImplementedError("Problem 7 Incomplete")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
A b C
2+
d E f
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Ab Cd
2+
Ef Gh
3+
Ij Kl
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# exceptions_fileIO.py
2+
"""Python Essentials: Exceptions and File Input/Output.
3+
<Name>
4+
<Class>
5+
<Date>
6+
"""
7+
8+
from random import choice
9+
10+
11+
# Problem 1
12+
def arithmagic():
13+
"""
14+
Takes in user input to perform a magic trick and prints the result.
15+
Verifies the user's input at each step and raises a
16+
ValueError with an informative error message if any of the following occur:
17+
18+
The first number step_1 is not a 3-digit number.
19+
The first number's first and last digits differ by less than $2$.
20+
The second number step_2 is not the reverse of the first number.
21+
The third number step_3 is not the positive difference of the first two numbers.
22+
The fourth number step_4 is not the reverse of the third number.
23+
"""
24+
25+
step_1 = input(
26+
"Enter a 3-digit number where the first and last "
27+
"digits differ by 2 or more: "
28+
)
29+
step_2 = input(
30+
"Enter the reverse of the first number, obtained "
31+
"by reading it backwards: "
32+
)
33+
step_3 = input("Enter the positive difference of these numbers: ")
34+
step_4 = input("Enter the reverse of the previous result: ")
35+
print(str(step_3), "+", str(step_4), "= 1089 (ta-da!)")
36+
37+
38+
# Problem 2
39+
def random_walk(max_iters=1e12):
40+
"""
41+
If the user raises a KeyboardInterrupt by pressing ctrl+c while the
42+
program is running, the function should catch the exception and
43+
print "Process interrupted at iteration $i$".
44+
If no KeyboardInterrupt is raised, print "Process completed".
45+
46+
Return walk.
47+
"""
48+
49+
walk = 0
50+
directions = [1, -1]
51+
for i in range(int(max_iters)):
52+
walk += choice(directions)
53+
return walk
54+
55+
56+
# Problems 3 and 4: Write a 'ContentFilter' class.
57+
class ContentFilter(object):
58+
"""Class for reading in file
59+
60+
Attributes:
61+
filename (str): The name of the file
62+
contents (str): the contents of the file
63+
64+
"""
65+
66+
# Problem 3
67+
def __init__(self, filename):
68+
"""Read from the specified file. If the filename is invalid, prompt
69+
the user until a valid filename is given.
70+
"""
71+
72+
# Problem 4 ---------------------------------------------------------------
73+
def check_mode(self, mode):
74+
"""Raise a ValueError if the mode is invalid."""
75+
76+
def uniform(self, outfile, mode="w", case="upper"):
77+
"""Write the data to the outfile with uniform case. Include an additional
78+
keyword argument case that defaults to "upper". If case="upper", write
79+
the data in upper case. If case="lower", write the data in lower case.
80+
If case is not one of these two values, raise a ValueError."""
81+
82+
def reverse(self, outfile, mode="w", unit="word"):
83+
"""Write the data to the outfile in reverse order. Include an additional
84+
keyword argument unit that defaults to "line". If unit="word", reverse
85+
the ordering of the words in each line, but write the lines in the same
86+
order as the original file. If units="line", reverse the ordering of the
87+
lines, but do not change the ordering of the words on each individual
88+
line. If unit is not one of these two values, raise a ValueError."""
89+
90+
def transpose(self, outfile, mode="w"):
91+
"""Write a transposed version of the data to the outfile. That is, write
92+
the first word of each line of the data to the first line of the new file,
93+
the second word of each line of the data to the second line of the new
94+
file, and so on. Viewed as a matrix of words, the rows of the input file
95+
then become the columns of the output file, and viceversa. You may assume
96+
that there are an equal number of words on each line of the input file.
97+
"""
98+
99+
def __str__(self):
100+
"""Printing a ContentFilter object yields the following output:
101+
102+
Source file: <filename>
103+
Total characters: <The total number of characters in file>
104+
Alphabetic characters: <The number of letters>
105+
Numerical characters: <The number of digits>
106+
Whitespace characters: <The number of spaces, tabs, and newlines>
107+
Number of lines: <The number of lines>
108+
"""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Hello,
2+
World!

code/Matplotlib1/FARS.npy

3.39 MB
Binary file not shown.
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# matplotlib_intro.py
2+
"""Python Essentials: Intro to Matplotlib.
3+
<Name>
4+
<Class>
5+
<Date>
6+
"""
7+
8+
9+
# Problem 1
10+
def var_of_means(n):
11+
"""Create an (n x n) array of values randomly sampled from the standard
12+
normal distribution. Compute the mean of each row of the array. Return the
13+
variance of these means.
14+
15+
Parameters:
16+
n (int): The number of rows and columns in the matrix.
17+
18+
Returns:
19+
(float) The variance of the means of each row.
20+
"""
21+
raise NotImplementedError("Problem 1 Incomplete")
22+
23+
24+
def prob1():
25+
"""Create an array of the results of var_of_means() with inputs
26+
n = 100, 200, ..., 1000. Plot and show the resulting array.
27+
"""
28+
raise NotImplementedError("Problem 1 Incomplete")
29+
30+
31+
# Problem 2
32+
def prob2():
33+
"""Plot the functions sin(x), cos(x), and arctan(x) on the domain
34+
[-2pi, 2pi]. Make sure the domain is refined enough to produce a figure
35+
with good resolution.
36+
"""
37+
raise NotImplementedError("Problem 2 Incomplete")
38+
39+
40+
# Problem 3
41+
def prob3():
42+
"""Plot the curve f(x) = 1/(x-1) on the domain [-2,6].
43+
1. Split the domain so that the curve looks discontinuous.
44+
2. Plot both curves with a thick, dashed magenta line.
45+
3. Set the range of the x-axis to [-2,6] and the range of the
46+
y-axis to [-6,6].
47+
"""
48+
raise NotImplementedError("Problem 3 Incomplete")
49+
50+
51+
# Problem 4
52+
def prob4():
53+
"""Plot the functions sin(x), sin(2x), 2sin(x), and 2sin(2x) on the
54+
domain [0, 2pi], each in a separate subplot of a single figure.
55+
1. Arrange the plots in a 2 x 2 grid of subplots.
56+
2. Set the limits of each subplot to [0, 2pi]x[-2, 2].
57+
3. Give each subplot an appropriate title.
58+
4. Give the overall figure a title.
59+
5. Use the following line colors and styles.
60+
sin(x): green solid line.
61+
sin(2x): red dashed line.
62+
2sin(x): blue dashed line.
63+
2sin(2x): magenta dotted line.
64+
"""
65+
raise NotImplementedError("Problem 4 Incomplete")
66+
67+
68+
# Problem 5
69+
def prob5():
70+
"""Visualize the data in FARS.npy. Use np.load() to load the data, then
71+
create a single figure with two subplots:
72+
1. A scatter plot of longitudes against latitudes. Because of the
73+
large number of data points, use black pixel markers (use "k,"
74+
as the third argument to plt.plot()). Label both axes.
75+
2. A histogram of the hours of the day, with one bin per hour.
76+
Label and set the limits of the x-axis.
77+
"""
78+
raise NotImplementedError("Problem 5 Incomplete")
79+
80+
81+
# Problem 6
82+
def prob6():
83+
"""Plot the function g(x,y) = sin(x)sin(y)/xy on the domain
84+
[-2pi, 2pi]x[-2pi, 2pi].
85+
1. Create 2 subplots: one with a heat map of g, and one with a contour
86+
map of g. Choose an appropriate number of level curves, or specify
87+
the curves yourself.
88+
2. Set the limits of each subplot to [-2pi, 2pi]x[-2pi, 2pi].
89+
3. Choose a non-default color scheme.
90+
4. Include a color scale bar for each subplot.
91+
"""
92+
raise NotImplementedError("Problem 6 Incomplete")

0 commit comments

Comments
 (0)