<jupyter_start><jupyter_text>*** Names: [Insert Your Names Here]***  Lab 4 - Plotting and Fitting with Hubble's Law<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Exercise 1In the cell below, I have transcribed the data from <NAME>'s original 1928 paper "A relation between distance and radial velocity among extra-galactic nebulae", available [here](https://www.pnas.org/content/pnas/15/3/168.full.pdf).a.  Open the original paper. Use it and your knowledge of Python code to decipher what each line in the next two code cells is doing. Add a comment at the top of each line stating what it is doing and/or where in the paper it came from.   b. Create a scatter plot from Hubble's data. To make a scatterplot in python, you use the same plt.plot function that we used for line graphs last week except after the x and y arguments, you add a string describing the type of plotting symbol that you want. [Here](https://matplotlib.org/3.1.1/api/markers_api.html) is a list of plot symbols. Note that you can combine these with colors so, for example, 'go' is green circles and 'rx' is red xs. Give your plot a title and axis labels to match Hubble's original.  c. Write code that will print each entry in the list obj_list on its own line (you will need this for exercise 2, below).<jupyter_code>NGC_nos = [6822,598,221,224,5457,4736,5194,4449,4214,
        3031,3627,4826,5236,1068,5055,7331,4258,
        4151,4382,4472,4486,4649]
obj_list = ['SMC', 'LMC']
for i in np.arange(len(NGC_nos)):
    obj_list.append('NGC '+str(NGC_nos[i]))
dists = np.array([0.032,0.034,0.214,0.263,0.275,0.275,0.45,0.5,0.5,0.63,0.8,0.9,0.9,
         0.9,0.9,1.0,1.1,1.1,1.4,1.7,2.0,2.0,2.0,2.0])#Mpc
vels = np.array([170.,290,-130,-70,-185,-220,200,290,270,200,300,-30,650,150,500,920,450,500,500,960,500,850,800,1000]) #km/sec
#plot goes here
#loop to print names goes here<jupyter_output><empty_output><jupyter_text>Exercise 2Now, let's pull modern data for Hubble's galaxies. Copy and paste the list from Exercise 1c into the query form [here](http://ned.ipac.caltech.edu/forms/gmd.html). ***Before you click "Submit Query"***, scroll to the check boxes at the bottom of the page and make sure to check ***only*** the following:  *  User Input Object Name  *  Redshift  *  Redshift Uncertainty    And in the bottom right panel:    *  Metric Distance  *  Mean  *  Standard Deviation  *  Number of measurementsOpen the Macintosh application "TextEdit" and copy and paste the table into it. From the Format menu, select "make plain text" and then save it as cat.txt in the same folder as your Lab3 notebook.The code cells below will "read in" the data using a python package called Pandas that we will learn about in great detail in the coming weeks. For now, just execute the cell below, which will create python lists stored in variables with descriptive names from your cat.txt file. a)Describe in words at least two patterns that you note in the tabular data  b) Make a histogram for each of the following quantities: redshift, redshift_uncert, dist, and dist_uncert. All your plots should have axis labels, and for the histograms you should play around with the number of bins until you can justify your choice for this value.  Discuss and compare the shapes of the distributions for each of the quantities in general, qualitative terms.  c) Plot the uncertainty in redshift as a function of redshift for these galaxies and the uncertainty in distance as a function of distance. What patterns do you notice, if any in the relationships between these quantities and their uncertainties?<jupyter_code>import pandas
cols = ['Obj Name', 'Redshift', 'Redshift Uncert', 'Dist Mean (Mpc)', 'Dist Std Dev (Mpc)', 'Num Obs']
df = pandas.read_csv('cat.txt', delimiter ='|', skiprows=3, header = 0, names = cols, skipinitialspace=True)
redshift = df["Redshift"].tolist()
redshift_uncert = df["Redshift Uncert"].tolist()
dists2 = df["Dist Mean (Mpc)"].tolist()
dists2_uncert = df["Dist Std Dev (Mpc)"].tolist()
#display table (python "data frame" object)
df<jupyter_output><empty_output><jupyter_text>***Answer to Part a***<jupyter_code>#plots for part b - redshift
#plots for part b - redshift uncertainty
#plots for part b - distance
#plots for part b - distance uncertainty<jupyter_output><empty_output><jupyter_text>***Part B explanation***<jupyter_code>#part c scatter plot 1
#part c scatter plot 2<jupyter_output><empty_output><jupyter_text>***Part C explanation***      Exercise 3 The conversion between redshift (z) as provided in the database and recessional velocity as provided in Hubble's original paper is given by the formula below. $$z=\sqrt{\frac{1+\beta}{1-\beta}}$$where $\beta$=v/c. This formula can also be written as:$$\beta=\frac{(z+1)^2-1}{(z+1)^2+1}$$(a) Write a function with an appropriate docstring that applies this forumula to an input array. Your function should return an array of velocities in km/sec.  b) Apply your new function to your redshift and redshift uncertainty arrays here to translate them to "recessional velocities", as in Hubble's original plot  \* Note that technically we should do some more complicated error propagation here, and we will discuss this later in this class. Luckily though, this formula is roughly equivalent to z = v/c, which means that errors in z and v can be directly translated.<jupyter_code>#part a here
#part b here<jupyter_output><empty_output><jupyter_text>Exercise 4Make the following plots, with appropriate axis labels and titles. a) A plot of the new data similar to the one you made in exercise 1, only with error bars. Use the function plt.errorbar and inflate the errors in the modern recessional velocities by a factor of 10, because they are actually so small for these very nearby galaxies with today's measurement techniques, that we can't even see them unless we   b) A plot showing both the new and old data overplotted, with different colors for each and a legend.   c) A plot showing Hubble's distances vs. the new distances, with a "    1 to 1" line overplotted  d) A plot showing Hubble's recessional velocities vs. the new velocities, with a "1 to 1" line overplotted  e) Discuss at least two trends that you see in the graphs and make a data-driven argument for how they might explain the discrepancy between the modern values and Hubble's. As always, your explanations need not be lengthy, but they should be ***clear and specific***.<jupyter_code>#Plot a here
#Plot b here
#Plot c here
# Plot d here<jupyter_output><empty_output><jupyter_text>***Part e explanations here*** ***We will do the exercise below in class next week and you should not attempt it now. However, it builds directly on this lab, so take some time with your lab mates to think about how you will approach it, since you will only have one 50min class period in which to answer it.*** In-Class Exercise for Next Week Time for fitting! Use the lecture notes on Model fitting as a guide to help you. a) Fit a linear model to Hubble's data and to the modern data. Make a plot showing both datasets and both fit lines. The plot should include a legend with both the points and the lines. The lines should be labeled in the legend with their equations. b) Now, let's fit a linear model to the modern data that takes the error bars in the recessional velocities into account in the fit. The problem here though is that the uncertainties in redshifts/recessional velocities are VERY small for these galaxies. So small in fact that when you overplot error bars on the data points you can't even see them (you can do this to verify). So to demonstrate differences between weighted and unweighted fits here, let's inflate them by a factor of 50. Overplot both the unweighted and weighted lines together with the modern data (with y error bars) and an appropriate legend. c) Discuss at least one trend or effect that you see in each graph. As always, your explanations need not be lengthy, but they should be ***clear, supported with references to the plot, and specific***. d) We won't do fitting with x and y error bars, but you can easily make a plot that shows errors in both quantities using plt.errorbar. Do this using the TRUE errors in velocity and distance (not the inflated values), and use your plot to make an argument about whether the "Hubble's Law" line is a good fit to the data.<jupyter_code>#import relevant modules here
#define a linear model function here
#calculate the values for your two fits here and print their values (to label lines)
#plot 1 goes here
#weighted fit goes here
#plot with error bars goes here<jupyter_output><empty_output><jupyter_text>***Discuss trends or effects seen here***<jupyter_code>#plot with x AND y errors goes here
from IPython.core.display import HTML
def css_styling():
    styles = open("../../custom.css", "r").read()
    return HTML(styles)
css_styling()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0782385157035878, 'fraction_numerical': 0.02961886665921538, 'mean_word_length': 4.765463917525773, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 38, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '31147', 'license': 'MIT', 'n_tokens_mistral': 2693, 'n_tokens_neox': 2454, 'n_words': 1282, 'path': 'Labs/Lab4/Lab4.ipynb', 'repo_name': 'kfollette/AST200-Spring2020', 'size': '8953'}