I am working on the file "PowerOutagePredictor/Linear/Ridge.ipynb".
The first task is:
Animals-caused Outages
Can you write Python code for it?

# Select input/output data
Y_ani = data['Animals']
X_ani = data[['Day_length_hr','Max_temp_F','Avg_Temp_F','Min_temp_F','Max_humidity_percent','Avg_humidity_percent','Min_humidity_percent','Max_visibility_mi','Avg_visibility_mi','Min_visibility_mi','Max_windspeed_mph','Avg_windspeed_mph','Max_windgust_mph','Precipitation_in','Event_fog','Event_rain','Event_snow','Event_thunderstorm','Event_Hail']]

# Initialize lists
coefs = []
trainerror = []

# Define lambda space
lambdas = np.logspace(-6,6,200)

# Define type of regressor
regr_ridge = linear_model.Ridge()

# loop over lambda (a) values (strength of regularization)
for a in lambdas:
    regr_ridge.set_params(alpha=a,normalize=True,max_iter=1e6)
    regr_ridge.fit(X_ani,Y_ani)
    coefs.append(regr_ridge.coef_)
    trainerror.append(mean_squared_error(Y_ani,regr_ridge.predict(X_ani)))

# Plot
plt.figure(figsize=(10,3))

# figure 1: Lasso Coef. and lambda
plt.subplot(121)
plt.plot(lambdas,coefs)
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('coefs')
plt.title('Ridge coefs vs $\lambda$')

# figure 2: Error and lambda
plt.subplot(122)
plt.plot(lambdas,trainerror,label='train error')
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('error')
plt.legend(loc='lower right')
plt.title('error vs $\lambda$')

plt.show()

# pick the best alpha value
regr_ridge_best_ani = linear_model.Ridge()
regr_ridge_best_ani.set_params(alpha=1e-2,normalize=True,max_iter=1e6)
regr_ridge_best_ani.fit(X_ani,Y_ani)
Y_ani_predict = regr_ridge_best_ani.predict(X_ani)

#make parity plot
plt.figure(figsize=(4,4))
plt.scatter(Y_ani,Y_ani_predict)
plt.plot([0,10],[0,10],lw=4,color='black')
plt.show()

#calculate the test and train error
print("Train error",mean_squared_error(Y_ani,Y_ani_predict))

# Returns the coefficient of determination R^2 of the prediction.
print("R^2",regr_ridge_best_ani.score(X_ani,Y_ani))


I am working on the file "PowerOutagePredictor/Linear/Ridge.ipynb".
The first task is:
Equipment-caused Outages
Can you write Python code for it?

# Select input/output data
Y_eqp = data['Equipment']
X_eqp = data[['Day_length_hr','Max_temp_F','Avg_Temp_F','Min_temp_F','Max_humidity_percent','Avg_humidity_percent','Min_humidity_percent','Max_visibility_mi','Avg_visibility_mi','Min_visibility_mi','Max_windspeed_mph','Avg_windspeed_mph','Max_windgust_mph','Precipitation_in','Event_fog','Event_rain','Event_snow','Event_thunderstorm','Event_Hail']]

# Initialize lists
coefs = []
trainerror = []

# Define lambda space
lambdas = np.logspace(-6,6,200)

# Define type of regressor
regr_ridge = linear_model.Ridge()

# loop over lambda (a) values (strength of regularization)
for a in lambdas:
    regr_ridge.set_params(alpha=a,normalize=True,max_iter=1e6)
    regr_ridge.fit(X_eqp,Y_eqp)
    coefs.append(regr_ridge.coef_)
    trainerror.append(mean_squared_error(Y_eqp,regr_ridge.predict(X_eqp)))

# Plot
plt.figure(figsize=(10,3))

# figure 1: Lasso Coef. and lambda
plt.subplot(121)
plt.plot(lambdas,coefs)
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('coefs')
plt.title('Ridge coefs vs $\lambda$')

# figure 2: Error and lambda
plt.subplot(122)
plt.plot(lambdas,trainerror,label='train error')
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('error')
plt.legend(loc='lower right')
plt.title('error vs $\lambda$')

plt.show()

# pick the best alpha value
regr_ridge_best_eqp = linear_model.Ridge()
regr_ridge_best_eqp.set_params(alpha=1e-3,normalize=True,max_iter=1e6)
regr_ridge_best_eqp.fit(X_eqp,Y_eqp)
Y_eqp_predict = regr_ridge_best_eqp.predict(X_eqp)

#make parity plot
plt.figure(figsize=(4,4))
plt.scatter(Y_eqp,Y_eqp_predict)
plt.plot([0,10],[0,10],lw=4,color='black')
plt.show()

#calculate the test and train error
print("Train error",mean_squared_error(Y_eqp,Y_eqp_predict))

# Returns the coefficient of determination R^2 of the prediction.
print("R^2",regr_ridge_best_eqp.score(X_eqp,Y_eqp))


I am working on the file "PowerOutagePredictor/Linear/Ridge.ipynb".
The first task is:
Total Outages
Can you write Python code for it?

# Select input/output data
Y_tot = data['Total_outages']
X_tot = data[['Day_length_hr','Max_temp_F','Avg_Temp_F','Min_temp_F','Max_humidity_percent','Avg_humidity_percent','Min_humidity_percent','Max_visibility_mi','Avg_visibility_mi','Min_visibility_mi','Max_windspeed_mph','Avg_windspeed_mph','Max_windgust_mph','Precipitation_in','Event_fog','Event_rain','Event_snow','Event_thunderstorm','Event_Hail']]

# Initialize lists
coefs = []
trainerror = []

# Define lambda space
lambdas = np.logspace(-6,6,200)

# Define type of regressor
regr_ridge = linear_model.Ridge()

# loop over lambda (a) values (strength of regularization)
for a in lambdas:
    regr_ridge.set_params(alpha=a,normalize=True,max_iter=1e6)
    regr_ridge.fit(X_tot,Y_tot)
    coefs.append(regr_ridge.coef_)
    trainerror.append(mean_squared_error(Y_tot,regr_ridge.predict(X_tot)))

# Plot
plt.figure(figsize=(10,3))

# figure 1: Lasso Coef. and lambda
plt.subplot(121)
plt.plot(lambdas,coefs)
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('coefs')
plt.title('Ridge coefs vs $\lambda$')

# figure 2: Error and lambda
plt.subplot(122)
plt.plot(lambdas,trainerror,label='train error')
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('error')
plt.legend(loc='lower right')
plt.title('error vs $\lambda$')

plt.show()

# pick the best alpha value
regr_ridge_best_tot = linear_model.Ridge()
regr_ridge_best_tot.set_params(alpha=1e-4,normalize=True,max_iter=1e6)
regr_ridge_best_tot.fit(X_tot,Y_tot)
Y_tot_predict = regr_ridge_best_tot.predict(X_tot)

#make parity plot
plt.figure(figsize=(4,4))
plt.scatter(Y_tot,Y_tot_predict)
plt.plot([0,10],[0,10],lw=4,color='black')
plt.show()

#calculate the test and train error
print("Train error",mean_squared_error(Y_tot,Y_tot_predict))

# Returns the coefficient of determination R^2 of the prediction.
print("R^2",regr_ridge_best_tot.score(X_tot,Y_tot))


I am working on the file "PowerOutagePredictor/Linear/Ridge.ipynb".
The first task is:
Trees-caused Outages
Can you write Python code for it?

# Select input/output data
Y_tree = data['Trees']
#X_tree = data[['Max_temp_F','Max_humidity_percent','Min_visibility_mi','Max_windspeed_mph','Precipitation_in','Event_Hail']]
X_tree = data[['Day_length_hr','Max_temp_F','Avg_Temp_F','Min_temp_F','Max_humidity_percent','Avg_humidity_percent','Min_humidity_percent','Max_visibility_mi','Avg_visibility_mi','Min_visibility_mi','Max_windspeed_mph','Avg_windspeed_mph','Max_windgust_mph','Precipitation_in','Event_fog','Event_rain','Event_snow','Event_thunderstorm','Event_Hail']]

# Initialize lists
coefs = []
trainerror = []

# Define lambda space
lambdas = np.logspace(-6,6,200)

# Define type of regressor
regr_ridge = linear_model.Ridge()

# loop over lambda (a) values (strength of regularization)
for a in lambdas:
    regr_ridge.set_params(alpha=a,normalize=True,max_iter=1e6)
    regr_ridge.fit(X_tree,Y_tree)
    coefs.append(regr_ridge.coef_)
    trainerror.append(mean_squared_error(Y_tree,regr_ridge.predict(X_tree)))

# Plot
plt.figure(figsize=(10,3))

# figure 1: Lasso Coef. and lambda
plt.subplot(121)
plt.plot(lambdas,coefs)
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('coefs')
plt.title('Ridge coefs vs $\lambda$')

# figure 2: Error and lambda
plt.subplot(122)
plt.plot(lambdas,trainerror,label='train error')
plt.xscale('log')
plt.xlabel('$\lambda$')
plt.ylabel('error')
plt.legend(loc='lower right')
plt.title('error vs $\lambda$')

plt.show()

# pick the best alpha value
regr_ridge_best_tree = linear_model.Ridge()
regr_ridge_best_tree.set_params(alpha=1e-4,normalize=True,max_iter=1e6)
regr_ridge_best_tree.fit(X_tree,Y_tree)
Y_tree_predict = regr_ridge_best_tree.predict(X_tree)

#make parity plot
plt.figure(figsize=(4,4))
plt.scatter(Y_tree,Y_tree_predict)
plt.plot([0,10],[0,10],lw=4,color='black')
plt.show()

#calculate the test and train error
print("Train error",mean_squared_error(Y_tree,Y_tree_predict))

# Returns the coefficient of determination R^2 of the prediction.
print("R^2",regr_ridge_best_tree.score(X_tree,Y_tree))


I am working on the file "PowerOutagePredictor/SVM/Grid Search Procedure.ipynb".
The first task is:
Finally we do the grid search. The following code will perform a grid search. Parameters such as the exploration values of C and gamma, etc can be changed. But the following was what was used in this project.
Can you write Python code for it?

# Define variables
xTrain = None
yTrain = None
xTest = None
yTest = None

# Define objects and parameters. Here, we have defined the test data set to be 20%, balanced weight for SVM.
# And we are exploring C and gamma from 10e-5 to 10e5
nSplits = 10
scaler = StandardScaler()
shuffleSplitter = ShuffleSplit(n_splits=nSplits, test_size=0.2)
classifier = SVC(cache_size=1000.0, class_weight="balanced", probability=True)
exploreC = np.logspace(-5, 5, 1)
exploreGamma = np.logspace(-5, 5, 1)
outputFilename = "filename.csv"
df = pd.DataFrame()

# For each values of C and gamma we want to explore, we will shuffle split 10 times, store them in an empty array,
# and then average them.
for cValue in exploreC:
    for gammaValue in exploreGamma:
        classifier.set_params(C = cValue, gamma = gammaValue)
        allCorrectness = []
        allFalseNegativesBad = []
        allFalseNegativesExtreme = []
        allFalsePositives = []
        allBadDays = []
        allExtremeDays = []

        # Separate testing and training data.
        for train, test in shuffleSplitter.split(data):
            overallCorrectness = 0
            falseNegativesBad = 0
            falseNegativesExtreme = 0
            falsePositives = 0
            badDays = 0
            extremeDays = 0
            xTrain = scaler.fit_transform(data.iloc[train, 1:-1])
            yTrain = data.iloc[train, -1]
            xTest = scaler.transform(data.iloc[test, 1:-1])
            yTest = data.iloc[test, -1]
            classifier.fit(xTrain, yTrain)
            yPredict = classifier.predict(xTest)
            yTest = yTest.tolist()
            yPredict = yPredict.tolist()

            #Compare testing data and predicted data from model. Tally up the results.
            for i in range(len(yTest)):
                if yTest[i] == 1:
                    badDays += 1
                elif yTest[i] == 2:
                    extremeDays += 1
                if yTest[i] == yPredict[i]:
                    overallCorrectness += 1
            ...


I am working on the file "PowerOutagePredictor/SVM/Grid Search Procedure.ipynb".
The first task is:
Now we need to import the appropriate dataset for SVM.
Can you write Python code for it?

data = pd.read_csv("../../Data/WeatherOutages_SVM.csv")

data.head()


I am working on the file "PowerOutagePredictor/Tree/.ipynb_checkpoints/TreeClassifier_Example-checkpoint.ipynb".
The first task is:
input weather data following the package instruction
Can you write Python code for it?

df = pd.DataFrame()
weather = df.append({"Day_length_hr": 11,
                "Avg_Temp_F": 38,
                "Avg_humidity_percent": 85,
                "Max_windspeed_mph": 16,
                "Avg_windspeed_mph": 7,
                "Max_windgust_mph": 20,
                "Precipitation_in": 0.33},
                ignore_index=True)
weather


I am working on the file "PowerOutagePredictor/Tree/TreeClassifier_Example.ipynb".
The first task is:
input weather data following the package instruction
Can you write Python code for it?


I am working on the file "PowerOutagePredictor/Tree/TreeClassifier_Example.ipynb".
The first task is:
predict the class of outage status (0 for normal, 1 for bad, 2 for extreme) for a given day using random forest
Can you write Python code for it?


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
1. Create a light curve
There are two ways to make Lightcurve objects. We'll show one way here. Check out "Lightcurve/Lightcurve\ tutorial.ipynb" for more examples.
Generate an array of relative timestamps that's 8 seconds long, with dt = 0.03125 s, and make two signals in units of counts. The signal is a sine wave with amplitude = 300 cts/s, frequency = 2 Hz, phase offset = 0 radians, and mean = 1000 cts/s. We then add Poisson noise to the light curve.
Can you write Python code for it?

dt = 0.03125  # seconds
exposure = 8.  # seconds
times = np.arange(0, exposure, dt)  # seconds

signal = 300 * np.sin(2.*np.pi*times/0.5) + 1000  # counts/s
noisy = np.random.poisson(signal*dt)  # counts


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
2. And we can logarithmically/geometrically re-bin a power spectrum
In this re-binning, each bin size is 1+f times larger than the previous bin size, where f is user-specified and normally in the range 0.01-0.1. The default value is f=0.01.
Can you write Python code for it?

# Both of the following ways are allowed syntax:
# log_rb_ps, log_rb_freq, binning = Powerspectrum.rebin_log(avg_ps, f=0.02)
log_rb_ps = ps.rebin_log(f=0.02)


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
2. Pass the light curve to the AveragedPowerspectrum class with a specified segment_size.
If the exposure (length) of the light curve cannot be divided by segment_size with a remainder of zero, the last incomplete segment is thrown out, to avoid signal artefacts. Here we're using 8 second segments.
Can you write Python code for it?

avg_ps = AveragedPowerspectrum.from_lightcurve(long_lc, 8., norm="leahy")


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
Here we plot it to see what it looks like.
Can you write Python code for it?

fig, ax = plt.subplots(1,1,figsize=(10,6))
ax.plot(lc.time, lc.counts, lw=2, color='blue')
ax.set_xlabel("Time (s)", fontproperties=font_prop)
ax.set_ylabel("Counts (cts)", fontproperties=font_prop)
ax.tick_params(axis='x', labelsize=16)
ax.tick_params(axis='y', labelsize=16)
ax.tick_params(which='major', width=1.5, length=7)
ax.tick_params(which='minor', width=1.5, length=4)
plt.show()


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
Like rebin, rebin_log returns a Powerspectrum or AveragedPowerspectrum object (depending on the input object):
Can you write Python code for it?


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
Now we'll show examples of all the things you can do with a Powerspectrum or AveragedPowerspectrum object using built-in stingray methods.
Normalizating the power spectrum
The three kinds of normalization are:
* leahy: Leahy normalization. Makes the Poisson noise level $= 2$. See Leahy et al. 1983, ApJ, 266, 160L.
* frac: Fractional rms-squared normalization, also known as rms normalization. Makes the Poisson noise level $= 2 / meanrate$. See Belloni & Hasinger 1990, A&A, 227, L33, and Miyamoto et al. 1992, ApJ, 391, L21.
* abs: Absolute rms-squared normalization, also known as absolute normalization. Makes the Poisson noise level $= 2 \times meanrate$. See insert citation.
* none: No normalization applied. This is the default.
Can you write Python code for it?

avg_ps_leahy = AveragedPowerspectrum.from_lightcurve(long_lc, 8, norm='leahy')
avg_ps_frac = AveragedPowerspectrum.from_lightcurve(long_lc, 8., norm='frac')
avg_ps_abs = AveragedPowerspectrum.from_lightcurve(long_lc, 8., norm='abs')

fig, [ax1, ax2, ax3] = plt.subplots(3,1,figsize=(6,12))
ax1.plot(avg_ps_leahy.freq, avg_ps_leahy.power, lw=2, color='black')
ax1.set_xlabel("Frequency (Hz)", fontproperties=font_prop)
ax1.set_ylabel("Power (Leahy)", fontproperties=font_prop)
ax1.set_yscale('log')
ax1.tick_params(axis='x', labelsize=14)
ax1.tick_params(axis='y', labelsize=14)
ax1.tick_params(which='major', width=1.5, length=7)
ax1.tick_params(which='minor', width=1.5, length=4)
ax1.set_title("Leahy norm.", fontproperties=font_prop)

ax2.plot(avg_ps_frac.freq, avg_ps_frac.power, lw=2, color='black')
ax2.set_xlabel("Frequency (Hz)", fontproperties=font_prop)
ax2.set_ylabel("Power (rms)", fontproperties=font_prop)
ax2.tick_params(axis='x', labelsize=14)
ax2.tick_params(axis='y', labelsize=14)
ax2.set_yscale('log')
ax2.tick_params(which='major', width=1.5, length=7)
ax2.tick_params(which='minor', width=1.5, length=4)
ax2.set_title("Fractional rms-squared norm.", fontproperties=font_prop)

ax3.plot(avg_ps_abs.freq, avg_ps_abs.power, lw=2, color='black')
ax3.set_xlabel("Frequency (Hz)", fontproperties=font_prop)
ax3.set_ylabel("Power (abs)", fontproperties=font_prop)
ax3.tick_params(axis='x', labelsize=14)
ax3.tick_params(axis='y', labelsize=14)
ax3.set_yscale('log')
ax3.tick_params(which='major', width=1.5, length=7)
ax3.tick_params(which='minor', width=1.5, length=4)
ax3.set_title("Absolute rms-squared norm.", fontproperties=font_prop)

for axis in ['top', 'bottom', 'left', 'right']:
    ax1.spines[axis].set_linewidth(1.5)
    ax2.spines[axis].set_linewidth(1.5)
    ax3.spines[axis].set_linewidth(1.5)
plt.tight_layout()
plt.show()


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
Power spectra of normal-distributed light curves
Starting with Stingray 0.3, we can also get Leahy-normalized power spectra of normally-distributed light curves.
Let us calculate such a light curve by subtracting the noise level and normalizing
Can you write Python code for it?

long_norm = (long_noisy - long_noisy.mean()) / long_noisy.max()
err = np.sqrt(long_noisy.mean()) / long_noisy.max()

long_lc_gauss = Lightcurve(long_times, long_norm, err=np.zeros_like(long_norm) + err, dt=long_dt, skip_checks=True, err_dist='gauss')

fig, ax = plt.subplots(1,1,figsize=(10, 6))
ax.plot(long_lc.time, long_lc.counts, lw=2, color='blue', label='Original light curve')
ax.plot(long_lc_gauss.time, long_lc_gauss.counts, lw=2, color='red', label='Normalized light curve')
ax.set_xlim(0,20)
ax.set_xlabel("Time (s)", fontproperties=font_prop)
ax.set_ylabel("Counts (cts)", fontproperties=font_prop)
ax.tick_params(axis='x', labelsize=16)
ax.tick_params(axis='y', labelsize=16)
ax.tick_params(which='major', width=1.5, length=7)
ax.tick_params(which='minor', width=1.5, length=4)
plt.legend()
plt.show()

avg_ps_gauss_leahy = AveragedPowerspectrum.from_lightcurve(long_lc_gauss, 8, norm='leahy')
avg_ps_gauss_frac = AveragedPowerspectrum.from_lightcurve(long_lc_gauss, 8., norm='frac')
avg_ps_gauss_abs = AveragedPowerspectrum.from_lightcurve(long_lc_gauss, 8., norm='abs')

fig, [ax1, ax2, ax3] = plt.subplots(3,1,figsize=(6,12))
ax1.plot(avg_ps_leahy.freq, avg_ps_leahy.power, lw=2, color='black')
ax1.plot(avg_ps_gauss_leahy.freq, avg_ps_gauss_leahy.power, lw=2, color='red', zorder=10)
ax1.set_xlabel("Frequency (Hz)", fontproperties=font_prop)
ax1.set_ylabel("Power (Leahy)", fontproperties=font_prop)
ax1.set_yscale('log')
ax1.tick_params(axis='x', labelsize=14)
ax1.tick_params(axis='y', labelsize=14)
ax1.tick_params(which='major', width=1.5, length=7)
ax1.tick_params(which='minor', width=1.5, length=4)
ax1.set_title("Leahy norm.", fontproperties=font_prop)

ax2.plot(avg_ps_frac.freq, avg_ps_frac.power, lw=2, color='black')
ax2.plot(avg_ps_gauss_frac.freq, avg_ps_gauss_frac.power, lw=2, color='red')
ax2.set_xlabel("Frequency (Hz)", fontproperties=font_prop)
ax2.set_ylabel("Power (rms)", fontproperties=font_prop)
ax2.tick_params(axis='x', labelsize=14)
ax2.tick_params(axis='y',...


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
Re-binning a power spectrum in frequency
Typically, rebinning is done on an averaged, normalized power spectrum.
1. We can linearly re-bin a power spectrum
(although this is not done much in practice)
Can you write Python code for it?

print("DF before:", avg_ps.df)
# Both of the following ways are allowed syntax:
# lin_rb_ps = Powerspectrum.rebin(avg_ps, 0.25, method='mean')
lin_rb_ps = avg_ps.rebin(0.25, method='mean')
print("DF after:", lin_rb_ps.df)


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
We can plot the power as a function of Fourier frequency. Notice how there's a spike at our signal frequency of 2 Hz!
Can you write Python code for it?

fig, ax1 = plt.subplots(1,1,figsize=(9,6), sharex=True)
ax1.plot(ps.freq, ps.power, lw=2, color='blue')
ax1.set_ylabel("Frequency (Hz)", fontproperties=font_prop)
ax1.set_ylabel("Power (raw)", fontproperties=font_prop)
ax1.set_yscale('log')
ax1.tick_params(axis='x', labelsize=16)
ax1.tick_params(axis='y', labelsize=16)
ax1.tick_params(which='major', width=1.5, length=7)
ax1.tick_params(which='minor', width=1.5, length=4)
for axis in ['top', 'bottom', 'left', 'right']:
    ax1.spines[axis].set_linewidth(1.5)
plt.show()


I am working on the file "Powerspectrum/Powerspectrum_tutorial.ipynb".
The first task is:
You'll notice that the power spectrum is a bit noisy. This is because we're only using one segment of data. Let's try averaging together power spectra from multiple segments of data.
Averaged power spectrum example
You could use a long Lightcurve and have AveragedPowerspectrum chop it into specified segments, or give a list of Lightcurves where each segment of Lightcurve is the same length. We'll show the first way here.
1. Create a long light curve.
Generate an array of relative timestamps that's 1600 seconds long, and a signal in count units, with the same properties as the previous example. We then add Poisson noise and turn it into a Lightcurve object.
Can you write Python code for it?

long_dt = 0.03125  # seconds
long_exposure = 1600.  # seconds
long_times = np.arange(0, long_exposure, long_dt)  # seconds

# In count rate units here
long_signal = 300 * np.sin(2.*np.pi*long_times/0.5) + 1000

# Multiply by dt to get count units, then add Poisson noise
long_noisy = np.random.poisson(long_signal*dt)

long_lc = Lightcurve(long_times, long_noisy, dt=long_dt, skip_checks=True)

fig, ax = plt.subplots(1,1,figsize=(10,6))
ax.plot(long_lc.time, long_lc.counts, lw=2, color='blue')
ax.set_xlim(0,20)
ax.set_xlabel("Time (s)", fontproperties=font_prop)
ax.set_ylabel("Counts (cts)", fontproperties=font_prop)
ax.tick_params(axis='x', labelsize=16)
ax.tick_params(axis='y', labelsize=16)
ax.tick_params(which='major', width=1.5, length=7)
ax.tick_params(which='minor', width=1.5, length=4)
plt.show()


I am working on the file "Poynting-Robertson_Cartesian-Long.ipynb".
The first task is:
Let's see how the oscillator's energy changes with time according to the different orders and integration schemes. The energy is
$$E = \frac{1}{2} m \dot{\mathbf q}^2 -(1-\beta)\frac{GM_{\odot}m}{r}.$$
To quantify the errors incurred by discretization and subsequent numerical integration, we define the fractional or relative energy difference as $\delta E / E = ( E_X - E_6 )/ E_6$ where $E_X$ is the energy as measured by integrator $X$ with $X \in { {\rm Slim2,~Slim4,~RK2,~RK4} }$ relative to the 6th order slimplectic result $E_6$.
Can you write Python code for it?

# Energy function
def Energy(q, v):
    return 0.5*m*(v[0]**2+v[1]**2) - (1.-beta)*G*M_Sun*m/np.sqrt(q[0]**2+q[1]**2)

# Energies from different integrators
E_slim2 = Energy(q_slim2, pi_slim2/m)
E_slim4 = Energy(q_slim4, pi_slim4/m)
E_slim6 = Energy(q_slim6, pi_slim6/m)

E_rk2 = Energy(q_rk2, v_rk2)
E_rk4 = Energy(q_rk4, v_rk4)

fig2 = plt.figure(figsize=(12,5), dpi=500)
ax2 = fig2.add_subplot(1,1,1)

ax2.set_xlim(0.01, 6000)
ax2.loglog(t, np.abs(E_slim2/E_slim6-1.), 'r-', linewidth=2.0, rasterized=True)
ax2.loglog(t, np.abs(E_slim4/E_slim6-1.), '-', color='orange', linewidth=2.0, rasterized=True)
ax2.loglog(t, np.abs(E_rk2/E_slim6-1.), 'g--', linewidth=2.0, rasterized=True)
ax2.loglog(t, np.abs(E_rk4/E_slim6-1.), 'b--', linewidth=2.0, rasterized=True)

ax2.set_xlabel('Time, $t$ [yr]', fontsize=18)
ax2.set_ylabel('Fractional Energy Error, $\delta E/E_6$', fontsize=18)

ax2.text(15, 1.8e-4, r'$2^{nd}$ order Slimplectic', fontsize=15, color='black')
ax2.text(15, 0.5e-8, r'$4^{th}$ order Slimplectic', fontsize=15, color='black')
ax2.text(30, 1e-5, r'$4^{th}$ order RK', fontsize=15, color='blue', rotation = 10)
ax2.text(30, 1.5e-1, r'$2^{nd}$ order RK', fontsize=15, color='g', rotation=10)
ax2.text(0.015, 1e-1, r'$\Delta t = 0.01$ yr', fontsize=18, color='black')

ax2.tick_params(axis='both', which='major', labelsize=16)

ax2.set_yticks([1e-12, 1e-9, 1e-6, 1e-3, 1e0]);

#fig2.savefig(plot_path + "PRDrag_E_errorLong.pdf", transparent=True,bbox_inches='tight')


I am working on the file "Poynting-Robertson_Cartesian-Long.ipynb".
The first task is:
Runge-Kutta integration
Generate the 2nd and 4th order Runge-Kutta solutions to compare below with output from the slimplectic integrators.
Can you write Python code for it?

# Instantiate the 2nd and 4th order Runge-Kutta classes
rk2 = slimplectic.RungeKutta2()
rk4 = slimplectic.RungeKutta4()

# Define the derivative operator
def dydt(time, y):
    deriv = np.zeros(4)
    [q_x, q_y, v_x, v_y] = y
    r = (q_x*q_x + q_y*q_y)**0.5
    deriv[0] = v_x
    deriv[1] = v_y
    deriv[2] = -(1. - beta)*G*M_Sun*q_x/(r*r*r)
    deriv[2] -=(beta*G*M_Sun/(c*r*r))*(v_x + q_x*(q_x*v_x + q_y*v_y)/(r*r))
    deriv[3] = -(1. - beta)*G*M_Sun*q_y/(r*r*r)
    deriv[3] -=(beta*G*M_Sun/(c*r*r))*(v_y + q_y*(q_x*v_x + q_y*v_y)/(r*r))

    return deriv

# Integrate
q_rk2, v_rk2 = rk2.integrate(q0[:2], v0[:2], t, dydt)
q_rk4, v_rk4 = rk4.integrate(q0[:2], v0[:2], t, dydt)

# Please note that q and pi are outputs of the slimplectic integration,
# while q and v are output from the Runge-Kutta integrators.


I am working on the file "Poynting-Robertson_Cartesian-Long.ipynb".
The first task is:
Slimplectic integration
Can you write Python code for it?

# Create an instance of the GalerkinGaussLobatto class and call it `pr` for Poynting-Robinson
# We will focus on motion in the x-y plane since the direction of the orbital angular momentum
# can be shown to be preserved analytically. All integrators considered here preserve this
# except for the 2nd order implicit slimplectic integrator. We shall not consider this further here.
pr = slimplectic.GalerkinGaussLobatto('t', ['x', 'y'], ['vx', 'vy'])

# Define the conservative $L$ and nonconservative $K$ parts of the total Lagrangian $\Lambda$
# We take the dust particle to have unit mass.
L = 0.5*np.dot(pr.v, pr.v) + (1.0 - beta)*G*M_Sun/np.dot(pr.q, pr.q)**0.5
K = np.dot(pr.vp, pr.qm) + np.dot(pr.vp, pr.qp)*np.dot(pr.qp, pr.qm)/np.dot(pr.qp, pr.qp)
K *= -beta*G*M_Sun/c/np.dot(pr.qp, pr.qp)

# Discretize total Lagrangian using a 2nd order (r=0) implicit scheme
pr.discretize(L, K, 0, method='implicit')

# Specify time samples at which the numerical solution is to be given and provide initial data.

# We take the initial orbital parameters to be given by:
# a=1, e=0, i=0, omega=0, Omega=0, M=0
q0, v0 = orbit.Calc_Cartesian(1.0, 0.2, 0.0, 0.0, 0.0, 0.0, (1.0-beta)*G*M_Sun)
pi0 = v0  # Dust taken to have unit mass

# Time samples (in years)
t_end = 6000
dt = 0.01
t = np.arange(0, t_end+dt, dt)

# Now integrate the 2nd order slimplectic integrator
q_slim2, pi_slim2 = pr.integrate(q0[:2], pi0[:2], t)

# For a 4th order (r=1) implicit scheme we run
pr.discretize(L, K, 1, method='implicit')

# ...and then integrate to get the corresponding numerical solution
q_slim4, pi_slim4 = pr.integrate(q0[:2], pi0[:2], t)


I am working on the file "Poynting-Robertson_Cartesian-Long.ipynb".
The first task is:
We can also look at how the orbital eccentricity changes depending on the integration scheme and order.
Can you write Python code for it?

# Compute the eccentricties
def ecc(q, v, t):
    Q = np.vstack([q, np.zeros(t.size)])
    V = np.vstack([v, np.zeros(t.size)])
    qT, vT = np.transpose(Q), np.transpose(V)
    return np.array( [orbit.Calc_e(qT[ii], vT[ii], (1.-beta)*G*M_Sun) for ii in range(t.size)])

e_slim2 = ecc(q_slim2, pi_slim2/m, t)
e_slim4 = ecc(q_slim4, pi_slim4/m, t)
e_slim6 = ecc(q_slim6, pi_slim6/m, t)
e_rk2 = ecc(q_rk2, v_rk2, t)
e_rk4 = ecc(q_rk4, v_rk4, t)

fig3 = plt.figure(figsize=(12,5), dpi=500)
ax3 = fig3.add_subplot(1,1,1)

ax3.set_xlim(0.01, 6000)
ax3.loglog(t, np.abs(e_slim2/e_slim6-1.), 'r-', linewidth=2.0, rasterized=True)
ax3.loglog(t, np.abs(e_slim4/e_slim6-1.), '-', color='orange', linewidth=2.0, rasterized=True)
ax3.loglog(t, np.abs(e_rk2/e_slim6-1.), 'g--', linewidth=2.0, rasterized=True)
ax3.loglog(t, np.abs(e_rk4/e_slim6-1.), 'b--', linewidth=2.0, rasterized=True)

ax3.set_xlabel('Time, $t$ [yr]', fontsize=18)
ax3.set_ylabel('Frac\'l Eccentricity Error, $\delta e/e_6$', fontsize=18)

ax3.text(20, 1.8e-3, r'$2^{nd}$ order Slimplectic', fontsize=15, color='black')
ax3.text(20, 0.5e-7, r'$4^{th}$ order Slimplectic', fontsize=15, color='black')
ax3.text(40, 1e-4, r'$4^{th}$ order RK', fontsize=15, color='blue', rotation = 10)
ax3.text(40, 1e0, r'$2^{nd}$ order RK', fontsize=15, color='g', rotation=10)

ax3.tick_params(axis='both', which='major', labelsize=16)
ax3.set_yticks([1e-12, 1e-9, 1e-6, 1e-3, 1e0])
ax3.text(0.015, 1e0, r'$\Delta t = 0.01$ yr', fontsize=18, color='black');

#fig3.savefig(plot_path + "PRDrag_Ecc_errorLong.pdf", transparent=True,bbox_inches='tight')


I am working on the file "Practical Code to Calculating Customer Lifetime Value (CLV).ipynb".
The first task is:
As with any analysis, the first thing we’ll do is look at some basic summary statistics.
Can you write Python code for it?

data = {'Transactions': [4181],
        'Customers': [1000],
        'MinTransactionDate': ['2010-01-04'],
        'MaxTransactionDate': ['2015-12-31'],
        'Amount': [33729.91]}
df = pd.DataFrame(data, index = [''])
df

TransactionsPerCustomer = round(Transactions / Customers, 2)
TransactionsPerCustomer

AmountPerTransaction = round(Amount / Transactions, 2)
AmountPerTransaction

AmountPerCustomer = round(Amount / Customers, 2)
AmountPerCustomer


I am working on the file "Practical Code to Calculating Customer Lifetime Value (CLV).ipynb".
The first task is:
Note that the data consists of 1000 customers who made transactions between 2010 and 2015. Furthermore, each customer made about 4 transactions for 8 bucks a piece, totaling close to $34. This amount can be considered a lower bound on CLV since it’s the total amount spent by each customer, but we still expect existing customers to make future purchases.
Can you write Python code for it?

data = {'TransactionsPerCustomer': [4.0],
        'AmountPerTransaction': [8.07],
        'AmountPerCustomer': [33.73]}
df = pd.DataFrame(data, index = [''])
df

more_summary = [TransactionsPerCustomer, AmountPerTransaction, AmountPerCustomer]
more_summary


I am working on the file "Practical Code to Calculating Customer Lifetime Value (CLV).ipynb".
The first task is:
We need to consider outlier transactions and should remove the transactions from the data entirely. Here we inspect the largest transactions.
Can you write Python code for it?

data.loc[data['Amount'] >= 29.99]

import seaborn as sns
sns.set(color_codes=True)


I am working on the file "Practical Pandas 01 - Reading the Data.ipynb".
The first task is:
Each day has data recorded in two formats, CSVs and KMLs.
For now I've just uploaded the CSVs to the data/ directory.
We'll start with the those, and come back to the KMLs later.
Can you write Python code for it?


I am working on the file "Practical Pandas 01 - Reading the Data.ipynb".
The first task is:
Great! The data itself is clean enough that we didn't have to do too much munging.
Let's persist the merged DataFrame. Writing it out to a csv would be fine, but I like to use
pandas' HDF5 integration (via pytables) for personal projects.
Can you write Python code for it?

df.to_hdf('data/cycle_store.h5', key='merged',
          format='table')


I am working on the file "Practical Pandas 01 - Reading the Data.ipynb".
The first task is:
I see a potential problem: We'll potentailly want to concatenate each csv together
into a single DataFrame. However we'll want to retain some idea of which specific
ride an observation came from. So let's create a ride_id variable, which will
just be an integar ranging from $0 \ldots N$, where $N$ is the number of rides.
Make a simple helper function to do this, and apply it to each csv.
Can you write Python code for it?

def read_ride(path_, i):
    """
    read in csv at path, and assign the `ride_id` variable to i.
    """
    date_cols = ["Time", "Ride Time", "Stopped Time", "Pace", "Average Pace"]

    df = pd.read_csv(path_, parse_dates=date_cols)
    df['ride_id'] = i
    return df

dfs = (read_ride(os.path.join('data', csv), i)
       for (i, csv) in enumerate(csvs))


I am working on the file "Practical Pandas 01 - Reading the Data.ipynb".
The first task is:
Now concatenate together. The original indicies are meaningless, so we'll ignore them in the concat.
Can you write Python code for it?

df = pd.concat(dfs, ignore_index=True)
df.head()


I am working on the file "Practical Pandas 01 - Reading the Data.ipynb".
The first task is:
One minor issue is that some of the dates are parsed as datetimes when they're really just times.
We'll take care of that later. Pandas store everything as datetime64. For now we'll keep them as
datetimes, and remember that they're really just times.
Now let's do the same thing, but for all the files.
Use a generator expression to filter down to just csv's that match the simple
condition of having the correct naming style.
I try to use lazy generators instead of lists wherever possible.
In this case the list is so small that it really doesn't matter, but it's
a good habit.
Can you write Python code for it?

import os
csvs = (f for f in os.listdir('data') if f.startswith('Cyclemeter')
        and f.endswith('.csv'))


I am working on the file "Practical Pandas 02 - EDA.ipynb".
The first task is:
Fun. The horizontal distance is the length of time it took me to make the ride.
I like this chart because it also conveys the start time of each ride.
The plot shows that the morning ride typically took longer, but we can verify that.
Can you write Python code for it?

is_morning = df.time.dt.time < datetime.time(12, 0, 0)

ride_time = df.groupby(['ride_id', is_morning])['ride_time_secs'].agg('max')
mean_time = ride_time.groupby(level=1).mean().rename(
    index={True: 'morning', False: 'evening'})
mean_time / 60


I am working on the file "Practical Pandas 02 - EDA.ipynb".
The first task is:
Let's break them into two parts, morning and afternoon.
Can you write Python code for it?

morning = sub[sub.time < datetime.time(12)]
evening = sub[sub.time >= datetime.time(12)]

fig, ax = plt.subplots(figsize=(12, 5))
ax.scatter(morning.time.values, morning.distance_miles, marker='.',
           color='k', linewidths=0.01, alpha=.5)
ax.set_ylim(0, 8)

fig, ax = plt.subplots(figsize=(12, 5))
ax.scatter(evening.time.values, evening.distance_miles, marker='.',
           color='k', linewidths=0.01, alpha=.5)
ax.set_ylim(0, 8)


I am working on the file "Practical Pandas 02 - EDA.ipynb".
The first task is:
So the morning ride is typically shorter! But I think I know what's going on. We were misleading with our plot earlier since the range of the horizontal axis weren't identical. Always check the axis!
Can you write Python code for it?

fig, ax = plt.subplots(figsize=(12, 5))
ax.scatter(morning.time.values, morning.distance_miles, marker='.',
           color='k', linewidths=0.01, alpha=.5)
ax.set_xlim(datetime.time(6, 40), datetime.time(10, 40))
ax.set_ylim(0, 8)

fig, ax = plt.subplots(figsize=(12, 5))
ax.scatter(evening.time.values, evening.distance_miles, marker='.',
           color='k', linewidths=0.01, alpha=.5)
ax.set_xlim(datetime.time(15, 30), datetime.time(19, 30))
ax.set_ylim(0, 8)

axes = df.groupby('ride_id').plot(x='distance_miles', y='elevation_feet', color='k', alpha=.5)

df['is_morning'] = df.time.dt.time < datetime.time(12)

sns.tsplot(df, time="distance_miles", unit="ride_id", value="elevation_feet")

df.groupby('ride_id').plot(x='distance_miles', y='elevation_feet')

sns.tsplot(df, time="ride_time_secs", value="distance_miles", condition="is_morning", unit="ride_id")


I am working on the file "Practical Pandas 02 - EDA.ipynb".
The first task is:
The columns should be pretty obvious. The pair (ride_id, Time) form a unique index for the DataFrame.
We may set them to be the MulitIndex later. Pace is just $\frac{time}{distance}$.
Let's drop some of the redundent columns and do a bit of renaming.
Can you write Python code for it?

df = df.drop(['Ride Time', 'Stopped Time', 'Pace', 'Average Pace'], axis=1)

def renamer(name):
    for char in ['(', ')']:
        name = name.replace(char, '')
    name = name.replace(' ', '_')
    name = name.lower()
    return name

df = df.rename(columns=renamer)


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
A bit of Exploring
We've done a lot of data wrangling with a notable lack of pretty pictures to look at. Let's fix that.
Can you write Python code for it?


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
For some other (less) pretty pictures, let's visualize some of the weather data we collected.
Can you write Python code for it?

sns.set(style="white")

cols = ['temperature', 'apparentTemperature', 'humidity', 'dewPoint', 'pressure']
# 'pressure', 'windBearing', 'windSpeed']].reset_index(drop=True))

g = sns.PairGrid(weather.reset_index()[cols])

g.map_diag(plt.hist)
g.map_lower(sns.kdeplot, cmap="Blues_d")
g.map_upper(plt.scatter)


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
Here's the plan. For each ride, we'll get the current conditions at the time, latitude, and longitude of departure.
We'll use those values for the entirety of that ride.
I'm a bit concerned about the variance of some quantities from the weather data (like the windspeed and bearing). This would be something to look into for a serious analysis. If the quantities are highly variable you would want to take a rolling average over more datapoints. forecast.io limits you to 1,000 API calls per day though (at the free tier), so we'll just stick with one request per ride.
Can you write Python code for it?

def get_weather(df, ride_id, key):
    """
    Get the current weather conditions for for a ride at the time of departure.
    """
    url = "https://api.forecast.io/forecast/{key}/{Latitude},{Longitude},{Time}"
    vals = df.query("ride_id == @ride_id").iloc[0][['latitude',
               'longitude', 'time']].rename(lambda x: x.title()).to_dict()
    vals['key'] = key
    vals['Time'] = str(vals['Time']).replace(' ', 'T')
    r = requests.get(url.format(**vals))
    resp = r.json()['currently']
    return resp


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
I map the speeds to colors with one of matplotlib's colormaps. It expects values in [0, 1], so
we normalize the speeds by dividing by the maximum.
hist doesn't take a cmap argument, and I couldn't get color to work, so we'll just plot it like before,
and then modify the color of the patches after the fact.
Can you write Python code for it?

fig = plt.figure()
ax = plt.subplot(polar=True)
ax.set_theta_zero_location('N')
ax.set_theta_direction('clockwise')

bins = np.arange(0, 360, 30)
ax.hist(np.radians(weather.windBearing.dropna()), bins=np.radians(bins))

for p, color in zip(ax.patches, colors):
    p.set_facecolor(color)

ax.set_title("Direction of Wind Origin")


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
Let's fixup the dtype on the time column. We need to convert from the seconds to a datetime.
Then handle the timezone like before. This is returned in 'UTC', so we'll bring it back to
my local time with .tz_convert.
Can you write Python code for it?

weather['time'] = pd.DatetimeIndex(pd.to_datetime(weather.time, unit='s'), tz='UTC').\
                     tz_convert('US/Central')


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
Let's test it out:
Can you write Python code for it?


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
Now do that for each ride_id, and store the result in a DataFrame
Can you write Python code for it?

conditions = [get_weather(df, ride_id, key) for ride_id
              in df.ride_id.unique()]
weather = pd.DataFrame(conditions)
weather.head()


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
Now we can merge the two DataFrames weather and df. In this case it's quite simple since the share a single column, time. Pandas behaves exactly as you'd expect, merging on the provided column.
We take the outer join since we only have weather information for the first obervation of each ride.
We'll fill those values forward for the entirety of the ride.
I don't just call with_weather.fillna() since the non-weather columns have NaNs that we may want to treat separately.
Can you write Python code for it?

with_weather = pd.merge(df, weather, on='time', how='outer')
print(with_weather.time.dtype)
with_weather[weather.columns] = with_weather[weather.columns].fillna(method='ffill')
print(with_weather.time.dtype)

with_weather.time.head()

with_weather.time.head()


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
So we'll go with #2, running the time column through the DatetimeIndex constructor, which has a tz (timezone) parameter, and placing that in a 'time' column. I'm in the US/Central timezone.
Can you write Python code for it?

df['time'] = pd.DatetimeIndex(df.time, tz='US/Central')
df.head()


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
There's nothing specific to pandas here, but knowing the basics of calling an API and parsing the response is still useful.
We'll use requests to make the
API call. You'll need to register for you own API key. I keep mine in a JSON file in my Dropbox bin folder.
For this specific call we need to give the Latitude, Longitude, and Time that we want the weather for.
We fill in those to a url with the format https://api.forecast.io/forecast/{key}/{Latitude},{Longitude},{Time}.
Can you write Python code for it?

import json
import requests

with open('/Users/tom/Dropbox/bin/api-keys.txt') as f:
    key = json.load(f)['forecast.io']

url = "https://api.forecast.io/forecast/{key}/{Latitude},{Longitude},{Time}"

vals = df.loc[0, ['latitude', 'longitude', 'time']].rename(lambda x: x.title()).to_dict()
vals['Time'] = str(vals['Time']).replace(' ', 'T')
vals['key'] = key

r = requests.get(url.format(**vals))
resp = r.json()

resp.keys()


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
With that done, let's write with_weather out to disk. We'll get a Performance Warning since some of the columns are text, which are relatively slow for HDF5, but it's not a problem worht worrying about for a dataset this small.
If you needed you could encode the text ones as integers with pd.factorize, write the integers out the the HDF5 store, and store the mapping from integer to text description elsewhere.
Can you write Python code for it?

with_weather.to_hdf('data/cycle_store.h5', key='with_weather', append=False, method='table')
weather.to_hdf('data/cycle_store.h5', key='weather', append=False, method='table')


I am working on the file "Practical Pandas 02 - More Cleaning, More Data, and Merging.ipynb".
The first task is:
windBearing represent the direction the wind is coming from so the most common direction is from the S/SW. It may be clearer to flip that around to represent the wind direction; I'm not sure what's standard.
If we were feeling ambitious, we could try to color the wedges by the windspeed. Let's give it a shot!
We'll need to get the average wind speed in each of our bins from above. This is clearly a groupby, but what excatly is the grouper? This is where pandas Catagorical comes in handy. We'll pd.cut the wind direction, and group the wind data by that.
Can you write Python code for it?

wind = weather[['windSpeed', 'windBearing']].dropna()

ct = pd.cut(wind.windBearing, bins)
speeds = wind.groupby(ct)['windSpeed'].mean()
colors = plt.cm.BuGn(speeds.div(speeds.max()))


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
Because of a bug in pandas, we lost our timzone information when we filled in our missing values. Until that's fixed we'll have to manually add back the timezone info and convert. The actual values stored were UTC (which is good practice whenever you have timezone-aware timestamps), it just doesn't know that it's UTC.
Can you write Python code for it?

df = df.tz_localize('UTC').tz_convert('US/Central')
df.head()


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
Better, but this still isn't quite what we want. When we call .plot(x=..., y=...) the data are sorted before being plotted. This means that an observation from one ride gets mixed up with another. So we'll need to group by ride, and then plot.
Can you write Python code for it?

axes = df[df.is_morning].groupby(df.ride_id).plot(x='time',
                                                  y='distance_miles',
                                                  color='k',
                                                  figsize=(12, 5))


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
Cartography
We'll use Folium to do a bit of map plotting.
If you're using python3 (like I am) you'll need to use this pull request from tbicr,
or just clone the master of my fork, where I've merged the changes.
Since this is a practical pandas post, and not an intro to folium, I won't delve into the details here. The basics are that we initialize a Map with some coordinates and tiles, and then add lines to that map. The lines will come from the latitude and longitude columns of our DataFrame.
Here's a small helper function from birdage to inline the map in the notebook. This allows it to be viewable on nbviewer (which is rendering this blog post).
Can you write Python code for it?

def inline_map(map):
    """
    Embeds the HTML source of the map directly into the IPython notebook.

    This method will not work if the map depends on any files (json data). Also this uses
    the HTML5 srcdoc attribute, which may not be supported in all browsers.
    """
    from IPython.display import HTML
    map._build_map()
    return HTML('<iframe srcdoc="{srcdoc}" style="width: 100%; height: 510px; border: none"></iframe>'.format(srcdoc=map.HTML.replace('"', '"')))


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
Fun. The horizontal distance is the length of time it took me to make the ride. The starting point on the horizontal axis conveys the time that I set out.
I like this chart because it also conveys the start time of each ride.
The plot shows that the morning ride typically took longer, but we can verify that.
Can you write Python code for it?

ride_time = df.groupby(['ride_id', 'is_morning'])['ride_time_secs'].agg('max')
mean_time = ride_time.groupby(level=1).mean().rename(
    index={True: 'morning', False: 'evening'})
mean_time / 60


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
Much better. Groupby is one of the most powerful operations in pandas, and it pays to understand it well. Here's the same thing for the evening.
Can you write Python code for it?

axes = df[~df.is_morning].groupby(df.ride_id).plot(x='time',
                                                   y='distance_miles',
                                                   color='k',
                                                   figsize=(12, 5))


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
So the morning ride is typically shorter! But I think I know what's going on. We were misleading with our plot earlier since the range of the horizontal axis weren't identical. Always check the axis!
At risk of raising the ire of Hadley Whickham, we'll plot these on the same plot, with a secondary x-axis. (I think its OK in this case since the second is just a transformation – a 10 hour or so shift – of the first).
We'll plot evening first, use matplotlib's twinx method, and plot the morning on the second axes.
Can you write Python code for it?

fig, ax = plt.subplots()

morning_color = sns.xkcd_rgb['amber']
evening_color = sns.xkcd_rgb['dusty purple']

_ = df[~df.is_morning].groupby(df.ride_id).plot(x='time', y='distance_miles',
    color=evening_color, figsize=(12, 5),
    ax=ax, alpha=.9, grid=False)
ax2 = ax.twiny()
_ = df[df.is_morning].groupby(df.ride_id).plot(x='time', y='distance_miles',
    color=morning_color, figsize=(12, 5),
    ax=ax2, alpha=.9, grid=False)

# Create fake lines for our custom legend.
morning_legend = plt.Line2D([0], [0], color=morning_color)
evening_legend = plt.Line2D([0], [0], color=evening_color)

ax.legend([morning_legend, evening_legend], ['Morning', 'Evening'])


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
There's a couple problems. First of all, the data are split into morning and afternoon.
Let's create a new, boolean, column indicating whether the ride took place in the morning or afternoon.
Can you write Python code for it?

df['is_morning'] = df.time < datetime.time(12)

ax = df[df.is_morning].plot(x='time', y='distance_miles')


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
Timelines
We'll store the time part of the DatetimeIndex in a column called time.
Can you write Python code for it?


I am working on the file "Practical Pandas 03 - EDA.ipynb".
The first task is:
What to do here? We could drop change the frequency to micro- or nano-second resolution, and add, say, a half-second onto the duplicated observations.
Since this is just for fun though, I'm going to do the easy thing and throw out the duplicates (in real life you'll want to make sure this doesn't affect your analysis).
Then we can set the time column to be our index, which will make our later analysis a bit simpler.
Can you write Python code for it?

df = df.drop_duplicates(subset=['time']).set_index('time')
df.index.is_unique


I am working on the file "Practical-06-2. Exploration.ipynb".
The first task is:
Principal Components Analysis
Can you write Python code for it?

o_dir = os.path.join('outputs','pca')
if os.path.isdir(o_dir) is not True:
    print("Creating '{0}' directory.".format(o_dir))
    os.mkdir(o_dir)

pca = PCA()                               # Use all Principal Components
pca.fit(scdf)                             # Train model on all data
pcdf = pd.DataFrame(pca.transform(scdf))  # Transform data using model

for i in range(0,21):
    print("Amount of explained variance for component {0} is: {1:6.2f}%".format(i, pca.explained_variance_ratio_[i]*100))

print("The amount of explained variance of the SES score using each component is...")
sns.lineplot(x=list(range(1,len(pca.explained_variance_ratio_)+1)), y=pca.explained_variance_ratio_)

pca = PCA(n_components=11)
pca.fit(scdf)
scores = pd.DataFrame(pca.transform(scdf), index=scdf.index)
scores.to_csv(os.path.join(o_dir,'Scores.csv.gz'), compression='gzip', index=True)

# Adapted from https://stackoverflow.com/questions/22984335/recovering-features-names-of-explained-variance-ratio-in-pca-with-sklearn
i = np.identity(scdf.shape[1])  # identity matrix

coef = pca.transform(i)

loadings = pd.DataFrame(coef, index=scdf.columns)
loadings.to_csv(os.path.join(o_dir,'Loadings.csv.gz'), compression='gzip', index=True)

print(scores.shape)
scores.sample(5, random_state=42)

print(loadings.shape)
loadings.sample(5, random_state=42)

odf = pd.DataFrame(columns=['Variable','Component Loading','Score'])
for i in range(0,len(loadings.index)):
    row = loadings.iloc[i,:]
    for c in list(loadings.columns.values):
        d = {'Variable':loadings.index[i], 'Component Loading':c, 'Score':row[c]}
        odf = odf.append(d, ignore_index=True)

g = sns.FacetGrid(odf, col="Variable", col_wrap=4, height=3, aspect=2.0, margin_titles=True, sharey=True)
g = g.map(plt.plot, "Component Loading", "Score", marker=".")


I am working on the file "Practical-06-2. Exploration.ipynb".
The first task is:
Rescale the Loaded Data
We need this so that differences in the component scores don't cause the clustering algorithms to focus only on the 1st component.
Can you write Python code for it?

scaler = preprocessing.MinMaxScaler()

df[df.columns] = scaler.fit_transform(df[df.columns])

df.describe()

df.sample(3, random_state=42)


I am working on the file "Practical-06-3. Correlation.ipynb".
The first task is:

STOP. Make sure that you understand what the figure above is showing before proceeding to the next stage.

Finding Strong Correlations Numerically
Can you write Python code for it?

# Generate the matrix but capture the output this time
cdf = scdf.corr()
cdf['name'] = cdf.index # We need a copy of the index

corrh = 0.66 # Specify threshold for highly correlated?
print("! High correlation threshold is {0}.".format(corrh))

num_corrs = []
hi_corrs  = []

for c in cdf.name.unique():
    if c != 'name':
        # Some formatting
        print("=" * 10 + f" {c} " + "=" * 10)

        # Find highly correlated variables
        hits = cdf.loc[(abs(cdf[c]) >= corrh), c]
        hits.drop(c, inplace=True)

        if hits.size == 0: # No correlations > corrs
            print("+ Not highly correlated with other variables.")
        else:
            num_corrs.append(hits.size)

            print("- High correlations ({0}) with other variables:".format(hits.size))
            print("    " + "\n    ".join(hits.index.values))
            hi_corrs.append(hits.size)

sns.distplot(hi_corrs, bins=range(0,20), kde=False).set_title(
    "Number of Strong Correlations (> " + str(corrh) + ")  with Other Variables")


I am working on the file "Practical-06-3. Correlation.ipynb".
The first task is:
Finding Strong Correlations Visually
Can you write Python code for it?

# And here's a correlation heatmap... which is easier to read but has
# less detail. What it *does* highlight is high levels of *negative*
# correlation as well as positive, so you'll need absolute difference,
# not just whether something is more than 0.x correlated.
#
# From https://seaborn.pydata.org/examples/many_pairwise_correlations.html
cdf = scdf.corr()

# Generate a mask for the upper triangle
mask = np.zeros_like(cdf, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(10, 10))

# Generate a custom diverging colormap
cm = sns.diverging_palette(240, 10, as_cmap=True)

# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(cdf, mask=mask, cmap=cm, vmax=1.0, vmin=-1.0, center=0,
            square=True, linewidths=.1, cbar_kws={"shrink": .5})


I am working on the file "Practical-06-3. Correlation.ipynb".
The first task is:
Stripping Out 'Redundant' Variables
Let's remove any variable that has a 'lot' of strong correlations correlations with other variables, though we need to define what is 'a lot'. This will reduce the dimensionality of our data and make clustering a bit easier. An alternative approach to dimensionality reduction -- which can be more 'robust' if we ensure that all of the data has unit variance (which we've done using the MinMaxScaler), though harder for many to understand -- would be to apply Principal Components Analysis (PCA) to the data set and to work with the eigenvalues afterwards. PCA is also available in sklearn.
We'll set our threshold at 5.0 based on a visual inspection of the chart above.
Can you write Python code for it?

corrh     = 0.66 # Specify threshold for highly correlated?
maxcorrs  = 4.0 # What's our threshold for too many strong correlations?
threshold = 0.5*maxcorrs # What's our threshold for too many strong correlations with columns we keep!

print("! High correlation threshold is {0}.".format(corrh))

to_drop = [] # Columns to drop
to_keep = [] # Columns to keep

num_corrs = []
hi_corrs  = []

for c in cdf.columns:
    if c != 'name':

        # Find highly correlated variables, but let's
        # keep the focus on *positive* correlation now
        hits = cdf.loc[(cdf[c] >= corrh), c]
        hits.drop(c, inplace=True)

        multi_vals = False

        # Remove ones with many correlations
        if hits.size >= maxcorrs:
            print(f"- {c} exceeds maxcorr ({maxcorrs}) correlation threshold (by {hits.size-threshold}).")
            s1 = set(to_keep)
            s2 = set(hits.index.values)
            #print("Comparing to_keep (" + ", ".join(s1) + ") to hits (" + ", ".join(s2) + ")")
            s1 &= s2
            #print("Column found in 'many correlations' :" + str(s1))
            if len(s1) >= threshold:
                multi_vals = True
                print(f"    - Dropping b/c exceed {threshold} correlations with retained cols: \n        -" + "\n        -".join(s1))
            else:
                print(f"    + Keeping b/c fewer than {threshold} correlations with retained columns.")
        else:
            print(f"+ {c} falls below maxcorr ({maxcorrs}) correlation threshold (by {abs(threshold-hits.size)}).")

        if multi_vals==True:
            to_drop.append(c)
        else:
            to_keep.append(c)

print(" ")
print("To drop ({0}): ".format(len(to_drop)) + ", ".join(to_drop))
print(" ")
print("To keep ({0}): ".format(len(to_keep)) + ", ".join(to_keep))

to_save = scdf.drop(to_drop, axis=1, errors='raise')
print("Retained variables: " + ",...


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
(Hopefully, the secret agents will have good memories and won’t forget each other’s secret code names during the secret mission.)
My solution:
Can you write Python code for it?

names = ['Mary', 'Isla', 'Sam']

secret_names = map(hash, names)

for i in secret_names:
     print(i)


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
Don’t iterate over lists. Use map and reduce.
Map
Map takes a function and a collection of items. It makes a new, empty collection, runs the function on each item in the original collection and inserts each return value into the new collection. It returns the new collection.
This is a simple map that takes a list of names and returns a list of the lengths of those names:
Can you write Python code for it?

name_lengths = map(len, ["Mary", "Isla", "Sam"])

for i in name_lengths:
    print(i)


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
How does this code come up with its initial a? The starting point for the number of incidences of 'Sam' cannot be 'Mary read a story to Sam and Isla.' The initial accumulator is specified with the third argument to reduce(). This allows the use of a value of a different type from the items in the collection.
Why are map and reduce better?
First, they are often one-liners.
Second, the important parts of the iteration - the collection, the operation and the return value - are always in the same places in every map and reduce.
Third, the code in a loop may affect variables defined before it or code that runs after it. By convention, maps and reduces are functional.
Fourth, map and reduce are elemental operations. Every time a person reads a for loop, they have to work through the logic line by line. There are few structural regularities they can use to create a scaffolding on which to hang their understanding of the code. In contrast, map and reduce are at once building blocks that can be combined into complex algorithms, and elements that the code reader can instantly understand and abstract in their mind. “Ah, this code is transforming each item in this collection. It’s throwing some of the transformations away. It’s combining the remainder into a single output.”
Fifth, map and reduce have many friends that provide useful, tweaked versions of their basic behaviour. For example: filter, all, any and find.
Exercise 2. Try rewriting the code below using map, reduce and filter. Filter takes a function and a collection. It returns a collection of every item for which the function returned True.
Can you write Python code for it?

people = [{'name': 'Mary', 'height': 160},
          {'name': 'Isla', 'height': 80},
          {'name': 'Sam'}]

height_total = 0
height_count = 0
for person in people:
    if 'height' in person:
        height_total += person['height']
        height_count += 1

if height_count > 0:
    average_height = height_total / height_count
    print(average_height)


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
If this seems tricky, try not thinking about the operations on the data. Think of the states the data will go through, from the list of people dictionaries to the average height. Don’t try and bundle multiple transformations together. Put each on a separate line and assign the result to a descriptively-named variable. Once the code works, condense it.
Can you write Python code for it?

people = [{'name': 'Mary', 'height': 160},
          {'name': 'Isla', 'height': 80},
          {'name': 'Sam'}]

heights = map(lambda x: x['height'],
              filter(lambda x: 'height' in x, people))

heightsList = list(heights) # Neccesary in Python3

if len(heightsList) > 0:
    from operator import add
    average_height = reduce(add, heightsList) / len(heightsList)
    print(average_height)


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
The code is written imperatively. A functional version would be declarative. It would describe what to do, rather than how to do it.
Use functions
A program can be made more declarative by bundling pieces of the code into functions.
Can you write Python code for it?

from random import random

def move_cars():
    for i, _ in enumerate(car_positions):
        if random() > 0.3:
            car_positions[i] += 1

def draw_car(car_position):
    print('-' * car_position)

def run_step_of_race():
    global time
    time -= 1
    move_cars()

def draw():
    print('')
    for car_position in car_positions:
        draw_car(car_position)

time = 5
car_positions = [1, 1, 1]

while time:
    run_step_of_race()
    draw()


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
This is a functional function:
Can you write Python code for it?


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
This is a map that squares every number in the passed collection:
Can you write Python code for it?

squares = map(lambda x: x * x, [0, 1, 2, 3, 4])

for i in squares:
    print(i)


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
This map doesn’t take a named function. It takes an anonymous, inlined function defined with lambda. The parameters of the lambda are defined to the left of the colon. The function body is defined to the right of the colon. The result of running the function body is (implicitly) returned.
The unfunctional code below takes a list of real names and replaces them with randomly assigned code names.
Can you write Python code for it?

import random

names = ['Mary', 'Isla', 'Sam']
code_names = ['Mr. Pink', 'Mr. Orange', 'Mr. Blonde']

for i in range(len(names)):
    names[i] = random.choice(code_names)

print(names)


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
Write declaratively, not imperatively
The program below runs a race between three cars. At each time step, each car may move forwards or it may stall. At each time step, the program prints out the paths of the cars so far. After five time steps, the race is over.
-
--
--
--
--
---
---
--
---
----
---
----
----
----
-----
This is the program:
Can you write Python code for it?

from random import random

time = 5
car_positions = [1, 1, 1]

while time:
    # decrease time
    time -= 1

    print('')
    for i in range(len(car_positions)):
        # move car
        if random() > 0.3:
            car_positions[i] += 1

        # draw car
        print('-' * car_positions[i])


I am working on the file "PracticalFunctionalProgramming-Python.ipynb".
The first task is:
x is the current item being iterated over. a is the accumulator. It is the value returned by the execution of the lambda on the previous item. reduce() walks through the items. For each one, it runs the lambda on the current a and x and returns the result as the a of the next iteration.
What is a in the first iteration? There is no previous iteration result for it to pass along. reduce() uses the first item in the collection for a in the first iteration and starts iterating at the second item. That is, the first x is the second item.
This code counts how often the word 'Sam' appears in a list of strings:
Can you write Python code for it?

sentences = ['Mary read a story to Sam and Isla.',
             'Isla cuddled Sam.',
             'Sam chortled.']

sam_count1 = 0
for sentence in sentences:
    sam_count1 += sentence.count('Sam')

print(sam_count1)

sentences = ['Mary read a story to Sam and Isla.',
             'Isla cuddled Sam.',
             'Sam chortled.']

sam_count2 = reduce(lambda a, x: a + x.count('Sam'),
                   sentences,
                   0)

print(sam_count2)


I am working on the file "PracticalModelFitting.ipynb".
The first task is:
Let us examine the model fit:
Can you write Python code for it?

f, a = plt.subplots(1,1)
a.plot(time, curve, label='Tissue curve')
a.plot(time, twocx.fit, label='Model fit')
plt.legend(loc=4)


I am working on the file "PracticalModelFitting.ipynb".
The first task is:
This fit produced the following parameters:
Can you write Python code for it?


I am working on the file "PracticalModelFitting.ipynb".
The first task is:
This looks like  a pretty arterial input function (left) and a tissue curve (right).
Tracer-kinetic analysis
To further analyze this data, we need a library for model fitting. Here, we use
https://github.com/michimichi/compartmentmodels. This particular library is currently under development, but in a usable status.
Can you write Python code for it?

import compartmentmodels.compartmentmodels as CM


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ciclos de control
Cuando queremos ejecutar código varias veces tenemos varias opciones, vamos a explorar rapidamente el ciclo for.
python
    for paso in pasos:
        ...
        codigo_a_ejecutar(paso)
        ...
En este caso el codigo se ejecutará tantas veces sean necesarias para usar todos los elementos que hay en pasos.
Por ejemplo, pordemos ejecutar la multiplicacion por 2 en cada uno de los datos:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Con los mismos resultados:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejecuta la prueba de abajo para saber si has creado el codigo correcto
Can you write Python code for it?

from pruebas_1 import prueba_1_1
prueba_1_1(_, c)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejecuta las pruebas de abajo
Can you write Python code for it?

from pruebas_1 import prueba_1_3
prueba_1_3(C, D)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejercicio
Define una función que convierta grados Celsius a grados Farenheit, de acuerdo a la siguiente formula:
$$
F = \frac{9}{5} C + 32
$$
Can you write Python code for it?

def cel_a_faren(grados_cel):

    grados_faren = # Escribe el codigo para hacer el calculo aqui

    return grados_faren


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Es decir, $n = 10$.
Can you write Python code for it?

def metodo_biseccion(funcion, x1, x2, n):
    xs = []
    for i in range(n):
        xs.append(biseccion(x1, x2))
        if funcion(x2)*funcion(xs[-1]) > 0:
            x2 = xs[-1]
        else:
            x1 = xs[-1]
    return xs[-1]

metodo_biseccion(f, 1.0, 2.0, 10)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Esta linea de codigo es equivalente a definir una función matemática de la siguiente manera:
$$
f(x) = x^2 + 1
$$
Por lo que si la evaluamos con $x = 2$, obviamente obtendremos como resultado $5$.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Esta notación que introducimos es muy util para funciones matemáticas, pero esto nos obliga a pensar en las definiciones de una manera funcional, lo cual no siempre es la solución (sobre todo en un lenguaje con un paradigma de programación orientado a objetos).
Esta función tambien puede ser escrita de la siguiente manera:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Listas
Las listas son una manera de guardar varios datos en un mismo arreglo. Podemos tener por ejemplo:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Método de bisección
Para obtener una raiz real de un polinomio $f(x) = x^3 + 2 x^2 + 10 x - 20$ por el metodo de bisección, tenemos que primero definir dos puntos, uno que evaluado en el polinomio nos de positivo, y otro que nos de negativo. Propondremos $x_1 = 1$ y $x_2 = 2$, y los evaluaremos para asegurarnos de que cumplan lo que acabamos de pedir.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Si volvemos a ejecutar el codigo que teniamos, sustituyendo esta función, obtendremos exactamente el mismo resultado:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Si, yo se que parece raro, pero si lo revisas con calma te daras cuenta que funciona.
Ya casi llegamos, tan solo tenemos que ir guardando cada una de las aproximaciones en un arreglo, y calcularemos el numero de aproximaciones necesarias para llegar a la precisión requerida. Tomemos en cuenta $\varepsilon = 0.001$. La formula para el numero de aproximaciones necesarias es:
$$n = \frac{\ln{a} - \ln{\varepsilon}}{\ln{2}}$$
donde $a$ es el tamaño del intervalo original.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Y ahora lo que tenemos que hacer es poner una condicion para que $x_M$ se intercambie con $x_1$ ó $x_2$ dependiendo del signo.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Y para probar trata de convertir algunos datos:
Can you write Python code for it?

cel_a_faren(10)

cel_a_faren(50)

from pruebas_1 import prueba_1_2
prueba_1_2(cel_a_faren)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Y podriamos seguir haciendo esto hasta que tengamos la exactitud que queremos, pero esa no seria una manera muy inteligente de hacerlo (tenemos una maquina a la que le gusta hacer tareas repetitivas y no la aprovechamos?).
En vez de eso, notemos que la formula no cambia absolutamente en nada, por lo que la podemos hacer una funcion y olvidarnos de ella.
Can you write Python code for it?

def biseccion(x1, x2):
    return (x1 + x2)/2.0


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
y aun muchas cosas mas, pero por ahora es momento de empezar con la práctica.
Ejercicio

Crea una lista C con los enteros positivos de un solo digito, es decir: $\left{ x \in \mathbb{Z} \mid 0 \leq x < 10\right}$
Crea una segunda lista D con los cuadrados de cada elemento de C
Can you write Python code for it?

C = [] # Escribe el codigo para declarar el primer arreglo adentro de los corchetes

C

D = []

# Escribe el codigo de tu ciclo for aqui

D


I am working on the file "Practicas/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
ó agregarlo en una lista nueva:
Can you write Python code for it?

B = []
for dato in A:
    B.append(dato*2)

B


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Ahora que tenemos estos valores, podemos graficar el comportamiento de este sistema, primero importamos la libreria matplotlib:
Can you write Python code for it?

%matplotlib inline
from matplotlib.pyplot import plot


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Ejercicio
Crea codigo para una iteración mas con estos mismos parametros y despliega el resultado.
Can you write Python code for it?

x3 = # Escribe el codigo de tus calculos aqui

from pruebas_2 import prueba_2_1
prueba_2_1(x0, x1, x2, x3, _)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Ejercicio
Grafica el comportamiento de la siguiente ecuación diferencial.
$$
\dot{x}  = x^2 - 5 x + \frac{1}{2} \sin{x} - 2
$$

Nota: Asegurate de impotar todas las librerias que puedas necesitar
Can you write Python code for it?

ts = # Escribe aqui el codigo que genera un arreglo de puntos equidistantes (linspace)
x0 = # Escribe el valor de la condicion inicial

# Importa las funciones de librerias que necesites aqui

G = lambda x, t: # Escribe aqui el codigo que describe los calculos que debe hacer la funcion

xs = # Escribe aqui el comando necesario para simular la ecuación diferencial

plot(ts, xs);

from pruebas_2 import prueba_2_2
prueba_2_2(ts, xs)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Ejercicio
Modela matematicamente la ecuación diferencial del ejercicio anterior, usando una representación de función de transferencia.

Nota: De nuevo, no desesperes, escribe tu ecuación diferencial y aplica la transformada de Laplaca tal como te enseñaron tus abuelos hace tantos años...
Can you write Python code for it?

G = tf([], []) # Escribe los coeficientes de la función de transferencia

xs, ts = step(G)
plot(ts, xs);

from pruebas_2 import prueba_2_5
prueba_2_5(ts, xs)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Esto va a ser tardado, mejor digamosle a Python que es lo que tenemos que hacer, y que no nos moleste hasta que acabe, podemos usar un ciclo for y una lista para guardar todos los valores de la trayectoria:
Can you write Python code for it?

xs = [x0]
for t in range(20):
    xs.append(xs[-1] + F(xs[-1])*Δt)

xs


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Mandamos a llamar la función plot:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Momento... que esta pasando? Resulta que este $\Delta t$ es demasiado grande, intentemos con 20 iteraciones:
$$
\begin{align}
\Delta t &= 0.5 \
x(0) &= 1
\end{align}
$$
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Sin embargo debido a que el periodo de integración que utilizamos es demasiado grande, la solución es bastante inexacta, podemos verlo al graficar contra la que sabemos es la solución de nuestro problema:
Can you write Python code for it?

from numpy import linspace, exp

ts = linspace(0, 10, 20)
plot(xs)
plot(exp(-ts));


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Solución a ecuaciones diferenciales de orden superior
Si ahora queremos obtener el comportamiento de una ecuacion diferencial de orden superior, como:
$$
\ddot{x} = -\dot{x} - x + 1
$$
Tenemos que convertirla en una ecuación diferencial de primer orden para poder resolverla numericamente, por lo que necesitaremos convertirla en una ecuación diferencial matricial, por lo que empezamos escribiendola junto con la identidad $\dot{x} = \dot{x}$ en un sistema de ecuaciones:
$$
\begin{align}
\dot{x} &= \dot{x} \
\ddot{x} &= -\dot{x} - x + 1
\end{align}
$$
Si extraemos el operador derivada del lado izquierda, tenemos:
$$
$$
\begin{align}
\frac{d}{dt} x &= \dot{x} \
\frac{d}{dt} \dot{x} &= -\dot{x} - x + 1
\end{align}
$$
$$
O bien, de manera matricial:
$$
\frac{d}{dt}
\begin{pmatrix}
x \
\dot{x}
\end{pmatrix} =
\begin{pmatrix}
0 & 1 \
-1 & -1
\end{pmatrix}
\begin{pmatrix}
x \
\dot{x}
\end{pmatrix} +
\begin{pmatrix}
0 \
1
\end{pmatrix}
$$
Esta ecuación ya no es de segundo orden, es de hecho, de primer orden, sin embargo nuestra variable ha crecido a ser un vector de estados, por el momento le llamaremos $X$, asi pues, lo podemos escribir como:
$$
\frac{d}{dt} X = A X + B
$$
en donde:
$$
A = \begin{pmatrix}
0 & 1 \
-1 & -1
\end{pmatrix} \quad \text{y} \quad B =
\begin{pmatrix}
0 \
1
\end{pmatrix}
$$
y de manera similar, declarar una función para dar a odeint.
Can you write Python code for it?

from numpy import matrix, array

def F(X, t):
    A = matrix([[0, 1], [-1, -1]])
    B = matrix([[0], [1]])
    return array((A*matrix(X).T + B).T).tolist()[0]

ts = linspace(0, 10, 100)
xs = odeint(func=F, y0=[0, 0], t=ts)

plot(xs);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
Sympy
Y por ultimo, hay veces en las que incluso podemos obtener una solución analítica de una ecuación diferencial, siempre y cuando cumpla ciertas condiciones de simplicidad.
Can you write Python code for it?

from sympy import var, Function, dsolve
from sympy.physics.mechanics import mlatex, mechanics_printing
mechanics_printing()

var("t")

x = Function("x")(t)
x, x.diff(t)

solucion = dsolve(x.diff(t) + x, x)
solucion


I am working on the file "Practicas/.ipynb_checkpoints/Practica 2 - Solucion de ecuaciones diferenciales-checkpoint.ipynb".
The first task is:
odeint
Este método funciona tan bien, que ya viene programado dentro de la libreria scipy, por lo que solo tenemos que importar esta librería para utilizar este método.
Sin embargo debemos de tener cuidado al declarar la función $F(x, t)$. El primer argumento de la función se debe de referir al estado de la función, es decir $x$, y el segundo debe de ser la variable independiente, en nuestro caso el tiempo.
Can you write Python code for it?

from scipy.integrate import odeint

F = lambda x, t : -x

x0 = 1
ts = linspace(0, 10, 100)
xs = odeint(func=F, y0=x0, t=ts)

plot(ts, xs);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Ahora solo damos el tamaño de la imagen, y obtenemos el objeto del axis de la grafica con el metodo gca para poder graficar:
Can you write Python code for it?

f = figure(figsize=(8, 8))
axi = f.gca()

axi.plot(t, y);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
De la misma manera lo metemos en una función, para que nuestro codigo quede:
Can you write Python code for it?

def coordenadas_amortiguador(y0, yf, x):

    ancho = (y0 - yf)/5
    alto = yf - y0
    cuerpo = alto/2
    pata = alto/4

    ax = [-0.5*ancho + x, -0.5*ancho + x, 0.5*ancho + x, 0.5*ancho + x]
    ay = [yf - pata, y0 + pata, y0 + pata, yf - pata]
    bx = [x, x]
    by = [y0 + cuerpo, yf]
    cx = [x, x]
    cy = [y0, y0 + pata]

    return ax, ay, bx, by, cx, cy

ax, ay, bx, by, cx, cy = coordenadas_amortiguador(-4, 6, 1)

f = figure(figsize=(8, 8))
axi = f.gca()

axi.plot(ax, ay, bx, by, cx, cy, lw=2, color="gray")

axi.set_xlim(-10, 10)
axi.set_ylim(-10, 10);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Ejercicio
¿Cuanto crees que pese una bola de demolición? ¿$500 kg$? ¿$1000 kg$? Grafica el comportamiento del sistema ante una fuerza de estas magnitudes, utilizando la función que acabamos de crear.
Can you write Python code for it?

t1, x1 = suspension(1200, 1500, 15000, ) # Agrega la fuerza necesaria para la primer simulacion

t2, x2 = # Completa el codigo para la segunda simulacion

from pruebas_3 import prueba_3_1
prueba_3_1(t1, x1, t2, x2)


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
El amortiguador es un poco mas complejo, son 3 lineas, 2 para las patitas y una para el cuerpo:
Can you write Python code for it?

y0 = -5
yf = 5
alto = yf - y0
cuerpo = alto/2
pata = alto/4
ancho = (yf - y0)/5
x = 2

f = figure(figsize=(8, 8))
axi = f.gca()

axi.plot([-0.5*ancho + x, -0.5*ancho + x, 0.5*ancho + x, 0.5*ancho + x],
         [yf - pata, y0 + pata, y0 + pata, yf - pata],
         [x, x], [y0 + cuerpo, yf],
         [x, x], [y0, y0 + pata], lw=2, color="gray")

axi.set_xlim(-10, 10)
axi.set_ylim(-10, 10);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Importamos el modulo de animacion de la libreria matplotlib:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Interactividad
Esta es la parte divertida, para interactuar con los datos del problema, podemos usar una función especifica de IPython, tan solo tenemos que dar una función, y los rangos de variación de sus argumentos, para tener:
Can you write Python code for it?

# Se importan widgets de IPython para interactuar con la funcion
from IPython.html.widgets import interact, fixed

# Se llama a la funcion interactiva
interact(suspension, m=(1000, 2500), c=(0, 2500), k=(0, 20000), F=(1, 10000));


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Muy bien, nuestra suspensión se ha movido $10 cm$ con una fuerza comparable con el peso de una persona. Ahora notamos que a la derecha tenemos espacio vacio, por lo que pondremos limite al eje $x$:
Can you write Python code for it?

f = figure(figsize=(16, 8))
axi = f.gca()

axi.plot(t, y)

axi.set_xlim(0, 10);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Para poder ver en una escala razonable esta gráfica pondremos un limite al eje $y$ tambien:
Can you write Python code for it?

from numpy import linspace

t = linspace(0, 10, 1000)
y, t = step(K*G, t)

f = figure(figsize=(16, 8))
axi = f.gca()

axi.plot(t, -y)

axi.set_xlim(0, 10)
axi.set_ylim(-1.2, 0);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Por ultimo, para animar esto, tenemos que obtener los puntos de la trayectoria:
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Por ultimo, para la masa tan solo necesitamos un rectangulo, el cual tenemos que importar de la libreria de matplotlib del modulo patches:
Can you write Python code for it?

from matplotlib.patches import Rectangle

f = figure(figsize=(8, 8))
axi = f.add_subplot(111, autoscale_on=False, xlim=(-3, 3), ylim=(-3, 3))

carro = Rectangle((0,0), 1, 1, lw=0.5)

carro.set_xy((-0.5, -0.5))

axi.add_patch(carro);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Sin embargo el comportamiento del sistema a penas es visible, $0.00006 m = .6 mm$ en posición es practicamente nada. Recordemos que usamos tan solo usamos una fuerza de $1 N$, para amplificar esta entrada del sistema utilizamos otro bloque con una ganancia de la magnitud de la fuerza a aplicar:
Can you write Python code for it?

K = tf([1000], [1])
K

y, t = step(K*G)

f = figure(figsize=(8, 8))
axi = f.gca()

axi.plot(t, y);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Y uniendo todo, nos queda el codigo:
Can you write Python code for it?

f = figure(figsize=(8, 8))
axi = f.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-3, 1))

carro = Rectangle((0,0), 1, 1, lw=0.5)
carro.set_xy((-0.5, -3))
axi.add_patch(carro)

x, y = coordenadas_resorte(0, -2, -0.25, 20)
axi.plot(x, y, lw=2, color="gray")

ax, ay, bx, by, cx, cy = coordenadas_amortiguador(-2, 0, 0.25)
axi.plot(ax, ay, bx, by, cx, cy, lw=2, color="gray");

axi.set_ylim(-4, 0);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Y utilizamos el siguiente codigo para la creacion de cada uno de los cuadros del GIF:
Can you write Python code for it?

# Se define el tamaño de la figura
fig = figure(figsize=(8, 8))

# Se define una sola grafica en la figura y se dan los limites de los ejes x y y
axi = fig.add_subplot(111, autoscale_on=False, xlim=(-1.5, 1.5), ylim=(-2, 1))

# Se hacen invisibles los ejes
axi.axes.get_xaxis().set_visible(False)
axi.axes.get_yaxis().set_visible(False)

# Se quitan los bordes de la grafica
axi.axes.spines["right"].set_color("none")
axi.axes.spines["left"].set_color("none")
axi.axes.spines["top"].set_color("none")
axi.axes.spines["bottom"].set_color("none")

# Se utilizan graficas de linea para el resorte y amortiguador
resorte, = axi.plot([], [], lw=2, color='gray')
amor1, = axi.plot([], [], lw=2, color='gray')
amor2, = axi.plot([], [], lw=2, color='gray')
amor3, = axi.plot([], [], lw=2, color='gray')
# Se utiliza un rectangulo para la masa
masa = Rectangle((10,10), 1, 1, lw=0.5)

def init():
    # Esta funcion se ejecuta una sola vez y sirve para inicializar el sistema
    resorte.set_data([], [])
    amor1.set_data([], [])
    amor2.set_data([], [])
    amor3.set_data([], [])
    masa.set_xy((0, 0))
    axi.add_patch(masa)
    return resorte, amor1, amor2, amor3, masa

def animate(i):
    # Esta funcion se ejecuta para cada cuadro del GIF

    # Se obtienen las coordenadas del resorte y se meten los datos en su grafica de linea
    xs, ys = coordenadas_resorte(-y[i], 1, -0.25, 20)
    resorte.set_data(xs, ys)

    # Se obtienen las coordenadas del amortiguador y se meten los datos en cada una de
    # las graficas de linea
    ax, ay, bx, by, cx, cy = coordenadas_amortiguador(-y[i], 1, 0.25)
    amor1.set_data(ax, ay)
    amor2.set_data(bx, by)
    amor3.set_data(cx, cy)

    # Se meten los datos de ubicacion de la masa
    masa.set_xy((-0.5, -1 - y[i]))
    return resorte, amor1, amor2, amor3, masa

# Se hace la animacion dandole el nombre de la figura definida al principio, la funcion que
# se debe ejecutar para cada cuadro, el numero de cuadros que se debe de hacer, el periodo
# de cada cuadro y la funcion...


I am working on the file "Practicas/.ipynb_checkpoints/Practica 3 - Visualizacion de sistemas mecanicos-checkpoint.ipynb".
The first task is:
Ya que tenemos esto, podemos meterlo en una funcion que nos de las coordenadas y el codigo nos queda mas simple:
Can you write Python code for it?

def coordenadas_resorte(y0, yf, x, N):

    ancho = (y0 - yf)/5
    xs = zeros(N) + x
    xs[N/4:N*3/4] = ancho*0.5*(-1)**arange(N/2) + x

    return xs, linspace(y0, yf, N)

x, y = coordenadas_resorte(-5, 5, 0, 20)

f = figure(figsize=(8, 8))
axi = f.gca()

axi.plot(x, y, lw=2, color="gray")

axi.set_xlim(-10, 10)
axi.set_ylim(-10, 10);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 4 - Movimientos de cuerpos rigidos-checkpoint.ipynb".
The first task is:
Entonces, tendremos el mismo resultado, con un codigo mas limpio.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 4 - Movimientos de cuerpos rigidos-checkpoint.ipynb".
The first task is:
Para empezar definiremos nuestra posición de inicio, como la coordenada:
$$
P_1 =
\begin{pmatrix}
1 \
0 \
0
\end{pmatrix}
$$
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 4 - Movimientos de cuerpos rigidos-checkpoint.ipynb".
The first task is:
Pero podemos hacer algo mejor, podemos definir una función que nos devuelva una matriz de rotación, dandole como argumento el angulo de rotación.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 4 - Movimientos de cuerpos rigidos-checkpoint.ipynb".
The first task is:
Podemos definir matrices de la siguiente manera, y ver que el resultado es lo que esperariamos si quisieramos rotar el vector unitario $\hat{i}$ , con $30^o$ es decir $\frac{\tau}{12}$.
Can you write Python code for it?


I am working on the file "Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb".
The first task is:
En este punto ya tenemos nuestros datos de la simulación, tan solo queda graficarlos para interpretar los resultados:
Can you write Python code for it?

%matplotlib inline
from matplotlib.pyplot import style, plot, figure
style.use("ggplot")

fig1 = figure(figsize = (8, 8))

ax1 = fig1.gca()

ax1.plot(xs);

fig2 = figure(figsize = (8, 8))

ax2 = fig2.gca()

ax2.plot(qs)
ax2.plot(q̇s);


I am working on the file "Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb".
The first task is:
Pero las gráficas de trayectoria son aburridas, recordemos que podemos hacer una animación con matplotlib:
Can you write Python code for it?

from matplotlib import animation
from numpy import sin, cos, arange

# Se define el tamaño de la figura
fig = figure(figsize=(8, 8))

# Se define una sola grafica en la figura y se dan los limites de los ejes x y y
axi = fig.add_subplot(111, autoscale_on=False, xlim=(-1.5, 1.5), ylim=(-2, 1))

# Se utilizan graficas de linea para el eslabon del pendulo
linea, = axi.plot([], [], "-o", lw=2, color='gray')

def init():
    # Esta funcion se ejecuta una sola vez y sirve para inicializar el sistema
    linea.set_data([], [])
    return linea

def animate(i):
    # Esta funcion se ejecuta para cada cuadro del GIF

    # Se obtienen las coordenadas x y y para el eslabon
    xs, ys = [[0, cos(qs[i])], [0, sin(qs[i])]]
    linea.set_data(xs, ys)

    return linea

# Se hace la animacion dandole el nombre de la figura definida al principio, la funcion que
# se debe ejecutar para cada cuadro, el numero de cuadros que se debe de hacer, el periodo
# de cada cuadro y la funcion inicial
ani = animation.FuncAnimation(fig, animate, arange(1, len(qs)), interval=25,
                              blit=True, init_func=init)

# Se guarda el GIF en el archivo indicado
ani.save('./imagenes/pendulo-simple.gif', writer='imagemagick');


I am working on the file "Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb".
The first task is:
Utilizamos la función odeint para simular el comportamiento del pendulo, dandole la función que programamos con la dinámica de $f(x)$ y sacamos los valores de $q$ y $\dot{q}$ que nos devolvió odeint envueltos en el estado $x$
Can you write Python code for it?

xs = odeint(func = f, y0 = x0, t = ts)
qs, q̇s = list(zip(*xs.tolist()))


I am working on the file "Practicas/.ipynb_checkpoints/Practica 5 - Modelado de Robots-checkpoint.ipynb".
The first task is:
Vamos a simular desde el tiempo $0$, hasta $10$, y las condiciones iniciales del pendulo son $q=0$ y $\dot{q} = 0$.
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Con los mismos resultados:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejecuta la prueba de abajo para saber si has creado el codigo correcto
Can you write Python code for it?

from pruebas_1 import prueba_1_1
prueba_1_1(_, c)


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejecuta las pruebas de abajo
Can you write Python code for it?

from pruebas_1 import prueba_1_3
prueba_1_3(C, D)


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejercicio
Define una función que convierta grados Celsius a grados Farenheit, de acuerdo a la siguiente formula:
$$
F = \frac{9}{5} C + 32
$$
Can you write Python code for it?

def cel_a_faren(grados_cel):

    grados_faren = # Escribe el codigo para hacer el calculo aqui

    return grados_faren


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Ejercicio
Ejecuta el siguiente calculo y guardalo en una variable:
$$
c = \pi *10^2
$$

Nota: Una vez que hayas concluido el calculo y guardado el valor en una variable, puedes desplegar el valor de cualquier variable al ejecutar en una celda el nombre de la variable
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Es decir, $n = 10$.
Can you write Python code for it?

def metodo_biseccion(funcion, x1, x2, n):
    xs = []
    for i in range(n):
        xs.append(biseccion(x1, x2))
        if funcion(x2)*funcion(xs[-1]) > 0:
            x2 = xs[-1]
        else:
            x1 = xs[-1]
    return xs[-1]

metodo_biseccion(f, 1.0, 2.0, 10)


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Esta notación que introducimos es muy util para funciones matemáticas, pero esto nos obliga a pensar en las definiciones de una manera funcional, lo cual no siempre es la solución (sobre todo en un lenguaje con un paradigma de programación orientado a objetos).
Esta función tambien puede ser escrita de la siguiente manera:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Funciones
Podemos definir funciones propias de la siguiente manera:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Listas
Las listas son una manera de guardar varios datos en un mismo arreglo. Podemos tener por ejemplo:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Método de bisección
Para obtener una raiz real de un polinomio $f(x) = x^3 + 2 x^2 + 10 x - 20$ por el metodo de bisección, tenemos que primero definir dos puntos, uno que evaluado en el polinomio nos de positivo, y otro que nos de negativo. Propondremos $x_1 = 1$ y $x_2 = 2$, y los evaluaremos para asegurarnos de que cumplan lo que acabamos de pedir.
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Si volvemos a ejecutar el codigo que teniamos, sustituyendo esta función, obtendremos exactamente el mismo resultado:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Si, yo se que parece raro, pero si lo revisas con calma te daras cuenta que funciona.
Ya casi llegamos, tan solo tenemos que ir guardando cada una de las aproximaciones en un arreglo, y calcularemos el numero de aproximaciones necesarias para llegar a la precisión requerida. Tomemos en cuenta $\varepsilon = 0.001$. La formula para el numero de aproximaciones necesarias es:
$$n = \frac{\ln{a} - \ln{\varepsilon}}{\ln{2}}$$
donde $a$ es el tamaño del intervalo original.
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Una vez que tenemos dos puntos de los que sabemos que definen el intervalo donde se encuetra una raiz, podemos empezar a iterar para descubrir el punto medio.
$$x_M = \frac{x_1 + x_2}{2}$$
Si hacemos esto ingenuamente y lo evaluamos en la función, podremos iterar manualmente:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Variables
Las variables pueden ser utilizadas en cualquier momento, sin necesidad de declararlas, tan solo usalas!
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Y ahora lo que tenemos que hacer es poner una condicion para que $x_M$ se intercambie con $x_1$ ó $x_2$ dependiendo del signo.
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Y para probar trata de convertir algunos datos:
Can you write Python code for it?


I am working on the file "Practicas/P1/.ipynb_checkpoints/Practica 1 - Introduccion a Jupyter-checkpoint.ipynb".
The first task is:
Y podriamos seguir haciendo esto hasta que tengamos la exactitud que queremos, pero esa no seria una manera muy inteligente de hacerlo (tenemos una maquina a la que le gusta hacer tareas repetitivas y no la aprovechamos?).
En vez de eso, notemos que la formula no cambia absolutamente en nada, por lo que la podemos hacer una funcion y olvidarnos de ella.
Can you write Python code for it?

def biseccion(x1, x2):
    return (x1 + x2)/2.0