I am working on the file "1_Radio_Science/1_6_synchrotron_emission.ipynb".
The first task is:
Figure 1.6.2  Cygnus A: Example of Synchroton Emission
The jets, which carry relativistic charged particles or plasma originating from the centre of the host galaxy (marked as 'core' in the figure), collide with the surrounding medium at the places labelled as "hotspots" in the figure. The plasma responsible for the radio emission (the lobes) tends to stream backward from the hotspots. As a result we can expect the youngest plasma to reside in and around the hotspots. On the other hand, we can expect the plasma closest to the core to be the oldest. But is there a way to verify this?
Well, the non-thermal nature of the emission can be verified by measuring the spectrum of the radio emission. A value close to -0.7 suggests, by the reasoning given above, that the radiation results from a synchroton emission mechanism. The plots below show the spectrum of the lobes of Cygnus A within a frequency range of 150 MHz to 14.65 GHz.
<span style="background-color:cyan"> LB:RF: Add proper citation. </span>
Can you write Python code for it?

# Data taken from Steenbrugge et al.,2010, MNRAS
freq=(151.0,327.5,1345.0,4525.0,8514.9,14650.0)
flux_L=(4746,2752.7,749.8,189.4,83.4,40.5)
flux_H=(115.7,176.4,69.3,45.2,20.8,13.4)
fig,ax = plt.subplots()
ax.loglog(freq,flux_L,'bo--',label='Lobe Flux')
ax.loglog(freq,flux_H,'g*-',label='Hotspot Flux')
ax.legend()
ax.set_xlabel("Frequency (MHz)")
ax.set_ylabel("Flux (Jy)")


I am working on the file "1_Radio_Science/1_6_synchrotron_emission.ipynb".
The first task is:
Import section specific modules:
Can you write Python code for it?

from IPython.display import Image
HTML('../style/code_toggle.html')


I am working on the file "1_Radio_Science/1_8_astronomical_radio_sources.ipynb".
The first task is:
Import section specific modules:
Can you write Python code for it?


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
1.9 A brief introduction to interferometry and its history
1.9.1 The double-slit experiment
The basics of interferometry date back to Thomas Young's double-slit experiment ➞ of 1801. In this experiment, a plate pierced by two parallel slits is illuminated by a monochromatic source of light. Due to the wave-like nature of light, the waves passing through the two slits interfere, resulting in an interference pattern, or fringe, projected onto a screen behind the slits:
<img src="figures/514px-Doubleslit.svg.png" width="50%"/>
Figure 1.9.1: Schematic diagram of Young's double-slit experiment. Credit: Unknown.
The position on the screen $P$ determines the phase difference between the two arriving wavefronts. Waves arriving in phase interfere constructively and produce bright strips in the interference pattern. Waves arriving out of phase interfere destructively and result in dark strips in the pattern.
In this section we'll construct a toy model of a dual-slit experiment. Note that this model is not really physically accurate, it is literally just a "toy" to help us get some intuition for what's going on. A proper description of interfering electromagnetic waves will follow later.
Firstly, a monochromatic electromagnetic wave of wavelength $\lambda$ can be described by at each point in time and space as a complex quantity i.e. having an amplitude and a phase, $A\mathrm{e}^{\imath\phi}$. For simplicity, let us assume a constant amplitude $A$ but allow the phase to vary as a function of time and position.
Now if the same wave travels along two paths of different lengths and recombines at point $P$, the resulting electric field is a sum:
$E=E_1+E_2 = A\mathrm{e}^{\imath\phi}+A\mathrm{e}^{\imath(\phi-\phi_0)},$
where the phase delay $\phi_0$ corresponds to the pathlength difference $\tau_0$:
$\phi_0 = 2\pi\tau_0/\lambda.$
What is actually "measured" on the screen, the brightness, is, physically, a time-averaged electric field intensity $EE^$, where the $^$ represents complex conjugation (this is exactly what...
Can you write Python code for it?

def double_slit (p0=[0],a0=[1],baseline=1,d1=5,d2=5,wavelength=.1,maxint=None):
    """Renders a toy dual-slit experiment.
    'p0' is a list or array of source positions (drawn along the vertical axis)
    'a0' is an array of source intensities
    'baseline' is the distance between the slits
    'd1' and 'd2' are distances between source and plate and plate and screen
    'wavelength' is wavelength
    'maxint' is the maximum intensity scale use to render the fringe pattern. If None, the pattern
       is auto-scaled. Maxint is useful if you want to render fringes from multiple invocations
       of double_slit() into the same intensity scale, i.e. for comparison.
    """
    ## setup figure and axes
    plt.figure(figsize=(20, 5))
    plt.axes(frameon=False)
    plt.xlim(-d1-.1, d2+2) and plt.ylim(-1, 1)
    plt.xticks([]) and plt.yticks([])
    plt.axhline(0, ls=':')
    baseline /= 2.
    ## draw representation of slits
    plt.arrow(0, 1,0, baseline-1, lw=0, width=.1, head_width=.1, length_includes_head=True)
    plt.arrow(0,-1,0, 1-baseline, lw=0, width=.1, head_width=.1, length_includes_head=True)
    plt.arrow(0, 0,0,  baseline,  lw=0, width=.1, head_width=.1, length_includes_head=True)
    plt.arrow(0, 0,0, -baseline,  lw=0, width=.1, head_width=.1, length_includes_head=True)
    ## draw representation of lightpath from slits to centre of screen
    plt.arrow(0, baseline,d2,-baseline, length_includes_head=True)
    plt.arrow(0,-baseline,d2, baseline, length_includes_head=True)
    ## draw representation of sinewave from the central position
    xw = np.arange(-d1, -d1+(d1+d2)/4, .01)
    yw = np.sin(2*np.pi*xw/wavelength)*.1 + (p0[0]+p0[-1])/2
    plt.plot(xw,yw,'b')
    ## 'xs' is a vector of x cordinates on the screen
    ## and we accumulate the interference pattern for each source into 'pattern'
    xs = np.arange(-1, 1, .01)
    pattern = 0
    total_intensity = 0
    ## compute contribution to pattern from each source position p
    for p,a in np.broadcast(p0,a0):
        plt.plot(-d1, p,...


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
1.9.4 From the double-slit box to an interferometer
The original double-slit experiment was conceived as a demonstration of the wave-like nature of light. The role of the light source in the experiment was simply to illuminate the slits. Let us now turn it around and ask ourselves, given a working dual-slit setup, could we use it to obatin some information about the light source? Could we use the double-slit experiment as a measurement device, i.e. an interferometer?
1.9.4.1 Measuring source position
Obviously, we could measure source intensity -- but that's not very interesting, since we can measure that by looking at the source directly. Less obviously, we could measure the source position. Observe what happens when we move the source around, and repeat this experiment for longer and shorter baselines:
Can you write Python code for it?

interact(lambda position,baseline,wavelength:double_slit(p0=[position],baseline=baseline,wavelength=wavelength),
               position=(-1,1,.01),baseline=(0.1,2,.01),wavelength=(.05,.2,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
A.1 The Betelgeuse size measurement
For fun, let us use our toy to re-create the Betelgeuse size measurement of 1920 by A.A. Michelson and F.G. Pease. Their experiment was set up as follows. The interferometer they constructed had movable outside mirrors, giving it a baseline that could be adjusted from a maximum of 6m downwards. Red light has a wavelength of ~650n; this gave them a maximum baseline of 10 million wavelengths.
For the experiment, they started with a baseline of 1m (1.5 million wavelengths), and verified that they could see fringes from Betelguese with the naked eye. They then adjusted the baseline up in small increments, until at 3m the fringes disappeared. From this, they inferred the diameter of Betelgeuse to be about 0.05".
You can repeat the experiment using the sliders below. You will probably find your toy Betelegeuse to be somewhat larger than 0.05". This is because our simulator is too simplistic -- in particular, it assumes a monochromatic source of light, which makes the fringes a lot sharper.
Can you write Python code for it?

arcsec = 1/3600.
interact(lambda extent_arcsec, baseline:
             michelson(p0=[0], a0=[1], extent=extent_arcsec*arcsec, maxint=1,
                       baseline=baseline,fov=1*arcsec),
         extent_arcsec=(0,0.1,0.001),
         baseline=(1e+4,1e+7,1e+4)
        ) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
And here's the same experiment for two sources:
Can you write Python code for it?

interact(lambda position1,position2,intensity1,intensity2,baseline:
            michelson(p0=[position1,position2], a0=[intensity1,intensity2], baseline=baseline, maxint=2),
         position1=(-5,5,.01), position2=(-5,5,.01), intensity1=(.2,1,.01), intensity2=(.2,1,.01),
         baseline=(10,100,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
However, as soon as we take a measurement on another baseline, the difference becomes apparent:
Can you write Python code for it?


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
Import section specific modules:
Can you write Python code for it?

from IPython.display import display
from ipywidgets import interact

HTML('../style/code_toggle.html')


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
In fact historically, this was the first application of interferometry in astronomy. In a famous experiment in 1920, a Michelson interferometer installed at Mount Wilson Observatory was used to measure the diameter of the red giant star Betelgeuse.

The historical origins of the term visibility, which you will become intimately familiar with in the course of these lectures, actually lie in the experiment described above. Originally, "visibility" was defined as just that, i.e. a measure of the contrast between the light and dark stripes of the interference pattern.

Modern interferometers deal in terms of complex visibilities, i.e. complex quantitities. The amplitude of a complex visibility, or visibility amplitude, corresponds to the intensity of the interference pattern, while the visibility phase corresponds to its relative phase (in our simulator, this is the phase of the fringe at the centre of the screen). This one complex number is all the information we have about the light source. Note that while our double-slit experiment shows an entire pattern, the variation in that pattern across the screen is entirely due to the geometry of the "box" (generically, this is the instrument used to make the measurement) -- the informational content, as far as the light source is concerned, is just the amplitude and the phase!

In the single-source simulations above, you can clearly see that amplitude encodes source shape (and intensity), while phase encodes source position. Visibility phase measures position, amplitude measures shape and intensity. This is a recurring theme in radio interferometry, one that we'll revisit again and again in subsequent lectures.

Note that a size measurement is a lot simpler than a position measurement. The phase of the fringe pattern gives us a very precise measurement of the position of the source relative to the optical axis of the instrument. To...
Can you write Python code for it?

interact(lambda d1,d2,position,extent: double_slit(p0=np.arange(position-extent,position+extent+.01,.01),d1=d1,d2=d2),
         d1=(1,5,.1),d2=(1,5,.1),
         position=(-1,1,.01),extent=(0,1,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
Modern interferometers exploit this by using an array of elements, which provides a whole range of possible baselines.
1.9.4.2 Measuring source size
Perhaps less obviously, we can use an inteferometer to measure source size. Until now we have been simulating only point-like sources. First, consider what happens when we add a second source to the experiment (fortunately, we wrote the function above to accommodate such a scenario). The interference pattern from two (independent) sources is the sum of the individual interference patterns. This seems obvious, but will be shown more formally later on. Here we add a second source, with a slider to control its position and intensity. Try to move the second source around, and observe how the superimposed interference pattern can become attenuated or even cancel out.
Can you write Python code for it?

interact(lambda position,intensity,baseline,wavelength:
            double_slit(p0=[0,position],a0=[1,intensity],baseline=baseline,wavelength=wavelength),
         position=(-1,1,.01),intensity=(.2,1,.01),baseline=(0.1,2,.01),wavelength=(.01,.2,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
Note that long baselines are very sensitive to change in source position, while short baselines are less sensitive. As we'll learn in Chapter 4, the spatial resolution (i.e. the distance at which we can distinguish sources) of an interfrometer is given by $\lambda/B$ , while the spatial resolution of a conventional telescope is given by $\lambda/D$, where $D$ is the dish (or mirror) aperture. This is a fortunate fact, as in practice it is much cheaper to build long baselines than large apertures!
On the other hand, due to the periodic nature of the interference pattern, the position measurement of a long baseline is ambiguous. Consider that two sources at completely different positions produce the same interference pattern:
Can you write Python code for it?


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
Now, let us simulate an extended source, by giving the simulator an array of closely spaced point-like sources. Try playing with the extent slider. What's happening here is that the many interference patterns generated by each little part of the extended source tend to "wash out" each other, resulting in a net loss of amplitude in the pattern. Note also how each particular baseline length is sensitive to a particular range of source sizes.
Can you write Python code for it?

interact(lambda extent,baseline,wavelength:
             double_slit(p0=np.arange(-extent,extent+.01,.01),baseline=baseline,wavelength=wavelength),
         extent=(0,1,.01),baseline=(0.1,2,.01),wavelength=(.01,.2,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
On the other hand, using a shorter baseline resolves the ambiguity:
Can you write Python code for it?


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
This function draws a double-slit setup, with a light source at position $p$ (in fact the function can render multiple sources, but we'll only use it for one source for the moment). The dotted blue line shows the optical axis ($p=0$). The sine wave (schematically) shows the wavelength. (Note that the units here are arbitrary, since it is only geometry relative to wavelength that determines the results). The black lines show the path of the light waves through the slits and onto the screen at the right. The strip on the right schematically renders the resulting interference pattern, and the red curve shows a cross-section through the pattern.
Inside the function, we simply compute the pathlength difference along the two paths, convert it to phase delay, and render the corresponding interference pattern.

Warning: Once again, let us stress that this is just a "toy" rendering of an interferometer. It serves to demonstrate the basic principles, but it is not physically accurate. In particular, it does not properly model diffraction or propagation. Also, since astronomical sources are effectively infinitely distant (compared to the size of the interferometer), the incoming light rays should be parallel (or equivalently, the incoming wavefront should be planar, as in the first illustration in this chapter).

1.9.3 Playing with the baseline
First of all, note how the properties of the interference pattern vary with baseline $B$ (the distance between the slits) and wavelength $\lambda$. Use the sliders below to adjust both. Note how increasing the baseline increases the frequency of the fringe, as does reducing the wavelength.
Can you write Python code for it?

interact(lambda baseline,wavelength:double_slit(p0=[0],baseline=baseline,wavelength=wavelength),
                baseline=(0.1,2,.01),wavelength=(.05,.2,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
This simple fact has led to many other applications for interferometers, from geodetic VLBI (where continental drift is measured by measuring extremely accurate antenna positions via radio interferometry of known radio sources), to the recent gravitational wave detection by LIGO (where the light source is a laser, and the interference pattern is used to measure miniscule distortions in space-time -- and thus the geometry of the interferometer -- caused by gravitational waves).
1.9.5 Practical interferometers
If you were given the job of constructing an interferometer for astronomical measurements, you would quickly find that the double-slit experiment does not translate into a very practical design. The baseline needs to be quite large; a box with slits and a screen is physically unwieldy. A more viable design can be obtained by playing with the optical path.
The basic design still used in optical interferometry to this day is the Michelson stellar interferometer mentioned above. This is schematically laid out as follows:

Figure 1.9.2: Schematic of a Michelson interferometer. Credit: Unknown.
The outer set of mirrors plays the role of slits, and provides a baseline of length $d$, while the rest of the optical path serves to bring the two wavefronts together onto a common screen. The first such interferometer, used to carry out the Betelgeuse size measurement, looked like this:

Figure 1.9.3: 100-inch Hooker Telescope at Mount Wilson Observatory in southern California, USA. Credit: Unknown.
In modern optical interferometers using the Michelson layout, the role of the "outer" mirrors is played by optical telescopes in their own right. For example, the Very Large Telescope operated by ESO can operate as an inteferometer, combining four 8.2m and four 1.8m individual telescopes:

Figure 1.9.4: The Very Large Telescope...
Can you write Python code for it?


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
We can therefore measure source size by measuring the reduction in the amplitude of the interference pattern:
Can you write Python code for it?


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
We have modified the setup as follows. First, the source is now infinitely distant, so we define the source position in terms of the angle of arrival of the incoming wavefront (with 0 meaning on-axis, i.e. along the vertical axis). We now define the baseline in terms of wavelengths. The phase difference of the wavefront arriving at the two arms of the interferometer is completely defined in terms of the angle of arrival. The two "rays" entering the outer arms of the interferometer indicate the angle of arrival.
The rest of the optical path consists of a series of mirrors to bring the two signals together. Note that the frequency of the fringe pattern is now completely determined by the internal geometry of the instrument (i.e. the distances between the inner set of mirrors and the screen); however the relative phase of the pattern is determined by source angle. Use the sliders below to get a feel for this.
Note that we've also modified the function to print the "visibility", as originally defined by Michelson.
Can you write Python code for it?

# single source
interact(lambda position, intensity, baseline:
             michelson(p0=[position], a0=[intensity], baseline=baseline, maxint=2),
         position=(-5,5,.01),intensity=(.2,1,.01),baseline=(10,100,.01)) and None


I am working on the file "1_Radio_Science/1_9_a_brief_introduction_to_interferometry.ipynb".
The first task is:
With a larger number of baselines, we can gather enough information to reconstruct an image of the sky. This is because each baseline essentially measures one Fourier component of the sky brightness distribution (Chapter 4 will explain this in more detail); and once we know the Fourier components, we can compute a Fourier transform in order to recover the sky image. The advent of sufficiently powerful computers in the late 1960s made this technique practical, and turned radio interferometers from exotic contraptions into generic imaging instruments. With a few notable exceptions, modern radio interferometry is aperture synthesis.
This concludes our introduction to radio interferometry; the rest of this course deals with aperture synthesis in detail. The remainder of this notebook consists of a few more interactive widgets that you can use to play with the toy dual-slit simulator.
Appendix: Recreating the Michelson interferometer
For completeness, let us modify the function above to make a more realistic interferometer. We'll implement two changes:

we'll put the light source infinitely far away, as an astronomical source should be

we'll change the light path to mimic the layout of a Michelson interferometer.
Can you write Python code for it?

def michelson (p0=[0],a0=[1],baseline=50,maxbaseline=100,extent=0,d1=9,d2=1,d3=.2,wavelength=.1,fov=5,maxint=None):
    """Renders a toy Michelson interferometer with an infinitely distant (astronomical) source
    'p0' is a list or array of source positions (as angles, in degrees).
    'a0' is an array of source intensities
    'extent' are source extents, in degrees
    'baseline' is the baseline, in lambdas
    'maxbaseline' is the max baseline to which the plot is scaled
    'd1' is the plotted distance between the "sky" and the interferometer arms
    'd2' is the plotted distance between arms and screen, in plot units
    'd3' is the plotted distance between inner mirrors, in plot units
    'fov' is the notionally rendered field of view radius (in degrees)
    'wavelength' is wavelength, used for scale
    'maxint' is the maximum intensity scale use to render the fringe pattern. If None, the pattern
       is auto-scaled. Maxint is useful if you want to render fringes from multiple invocations
       of michelson() into the same intensity scale, i.e. for comparison.
    """
    ## setup figure and axes
    plt.figure(figsize=(20, 5))
    plt.axes(frameon=False)
    plt.xlim(-d1-.1, d2+2) and plt.ylim(-1, 1)
    plt.xticks([])
    # label Y axis with degrees
    yt,ytlab = plt.yticks()
    plt.yticks(yt,["-%g"%(float(y)*fov) for y in yt])
    plt.ylabel("Angle of Arrival (degrees)")
    plt.axhline(0, ls=':')
    ## draw representation of arms and light path
    maxbaseline = max(maxbaseline,baseline)
    bl2 = baseline/float(maxbaseline)    # coordinate of half a baseline, in plot units
    plt.plot([0,0],[-bl2,bl2], 'o', ms=10)
    plt.plot([0,d2/2.,d2/2.,d2],[-bl2,-bl2,-d3/2.,0],'-k')
    plt.plot([0,d2/2.,d2/2.,d2],[ bl2, bl2, d3/2.,0],'-k')
    plt.text(0,0,'$b=%d\lambda$'%baseline, ha='right', va='bottom', size='xx-large')
    ## draw representation of sinewave from the central position
    if isinstance(p0,(int,float)):
        p0 = [p0]
    xw = np.arange(-d1, -d1+(d1+d2)/4, .01)
    yw =...


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Advanced Search with sharepa
You can make your own search object, which allows you to pass in custom queries for certain terms or SHARE fields. Queries are formed using lucene query syntax, just like we used in the above examples.
This type of query accepts an exists field. Other options include a query_string, a match query, a multi-match query, a bool query, and any other query structure available in the elasticsearch API.
We can see what that query that we're about to send to elasticsearch by using the pretty print helper function. You'll see that it looks very similar to the queries we defined by hand earlier.
Can you write Python code for it?

# Sharepa is a python client for  browsing and analyzing SHARE data specifically using elasticsearch querying.
    # We can use this to aggregate, graph, and analyze the data.
    # Helpful Links:
        # https://github.com/CenterForOpenScience/sharepa
        # https://pypi.python.org/pypi/sharepa
    # here, we import the specific function from Sharepa called ShareSearch and pretty_print
from sharepa import ShareSearch
from sharepa.helpers import pretty_print

#we just created a local name for ShareSearch function for us to use
my_search = ShareSearch()

# Lucene supports fielded data. When performing a search you can either specify a field, or use the default field.
my_search = my_search.query(
    'exists', # Type of query, will accept a lucene query string
    field='tags', # This lucene query string will find all documents that don't have tags
)

# this prints out (prettily!) our search, transformed into a dictionary data type
    # read more about dictionaries here: http://learnpythonthehardway.org/book/ex39.html
pretty_print(my_search.to_dict())


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Complex Queries
The SHARE Search API runs on elasticsearch - meaning that it can accept complicated queries that give you a wide variety of information.
Here are some examples of how to make more complex queries using the raw elasticsearch results. You can read a lot more about elasticsearch queries here.
Can you write Python code for it?

# reset the args so that we remove our old query arguments.
search_url.args = None

# Show the URL that we'll be requesting to make sure the args were cleared
search_url.url


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Debugging and Problem Solving
Not everything always goes as planned when querying an unfamillar API. Here are some debugging and problem solving strategies when you're querying the SHARE API.
Schema issues
The SHARE schema has a lot of parts, and much of the information is nested within sections. Making a query isn't always as straight forward as you might think, if you're not looking in the right part of the schema.
Let's say you were trying to query for all SHARE documents that specify the language as not being in English.
We'll guess as to what that query might be, and try to make it using sharepa.
Can you write Python code for it?

# this creates a new search for us to use!
language_search = ShareSearch()

# this sets the search query we are using for our new search! all the items that aren't in english
language_search = language_search.query(
    'query_string', # Type of query, will accept a lucene query string
    query='NOT languages=english', # This lucene query string will find all documents that don't have tags
)

# this allows us to search through 10 results and find the languages of each
results = language_search.execute()

# for each item in results, print out the language it is in
for hit in results:
    print(hit.languages)


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Iterating Through Results
Executing the basic search will send the actual basic query to the SHARE API and then let you iterate through results, 10 at a time.
Can you write Python code for it?

# this captures 10 items in the SHARE dataset -- that's what the basic search function is for
results = basic_search.execute()

# this prints out the 10 items we added to the list variable, results (above)
for hit in results:
    print(hit.title)


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Let's combine the two and find documents from CrossRef that mention giraffes
Can you write Python code for it?

# we are reusing that variable search_url from the cell above! We are querying (see that arg again) for entries
    # that use the keyword "giraffes" from the source provider CrossRef
search_url.args['q'] = 'sources:providers.org.crossref AND giraffes'

# We are requsting the information from the search_url and parsing the JSON that we requested and got back
    # (requests.get!) like we did in cell 2. We put it into this list variable
recent_results = requests.get(search_url.url).json()

# This is called a 2 dimensional array -- a list that looks kind of like a matrix. A list can store other lists.
    # This is a way to create two-dimensional (2D) lists in Python -- 2Dlist=[hi,my,name,is,erin][but,my,name,is,vicky]. We can print out 2Dlist[1][4] and we would see "my Vicky" because we start counting at 0 instead of 1
recent_results = recent_results['hits']['hits']

# We are printing out on the screen the variable search_url
print('The request URL is {}'.format(search_url.url))

# This is just so we have a nice visual queue between the url that we searched and the actual data we are grabbing
print('---------')

# Another for loop! For all of the items in the results we just grabbed, we are printing out the entries that are
    # from CrossRef that are about giraffes
for result in recent_results:
    print(
        '{} -- from {}'.format(
            result['_source']['title'],
            result['_source']['sources']
        )
    )


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Let's search for documents from the source CrossRef
Can you write Python code for it?

# we are reusing that variable search_url from the cell above! We are querying (see that arg again) for everything
    # from the source provide CrossRef
search_url.args['q'] = 'sources:providers.org.crossref'

# We are requsting the information from the search_url and parsing the JSON that we requested and got back
    # (requests.get!) like we did in cell 2. We put it into this list variable
recent_results = requests.get(search_url.url).json()

# This is called a 2 dimensional array -- a list that looks kind of like a matrix. A list can store other lists.
    # This is a way to create two-dimensional (2D) lists in Python --
    # Example: 2Dlist=[hi,my,name,is,erin][but,my,name,is,vicky]. We can print out 2Dlist[1][4]
    # and we would see "my Vicky" because we start counting at 0 instead of 1 (computer science quirk)
recent_results = recent_results['hits']['hits']

# We are printing out on the screen the variable search_url
print('The request URL is {}'.format(search_url.url))

# This is just so we have a nice visual queue between the url that we searched and the actual data we are grabbing
print('---------')

# Another for loop! For all of the items in the results we just grabbed, we are printing out the entries that are
    # from CrossRef
for result in recent_results:
    print(
        '{} -- from {}'.format(
            result['_source']['title'],
            result['_source']['sources']
        )
    )


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Now let's limit that query to only documents mentioning "giraffes" somewhere in the title, description, or in any of the metadata. We'd do that by adding a query search term.
Can you write Python code for it?

# we are reusing that variable search_url from the cell above! We are querying (hence the args['q']) the API to try
    # and get items that have the word 'giraffes' in them
search_url.args['q'] = 'giraffes'

# We are requsting the information from the search_url and parsing the JSON that we requested and got back
    # (requests.get!) like we did in cell 2. We put it into this list variable
recent_results = requests.get(search_url.url).json()

# This is called a 2 dimensional array -- a list that looks kind of like a matrix. A list can store other lists.
    # This is a way to create two-dimensional (2D) lists in Python --
    # Exmaple: 2Dlist=[hi,my,name,is,erin][but,my,name,is,vicky]. We can print out 2Dlist[1][4] and we would see
    # "my Vicky" because we start counting lists at 0 instead of 1 (computer science quirk)
recent_results = recent_results['hits']['hits']

# We are printing out on the screen the variable search_url
print('The request URL is {}'.format(search_url.url))

# This is just so we have a nice visual queue between the url that we searched and the actual data we are grabbing
print('---------')

# Another for loop! For all of the items in the results we just grabbed, we are printing out the entries that have
    # the keyword 'giraffes'
for result in recent_results:
    print(
        '{} -- from {}'.format(
            result['_source']['title'],
            result['_source']['sources']
        )
    )


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Query Setup
We can define a few functions that we can reuse to make querying simpler. Elasticsearch queries are passed through as json blobs specifying how to return the information you want.
Can you write Python code for it?

#just like the json library from cell 2
import json

#this is called a function -- we DEFINE it (def) and name it something useful for us. It makes it easy for us to
    #reuse this later on by just calling the function by typng it's name, and adding the appropriate values in the
    #parentheses (called arguments). To learn more about functions:
        #http://www.tutorialspoint.com/python/python_functions.htm
        #http://docs.python-guide.org/en/latest/writing/style/?highlight=function

# This is a helper function that will use the requests library, pass along the correct headers, and make the query
    # we want
def query_share(url, query):
    headers = {'Content-Type': 'application/json'}
    data = json.dumps(query)
    return requests.post(url, headers=headers, data=data).json()


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
SHARE Schema
You can make queries against any of the fields defined in the SHARE Schema. If we were able to harvest the information from the original source, it should appear in SHARE. However, not all fields are required for every document.
Required fields include:
- title
- contributors
- uris
- providerUpdatedDateTime
We add some information after each document is harvested inside the field shareProperties, including:
- source (where the document was originally harvested)
- docID  (a unique identifier for that object from that source)
These two fields can be combined to make a unique document identifier.
Simple Queries
Let's get the first 3 results from the most basic query - the first page of the most recently updated research release events in SHARE.
We'll use the URL parsing library furl to keep track of all of our arguments to the URL, because we'll be modifying them as we go along. We'll print the URL as we go to take a look at it, so we know what we're requesting.
We'll print out the result's title and sources where it appears.
Can you write Python code for it?

# furl is a Python library that allows you to easily manipulate URLs. https://github.com/gruns/furl
import furl

# In cell 1, we put the URL for the SHARE API into the variable SHARE_API. We can use it even down here!
    # We are parsing it using furl and putting it into a new variable called search_url
search_url = furl.furl(SHARE_API)

# We are limiting the arguments that we can attach to the URL to 3 -- so we grab the first 3 entries from the API
search_url.args['size'] = 3

# We are requsting the information from the search_url and parsing the JSON that we requested and got back
    # (requests.get!) like we did in cell 2. We put it into this list variable
recent_results = requests.get(search_url.url).json()

# This is called a 2 dimensional array -- a list that looks kind of like a matrix. A list can store other lists.
    # This is a way to create two-dimensional (2D) lists in Python -- 2Dlist=[hi,my,name,is,erin][but,my,name,is,vicky]. We can print out 2Dlist[1][4] and we would see "my Vicky" because we start counting at 0 instead of 1
recent_results = recent_results['hits']['hits']

# we need to do this to initialize/define the list -- look at this for more information:
    # http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python
recent_results

#We are printing out on the screen the variable search_url
print('The request URL is {}'.format(search_url.url))

#This is just so we have a nice visual queue between the url that we searched and the actual data we are grabbing
print('----------')

#Another for loop! For all of the items in the results we just grabbed, we are printing out the variables
    # called source and title
for result in recent_results:
    print(
        '{} -- from {}'.format(
            result['_source']['title'],
            result['_source']['sources']
        )
    )


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
So now we're better equipped to add on to this filter, and then narrow down to results that are not in English.
When we printed out the first few results, we might have noticed a second problem with our query -- going back to the SHARE Schema, we might notice that there is a restriction on how languages are captured - as a three letter lowercase representation. Instead of "english" let's look for the three letter abbreviation - "eng"
We can modify our new and improved language query by adding on another query to our started language_search. We'll use the elasticsearch query object Q, and invert it with a ~ symbol, and search for the term "eng."
Can you write Python code for it?

# Elasticsearch DSL is a high-level library whose aim is to help with writing and running queries against Elasticsearch.
    # Read more about elasticsearch here:
        # http://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html
        # https://pypi.python.org/pypi/elasticsearch-dsl
        # https://github.com/elastic/elasticsearch-dsl-py
    # this imports the function Q from the library
from elasticsearch_dsl import Q

# sets up a new search -- for results that have english ('eng') in their language field
language_search = language_search.query(~Q("term", language="eng"))

# execute our search and throw it into a new list
results = language_search.execute()

# Let's see how many documents have language results that aren't eng
print('There are {} documents that do not have "eng" listed.'.format(language_search.count()))

print('Here are the languages for the first 10 results:')

# Check out the first few results, make sure "eng" isn't in there
for hit in results:
    print(hit.language)
    print(hit.title)


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
So the result does not have an attribute called languages! Let's try to figure out what went wrong here.
Step one could be that we are trying to find something that does NOT match a given parameter. Since languages is not required, this is returning results that do not include the languages result at all!
So let's fix this up a bit to make sure that we're querying for items that specify language in the first place.
Can you write Python code for it?

# let's try that again! creating a new search from the ShareSearch() function
language_search = ShareSearch()

# this sets up our new query: if the field called 'language' exists, grab those results
language_search = language_search.filter(
    'exists',
    field="language"
)

# count the number of entries that have a language field
language_search.count()

# grab the results of the search for a language field!
results = language_search.execute()

# Let's see how many documents have language results.
print('There are {} documents with languages specified'.format(language_search.count()))

print('Here are the languages for the first 10 results:')

# for each item in results, print out the language it is in
for hit in results:
    print(hit.language)


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Some Queries
The SHARE schema has many spots for information, and many of the original sources do not provide this information. We can do a query to find out if a certain field exists or not within certain records. The SHARE API is set up to show an empty list if the field is empty.
Let's query for the counts of documents that have a content in their tags field.
Can you write Python code for it?

# we are making another list of all the items with tags
tags_query = {
    "query": {
        "exists": {
            "field": "tags"
        }
    }
}

# we are making another list of all the items without tags
missing_tags_query = {
    "query": {
        "bool": {
            "must_not": {
                "exists": {
                    "field": "tags"
                }
            }
        }
    }
}

# we are making a list of the results from searching items with tags
with_tags = query_share(search_url.url, tags_query)

# we are making a list of the results from searching items without tags
missing_tags = query_share(search_url.url, missing_tags_query)

#Gets the total number of hits from each search
total_results = requests.get(search_url.url).json()['hits']['total']

# getting the percentages of hits with and without tags, respectively, using the built-in float function, which
    # returns a float number (written with a decimal point dividing the integer and fractional parts.)
    # read more about float function: https://docs.python.org/3/library/functions.html#float
with_tags_percent = (float(with_tags['hits']['total'])/total_results)*100
missing_tags_percent = (float(missing_tags['hits']['total'])/total_results)*100

# this simply prints out the list of results that have tags by iterating over the list we already made "with_tags"
    # it then prints out the percentage of total
print(
    '{} results out of {}, or {}%, have tags.'.format(
        with_tags['hits']['total'],
        total_results,
        format(with_tags_percent, '.2f')
    )
)

# this simply prints out the list of results without tags by iterating over the list we already made "missing_tags"
    # it then prints out the percentage of tota
print(
    '{} results out of {}, or {}%, do NOT have tags.'.format(
        missing_tags['hits']['total'],
        total_results,
        format(missing_tags_percent, '.2f')
    )
)

# Visual cue, printing the percentage of results with tags + percent with no tags (we make sure it...


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
The SHARE Search Schema
The SHARE search API is built on a tool called elasticsearch. It lets you search a subset of SHARE's normalized metadata in a simple format.
Here are the fields available in SHARE's elasticsearch endpoint:
- 'title'
- 'language'
- 'subject'
- 'description'
- 'date'
- 'date_created'
- 'date_modified
- 'date_updated'
- 'date_published'
- 'tags'
- 'links'
- 'awards'
- 'venues'
- 'sources'
- 'contributors'

You can see a formatted version of the base results from the API by visiting the SHARE Search API URL.
Service Names for Reference

Each provider harvested from has a specific . Let's make an API call to generate a table to get all of those "internal" names, along with the official name of the repository that they represent.
The SHARE API has different endpoints. One of those endpoints returns a list of all of the providers that SHARE is harvesting from, along with their internal names, official names, links to their homepages, and a simple version of an icon representing their service, in a parsable format called json.
Let's make a call to that API endpoint using the requests libarary, get the json data, and print out all of the shortnames and longnames.
Can you write Python code for it?

# Requests library allows you to send organic, grass-fed HTTP/1.1 requests, no need to manually add query strings
    # to your URLs, or to form-encode your POST data. Docs: http://docs.python-requests.org/en/master/
import requests

# Json library parses JSON from strings or files. The library parses JSON into a Python dictionary or list.
    # It can also convert Python dictionaries or lists into JSON strings.
    # https://docs.python.org/2.7/library/json.html
import json

# This takes the URL and puts it into a variable (so we only need to ever reference this variable,
    # and so we don't have to repeat adding this URL when we want to work with the data)
SHARE_PROVIDERS = 'https://staging-share.osf.io/api/providers/'

# this requests the data from the SHARE_PROVIDERS and uses the json library to parse it into this list variable
data = requests.get(SHARE_PROVIDERS).json()

# literally prints out the sentence in the quotes on the screen
print('Here are the first 10 Providers:')

# this is a for loop (https://wiki.python.org/moin/ForLoop) to repeat the same tasks for each of the items in the
    # list of our SHARE providers (what we put into the variable "data").
# for every item (called 'source' below) in the list, we print out the title, website, and provider name,
    # formatted so each is on a new line (\n)
for source in data['results']:
    print(
        '{}\n{}\n{}\n'.format(
            source['long_title'],
            source['home_page'],
            source['provider_name']
        )
    )


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
Using SHAREPA for SHARE Parsing and Analysis
While you can always pass raw elasticsearch queries to the SHARE API, there is also a pip-installable python library that you can use that makes elasticsearch aggregations a little simpler. This library is called sharepa - short for SHARE Parsing and Analysis
Basic Actions
A basic search will provide access to all documents in SHARE in 10 document slices.
Count
You can use sharepa and the basic search to get the total number of documents in SHARE
Can you write Python code for it?

# Sharepa is a python client for  browsing and analyzing SHARE data specifically using elasticsearch querying.
    # We can use this to aggregate, graph, and analyze the data.
    # Helpful Links:
        # https://github.com/CenterForOpenScience/sharepa
        # https://pypi.python.org/pypi/sharepa
    # here, we import the specific function from Sharepa called basic_search
from sharepa import basic_search

# this performs a basic search over the SHARE dataset and returns a count of the items in it
basic_search.count()


I am working on the file "1_SHARE_API_Basics_py3.ipynb".
The first task is:
When you execute that query, you can then iterate through the results the same way that you could with the simple search query.
Can you write Python code for it?

# we are taking the my_search variable from the cell above and executing the search, placing the results into a
    # new list called new_results
new_results = my_search.execute()

# this for loop prints out the tags for each item in the results we gathered
for hit in new_results:
    print(hit.tags)


I am working on the file "1_Scraping/Collector.ipynb".
The first task is:
An updated csv example :
Can you write Python code for it?

df = pd.read_csv('BBCThai.csv', encoding = 'utf_8_sig')
df.head(5)


I am working on the file "1_Scraping/Collector.ipynb".
The first task is:
Then, run this code hourly to update all of the csv files :
Can you write Python code for it?

print(str(datetime.datetime.now()))
for page in pages :
    appending(page, token, lim)
print(str(datetime.datetime.now()))


I am working on the file "1_Scraping_Google_News_Indonesia.ipynb".
The first task is:
Masih terdapat beberapa link yang redudant, maka kita harus menghilangkan menjadi unique
Can you write Python code for it?

links_unique = list(set(links))

pprint(links_unique[:10])


I am working on the file "1_Scraping_Google_News_Indonesia.ipynb".
The first task is:
Menyimpan Hasil
Can you write Python code for it?

f = open('list_links_google_news_indonesia.txt','w')

f.write(str(links_unique))
f.close()


I am working on the file "1_SelectFiles.ipynb".
The first task is:
Now load the phenotype file and check to see the filenames match the selected ones and have the SUB_IN_SMP set to 1
Can you write Python code for it?

import pandas as pd
# read in csv
df_phen = pd.read_csv('./data/Phenotypic_V1_0b_preprocessed1_filt.csv')
# add a column that matches the filename
for i in df_phen:
    df_phen['filename_1D'] = df_phen['FILE_ID']+"_rois_cc400.1D"
    df_phen['filename_npy'] = df_phen['FILE_ID']+"_rois_cc400.1D.npy"

df_phen['selected'] = np.where(df_phen['filename_1D'].isin((selected_full_path)), 1, 0 )

df_phen = df_phen.loc[df_phen["SUB_IN_SMP"] == 1]
df_phen = df_phen.loc[df_phen["selected"] == 1]

df_phen.to_csv('./data/SelectedSubjects.csv')

"There are " + str(len(df_phen.index)) + " in the final selection."


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(a) $2x^3 - 6x - 1 = 0$
Can you write Python code for it?

f = lambda x : 2 * np.power(x, 3) - 6 * x - 1
xpts = np.linspace(-2, 2, 41)
ypts = f(xpts)

myplot(xpts, ypts, '$f(x) = 2x^3 - 6x - 1$')
print('root = {:>+.6f}'.format(scipy.optimize.bisect(f, -2, -1)))
print('root = {:>+.6f}'.format(scipy.optimize.bisect(f, -0.5, 0)))
print('root = {:>+.6f}'.format(scipy.optimize.bisect(f, 1.5, 2)))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(a) Use (1.21) to approximate the root near 3 of $f(x) = (1 + \epsilon)x^3 - 3x^2 + x - 3$ for a constant $\epsilon$.
Can you write Python code for it?

epsilon = 1e-6
f = lambda x : np.power(x, 3) - 3 * np.power(x, 2) + x - 3
df = lambda x : 3 * np.power(x, 2) - 6 * x + 1
g = lambda x : np.power(x, 3)
f_eps = lambda x, epsilon : f(x) + g(x) * epsilon
root = scipy.optimize.fsolve(lambda x : f_eps(x, epsilon), 3)
droot = -epsilon * g(3) / df(3)
print('x = r + Δr = %.8f' % root)
print('Δr = %.8f' % droot)
print('r = x - Δr = %.8f' % (root - droot))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(a) Use fzero to find the root of $f(x) = 2x\cos{x} - 2x + \sin{x^3}$ on $\left [ -0.1, 0.2 \right ]$. Report the forward and backward errors.
Can you write Python code for it?

f = lambda x : 2 * x * np.cos(x) - 2 * x + np.sin(np.power(x, 3))
root = scipy.optimize.fsolve(f, 0.03)[0]
print('root = %.16f' % root)
print('forward  error : %.16f' % np.abs(root) )
print('backward error : %.16f' % np.abs(f(root)) )


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $ e^x + x = 7 $
$ e^x + x = 7 $
$ \Rightarrow e^x = 7 - x $
$ \Rightarrow x = \ln{7 - x} $
$ \Rightarrow g(x) = \ln{7 - x} $
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : np.log(7 - x), 0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $3x^3 + x^2 = x + 5$
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : 3 * np.power(x, 3) + np.power(x, 2) - x - 5, 1, 2)
print('{:>.6f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $\sin{x} = 6x + 5$
$ \sin{x} = 6x + 5 $
$ \Rightarrow x = \frac{\sin{x} - 5}{6} $
$ \Rightarrow g(x) = \frac{\sin{x} - 5}{6} $
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : (np.sin(x) - 5) / 6, 0.1, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $\sin{x} = 6x + 5$
Can you write Python code for it?

f = lambda x : np.sin(x) - 6 * x - 5
df = lambda x : np.cos(x) - 6
root = scipy.optimize.newton(f, 1, df)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $e^{x-2} + x^3 - x = 0$
Can you write Python code for it?

f = lambda x : np.exp(x - 2) + np.power(x, 3) - x
xpts = np.linspace(-1.2, 1.2, 41)
ypts = f(xpts)

myplot(xpts, ypts, '$f(x) = e^{x - 2} + x^3 - x$')
print('root = {:>+.6f}'.format(scipy.optimize.bisect(f, -1.5, -0.5)))
print('root = {:>+.6f}'.format(scipy.optimize.bisect(f, -0.5, 0.5)))
print('root = {:>+.6f}'.format(scipy.optimize.bisect(f, 0.5, 1.0)))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $f(x) = x^2 - 3$
Can you write Python code for it?

ranges = [1, 2]
f = lambda x : np.power(x, 2) - 3
root = scipy.optimize.bisect(f, *ranges)
print('x is {:>.8f} in {:}'.format(root, ranges))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $g(x, 5) = \frac{x^2 + 5}{2x}$
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : g(x, 5), 0.1, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $h(y, 3) = \sqrt[3]{(2y^3 + 3/y^6)/3}$
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda y : h(y, 3), 1.0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) $sin{x} = 6x + 5$
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : np.sin(x) - 6 * x - 5, -5, 5)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) Apply Newton’s Method to find both the negative root and the positive root of $f(x)$. Then find intervals of positive initial guesses $[d1, d2]$, where $d2 > d1$, for which Newton’s Method: (c) converges to the positive root, (d) converges to the negative root, (e) is defined, but does not converge to any root. Your intervals should not contain any initial guess where $f'(x) = 0$, at which Newton’s Method is not defined.
Can you write Python code for it?

root = scipy.optimize.newton(lambda x : f(x, a = 1, b = 3), 4, lambda x : df(x, a = 1, b = 3))
print('[positive] root = {:.8f}'.format(root))

root = scipy.optimize.newton(lambda x : f(x, a = 1, b = 3), -4, lambda x : df(x, a = 1, b = 3))
print('[negative] root = {:.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) Fix $D$ and $\epsilon$ as in (a), and calculate the Darcy number for several Reynolds numbers $R$ between $10^4$ and $10^8$. Make a plot of the Darcy number versus Reynolds number, using a log axis for the latter.
Can you write Python code for it?

Rs = np.array(np.power(10, np.linspace(4, 8, 41)))
Fs = np.array([])
for R in Rs:
    Fs = np.append(Fs, scipy.optimize.newton(lambda f : colebrook(f, 0.0002, 0.3, R), 1e-3, lambda f : dcolebrook(f, 0.0002, 0.3, R)))

plt.plot(Rs, Fs, color='black')
plt.xlabel('Reynolds number R')
plt.ylabel('Darcy number f')
plt.xscale('log')
plt.title('Colebrook equation with fixed $D$ and $\epsilon$')
plt.show()
plt.close()


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) How do the answers to (a) change if the eccentricity is changed to $e = 0.2$?
Can you write Python code for it?

e = 0.2

# define f(x) = M - E + e * sin(E)
f = lambda E, e, M : M - E + e * np.sin(E)

# when M = π/6
M = scipy.pi / 6
xpts = np.linspace(-1, 1, 21)
ypts = f(xpts, e, M)
myplot(xpts, ypts, '$M = \pi/6, e = 0.2$', xlabel = 'E', ylabel = 'f(x)')
root = scipy.optimize.bisect(lambda x : f(x, e, M), 0.25, 0.75)
print('eccentric anomalies is {:>.6f} while M = π/6'.format(root))

# when M = π/2
M = scipy.pi / 2
xpts = np.linspace(1, 2, 21)
ypts = f(xpts, e, M)
myplot(xpts, ypts, '$M = \pi/2, e = 0.2$', xlabel = 'E', ylabel = 'f(x)')
root = scipy.optimize.bisect(lambda x : f(x, e, M), 1, 2)
print('eccentric anomalies is {:>.6f} while M = π/2'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) Setting $\epsilon = 10^{-3}$, find the actual root and compare with part (a).
Can you write Python code for it?

epsilon = 1e-3
f = lambda x : np.power(x, 3) - 3 * np.power(x, 2) + x - 3
df = lambda x : 3 * np.power(x, 2) - 6 * x + 1
g = lambda x : np.power(x, 3)
f_eps = lambda x, epsilon : f(x) + g(x) * epsilon
root = scipy.optimize.fsolve(lambda x : f_eps(x, epsilon), 3)
droot = -epsilon * g(3) / df(3)
print('x = r + Δr = %.8f' % root)
print('Δr = %.8f' % droot)
print('r = x - Δr = %.8f' % (root - droot))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) The immigration rate from 2000 to 2010 was $m = 1.030$ million per year, and the population in 2010 was 308.7 million. Find the intrinsic growth rate r during the 2000–2010 decade.
$f(x) = 27.3 + \frac{1.030}{r}(1 - e^{10r})$
Can you write Python code for it?


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(b) Use initial guess x = 0.1 to locate a root. What are the forward and backward errors.
Can you write Python code for it?

f = lambda x : np.sin(np.power(x, 3)) - np.power(x, 3)
root = scipy.optimize.fsolve(f, 0.1)[0]
print('forward error  = %.16f' %(np.abs(root)))
print('backward error = %.16f' %(np.abs(f(root))))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $ e^x + \sin{x} = 4 $
$ e^x + \sin{x} = 4 $
$ \Rightarrow e^x = 4 - \sin{x} $
$ \Rightarrow x = \ln{(4 - \sin{x})} $
$ \Rightarrow g(x) = \ln{(4 - \sin{x})} $
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : np.log(4 - np.sin(x)), 0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $\cos^2{x} + 6 = x$
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : np.power(np.cos(x), 2) - x + 6, 0, 10)
print('{:>.6f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $e^x + \sin{x} = 4$
Can you write Python code for it?

f = lambda x : np.exp(x) + np.sin(x) - 4
df = lambda x : np.exp(x) + np.cos(x)
root = scipy.optimize.newton(f, 1, df)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $e^x + sin(x) = 4$
Can you write Python code for it?

f = lambda x : np.exp(x) + np.sin(x) - 4
root = scipy.optimize.brentq(f, 1, 2)
print('{:>.8f}'.format(root))


f = lambda x : np.exp(x) + np.sin(x) - 4
root = false_position_method(f, 1, 2)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $f(x) = x^2 - 5$
Can you write Python code for it?

ranges = [2, 3]
f = lambda x : np.power(x, 2) - 5
root = scipy.optimize.bisect(f, *ranges)
print('x is {:>.8f} in {:}'.format(root, ranges))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $f(x) = x^3 - 5$
Can you write Python code for it?

ranges = [1, 2]
f = lambda x : np.power(x, 3) - 5
root = scipy.optimize.bisect(f, *ranges)
print('x is {:>.8f} in {:}'.format(root, ranges))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) $h(y, 5) = \sqrt[3]{(2y^3 + 5/y^6)/3}$
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda y : h(y, 5), 1.0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
(c) Why are Theorems 1.11 and 1.12 not applicable?
$f(x)$ is not differentiable in $[0, 0.75]$

(a) Fix real numbers $a,b > 0$ and plot the graph of $f(x) = a^2x^4 - 6abx^2 - 11b^2$ for your chosen values. Do not use $a = 2,b = 1/2$, since that case already appears in Example 1.15.
Can you write Python code for it?

f = lambda x, a, b : np.power(a, 2) * np.power(x, 4) - 6 * a * b * np.power(x, 2) - 11 * np.power(b, 2)
df = lambda x, a, b : 4 * np.power(a, 2) * np.power(x, 3) - 12 * a * b * x
xpts = np.linspace(-5, 5, 60)
ypts = f(xpts, a = 1, b = 3)
myplot(xpts, ypts, '$f(x) = a^2x^4 − 6abx^2 − 11b^2, a = 1, b = 3$')


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.1 Computer Problems

Use the Bisection Method to ﬁnd the root to six correct decimal places.

(a) $x^3 = 9$
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : np.power(x, 3) - 9, 2, 3)
print('{:>.6f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.2 Computer Problems

Apply Fixed-Point Iteration to find the solution of each equation to eight correct decimal places.

(a) $ x^3 = 2x + 2 $
$ x^3 = 2x + 2 $
$\Rightarrow x = \sqrt[3]{2x + 2}$
$\Rightarrow g(x) = \sqrt[3]{2x + 2}$
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : np.power(2 * x + 2, 1 / 3), 2.0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.2 Fixed-Point Iteration
DEFINITION 1.4
The real number r is a fixed point of the function g if $g(r) = r$.
Can you write Python code for it?

def fpi(g, x0, k, tol = 0):
    """
    Computes approximate solution of g(x)=x by Fixed-Point Iteration

    Args:
        g (function prototype) : function handle
        x0 (real number) : starting guess
        k (integer) : number of iteration steps
        tol (real number) : tolerance (default : 0)

    Returns:
        Approximate solution xc

    Raises:
        ValueError :
            - g is None
            - k is not the type of positive integer
            - tol is negative
    """
    try:
        if g is None :
            raise ValueError('f is null')
        if k != int(k) :
            raise ValueError('k must be type of integer')
        if k < 0 :
            raise ValueError('k must be positive integer')
        if tol < 0 :
            raise ValueError('tol must be positive')

        x = x0
        for _ in range(k) :
            tx = g(x)
            if tol > 0 and abs(tx - x) / abs(tx) < tol :
                return tx
            else :
                x = tx

        return x
    except ValueError as e:
        print('ValueError Exception : ', e)
        traceback.print_exception()


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.3 Computer Problems

Let $f(x) = sinx - x$.

(a) Find the multiplicity of the root r = 0.
$f(0) = \sin{0} - 0 = 0$
$f'(0) = \cos0 - 1 = 0$
$f''(0) = -\sin0 = 0$
$f'''(0) = -\cos0 = -1$
The multiplicity is 3
(b) Use initial guess x = 0.1 to locate a root. What are the forward and backward errors.
Can you write Python code for it?

f = lambda x : np.sin(x) - x
root = scipy.optimize.fsolve(f, 0.1)[0]
print('forward error  = %.16f' %(np.abs(root)))
print('backward error = %.16f' %(np.abs(f(root))))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.4 Computer Problems

Each equation has one root. Use Newton’s Method to approximate the root to eight correct decimal places.

(a) $x^3 = 2x + 2$
Can you write Python code for it?

f = lambda x : np.power(x, 3) - 2 * x - 2
df = lambda x : 3 * np.power(x, 2) - 2
root = scipy.optimize.newton(f, 1, df)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.4 Newton's Method
Can you write Python code for it?

def newton_method( f, df, x0, k = 500, tol = 1e-6) :
    """
    Use Newton's method to find the root of the function

    Args:
        f (function prototype) : function handle
        df (function prototype) : derivative function handle
        x0 (real number) : starting guess
        k (integer) : number of iteration steps (default : 500)
        tol (real number) : tolerance (default : 1e-6)

    Return:
        Approximate solution xc

    Raises:
        ValueError :
            - f or df is None
            - k is smaller than 0
    """
    try:
        if f is None or df is None :
            raise ValueError('Function handle f or df is Null')

        if k <= 0 :
            raise ValueError('Iteration k must be larger than 0')

        xc = x0
        for _ in range(k) :
            xt = xc - f(xc) / df(xc)
            if tol > 0 and abs(xt - xc) / abs(xc) < tol :
                return xt
            else :
                xc = xt
        return xc
    except ValueError as e :
        print('ValueError Exception : ', e)
        traceback.print_exception()


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
1.5 Computer Problems

Use the Secant Method to ﬁnd the (single) solution of each equation in Exercise 1.

Initial guesses $x_0 = 1$ and $x_1 = 2$.

(a) $x^3 = 2x + 2$
Can you write Python code for it?

f = lambda x : np.power(x, 3) - 2 * x - 2
root = scipy.optimize.newton(f, 1)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
A $10cm$ high cone contains $60cm^3$ of ice cream, including a hemispherical scoop on top. Find the radius of the scoop to four correct decimal places.

The formula for the volume $V$ of a cone is $\large \frac{hr^2\pi}{3}$.
Then, $\normalsize 60 = V + \frac{(4/3\pi r^3)}{2} = \frac{hr^2\pi}{3} + \frac{2\pi r^3}{3}$
Can you write Python code for it?

f = lambda x : 10 * np.power(x, 2) * np.pi / 3 + 2 * np.power(x, 3) * np.pi / 3 - 60
df = lambda x : 20 * x * np.pi / 3 + 2 * np.power(x, 2) * np.pi
root = scipy.optimize.newton(f, 1, df)
print('{:>.4f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
A crucial quantity in pipeline design is the pressure drop due to friction under turbulent flow. The pressure drop per unit length is described by the $\textit{Darcy number} f$, a unitless quantity that satisfies the empirical $\textit{Colebrook equation}$

$$
\large \frac{1}{\sqrt{f}} = -2\log_{10}{\left [ \frac{\epsilon}{3.7D} + \frac{2.51}{R\sqrt{f}} \right ]}
$$
where $D$ is the inside pipe diameter, $\epsilon$ is the roughness height of the pipe interior, and $R$ is the Reynolds number of the flow. (Flows in pipes are considered turbulent when $R > 4000$ or so.)
(a) For $D = 0.3 m$, $\epsilon = 0.0002m$, and $R = 105$, use Newton’s Method to calculate the Darcy number $f$.
Can you write Python code for it?

colebrook = lambda f, epsilon, D, R : 1 / np.sqrt(f) + 2 * np.log10(epsilon / (3.7 * D) + 2.51 / (R * np.sqrt(f)))
dcolebrook = lambda f, epsilon, D, R : -1 / (2 * np.power(f, 1.5)) - 2.51 / (R * np.power(f, 1.5) * (epsilon / (3.7 * D) + 2.51 / (R * np.sqrt(f))) *  np.log(10))

xpts = np.linspace(0.1, 1, 40)
ypts = colebrook(xpts, 0.0002, 0.3, 105)
myplot(xpts, ypts, 'Colebrook equation')

root = scipy.optimize.newton(lambda f : colebrook(f, 0.0002, 0.3, 105), 0.15, lambda f : dcolebrook(f, 0.0002, 0.3, 105))
print('f = {:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
A silo composed of a right circular cylinder of height $10m$ surmounted by a hemispherical dome contains $400m^3$ of volume. Find the base radius of the silo to four correct decimal places.

Assume that radius is $\textbf{r}$ and that satisfies
$\normalsize 400 = 10 \cdot (r^2\pi) + \frac{(4/3\pi r^3)}{2} = 10r^2\pi + \frac{2r^3\pi}{3}$
Can you write Python code for it?

f = lambda x : 10 * np.power(x, 2) * np.pi + 2 * np.power(x, 3) * np.pi / 3 - 400
df = lambda x : 20 * x * np.pi + 2 * np.power(x, 2) * np.pi
root = scipy.optimize.newton(f, 1, df)
print('{:>.4f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Additional Examples

Apply two steps of the Secant Method on the interval with initial guesses $x_0 = 1$ and $x_1 = 2$ to ﬁnd the approximate root of $f(x) = 2x^3 - x - 7$.
Can you write Python code for it?

root = scipy.optimize.newton(lambda x : 2 * np.power(x, 3) - x - 7, 1)
print('r = {:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Apply Fixed-Point Iteration to find the solution of each equation to eight correct decimal places.

(a) $x^5 + x = 1$
$ x^5 + x = 1 $
$ \Rightarrow x^5 = 1 - x $
$ \Rightarrow x = \sqrt[5]{1 - x} $
$ \Rightarrow g(x) = \sqrt[5]{1 - x} $
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : np.power(1 - x, 1 / 5), 0.1, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Apply Newton’s Method to find both roots of the function
$f(x) = 14xe^{x-2} - 12e^{x-2} - 7x^3 + 20x^2 - 26x + 12$ on the interval $[0, 3]$. For each root, print out the sequence of iterates, the errors $e_i$, and the relevant error ratio $e_{i+1}/e^2_{i}$ or $e_{i+1}/e_{i}$ that converges to a
nonzero limit. Match the limit with the expected value $M$ from Theorem 1.11 or $S$ from Theorem 1.12.
Can you write Python code for it?

f = lambda x :  14 * x * np.exp(x - 2) - 12 * np.exp(x - 2) - 7 * np.power(x, 3) + 20 * np.power(x, 2) - 26 * x + 12
df = lambda x : 14 * x * np.exp(x - 2) + 2 * np.exp(x - 2) - 21 * np.power(x, 2) + 40 * x - 26

xpts = np.linspace(0.8, 2, 41)
ypts = f(xpts)

myplot(xpts, ypts, '$f(x) = 14xe^{x-2} - 12e^{x-2} - 7x^3 + 20x^2 - 26x + 12$')

root = scipy.optimize.newton(f, 0, df)
print('root = {:.8f}'.format(root))

e_i = np.abs(scipy.optimize.newton(f, 0, df, maxiter = 6, disp = False) - root)
e_ii = np.abs(scipy.optimize.newton(f, 0, df, maxiter = 7, disp = False) - root)
M = e_ii / np.power(e_i, 2)
print('M = {:.8f}'.format(M))

root = scipy.optimize.newton(f, 1.9, df)
print('root = {:.8f}'.format(root))

e_i = np.abs(scipy.optimize.newton(f, 1.9, df, maxiter = 8, disp = False) - root)
e_ii = np.abs(scipy.optimize.newton(f, 1.9, df, maxiter = 9, disp = False) - root)
S = e_ii / e_i
print('S = {:.8f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Apply Newton’s Method to find the only root to as much accuracy as possible, and find the root’s multiplicity. Then use Modified Newton’s Method to converge to the root quadratically. Report the forward and backward errors of the best approximation obtained from each method.

(a) $f(x) = 27x^3 + 54x^2 + 36x + 8$
Can you write Python code for it?

f = lambda x : 27 * np.power(x, 3) + 54 * np.power(x, 2) + 36 * x + 8
df = lambda x : 81 * np.power(x, 2) + 108 * x + 36
root = scipy.optimize.newton(f, 1, df)
print('root = {:>.8f}'.format(root))

e_i = np.abs(scipy.optimize.newton(f, 1, df, maxiter = 10, disp = False) - root)
e_ii = np.abs(scipy.optimize.newton(f, 1, df, maxiter = 11, disp = False) - root)
print('S = {:.6f} ≈ 2/3 implies that multiplicity is 3 according to theorem 1.12'.format(e_ii / e_i))

print('forward  error : {:.8f}'.format(np.abs(- 2 / 3 - root)))
print('backward error : {:.8f}'.format(np.abs(f(root))))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Apply two steps of the Bisection Method on the interval $[1, 2]$ to find the approximate root of $f(x) = 2x^3 - x - 7$.
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : 2 * np.power(x, 3) - x - 7, 1, 2)
print('{:>.6f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Calculate the cube roots of the following numbers to eight correct decimal places by using the Bisection Method to solve $x^3 - A = 0$, where A is (a) 2 (b) 3 (c) 5. State your starting interval and the number of steps needed.

(a) $f(x) = x^3 - 2$
Can you write Python code for it?

ranges = [1, 2]
f = lambda x : np.power(x, 3) - 2
root = scipy.optimize.bisect(f, *ranges)
print('x is {:>.8f} in {:}'.format(root, ranges))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Calculate the cube roots of the following numbers to eight correct decimal places, by using Fixed-Point Iteration with $g(x) = (2x + A/x^2) / 3$, where A is (a) 2 (b) 3 (c) 5. State your initial guess and the number of steps needed.

Let $y^3 = x$ and $g(x, A) = (2y^3 + A/y^6)/3$
$\Rightarrow y^3 = (2y^3 + A/y^6)/3$
$\Rightarrow y = \sqrt[3]{(2y^3 + A/y^6)/3}$
$\Rightarrow h(y, A) = \sqrt[3]{(2y^3 + A/y^6)/3}$
Can you write Python code for it?

h = lambda y, A : np.power((2 * np.power(y, 3) + A / np.power(y, 6)) / 3, 1 / 3)


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Calculate the square roots of the following numbers to eight correct decimal places by using Fixed-Point Iteration as in Example 1.6: (a) 3 (b) 5. State your initial guess and the number of steps needed.

We can conclude that $g(x, c) = x = \sqrt{c} = \frac{x^2 + c}{2x}$ from Example 1.6. Then
Can you write Python code for it?

g = lambda x, c : (np.power(x, 2) + c) / (2 * x)


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Calculate the square roots of the following numbers to eight correct decimal places by using the Bisection Method to solve $x^2 - A = 0$, where A is (a) 2 (b) 3 (c) 5. State your starting interval and the number of steps needed.

(a) $f(x) = x^2 - 2$
Can you write Python code for it?

ranges = [1, 2]
f = lambda x : np.power(x, 2) - 2
root = scipy.optimize.bisect(f, *ranges)
print('x is {:>.8f} in {:}'.format(root, ranges))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Carry out Computer Problem 1 for $f(x) = \sin{x^3} - x^3$.

(a) Find the multiplicity of the root r = 0.
Can you write Python code for it?

def derivative_f(f):
    while True:
        f = sympy.diff(f)
        yield f

f = sympy.sin(sympy.abc.x ** 3) - sympy.abc.x ** 3
fx = sympy.lambdify(sympy.abc.x, f)(0)
df_generator = derivative_f(f)

display(f)
display(fx)

while fx == 0:
    f = next(df_generator)
    fx = sympy.lambdify(sympy.abc.x, f)(0)
    display(f)
    display(fx)

print('multiplicity is 10')


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Carry out the steps of Computer Problem 7 for the function
$f(x) = 94\cos^3{x} - 24\cos{x} + 177\sin^2{x} - 108\sin^4{x} - 72\cos^3{x}\sin^2{x} - 65$ on the interval $[0, 3]$
Can you write Python code for it?

f = lambda x : 94 * np.power(np.cos(x), 3) - 24 * np.cos(x) + 177 * np.power(np.sin(x), 2) - 108 * np.power(np.sin(x), 4) \
- 72 * np.power(np.cos(x), 3) * np.power(np.sin(x), 2) - 65

df = lambda x : -282 * np.sin(x) * np.power(np.cos(x), 2) + 24 * np.sin(x) + 354 * np.sin(x) * np.cos(x) \
- 432 * np.power(np.sin(x), 3) * np.cos(x) + 216 * np.power(np.sin(x), 3) * np.power(np.cos(x), 2) \
- 144 * np.sin(x) * np.power(np.cos(x), 4)

xpts = np.linspace(0, 2.4, 41)
ypts = f(xpts)

myplot(xpts, ypts, '$f(x) = 94\cos^3{x} − 24\cos{x} + 177\sin^2{x} − 108\sin^4{x} − 72\cos^3{x}\sin^2{x} − 65$')

# rightmost root
root = scipy.optimize.newton(f, 2.2, df)
e_i = np.abs(scipy.optimize.newton(f, 2.2, df, maxiter = 4, disp = False) - root)
e_ii = np.abs(scipy.optimize.newton(f, 2.2, df, maxiter = 5, disp = False) - root)
print('(rightmost) root = {:.6f}'.format(root))
print('converge quadratically')

root = scipy.optimize.newton(f, 0.9, df)
e_i = np.abs(scipy.optimize.newton(f, 0.9, df, maxiter = 10, disp = False) - root)
e_ii = np.abs(scipy.optimize.newton(f, 0.9, df, maxiter = 11, disp = False) - root)
print('root = {:.6f}'.format(root))
print('converge linearly')
print('S = {:.6f} ≈ 2/3 implies multiplicity is 3'.format(e_ii / e_i))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
DEFINITION 1.5
Let $e_i$ denote the error at step $i$ of an iterative method. If
$$\lim_{i \rightarrow \infty} \frac{e_{i+1}}{e_i} = S < 1$$
the method is said to obey linear convergence with rate $S$.
THEOREM 1.6
Assume that $g$ is continuously differentiable, that $g(r) = r$, and that $S = \left | {g}'(r) \right | < 1$. Then Fixed-Point Iteration converges linearly with rate $S$ to the fixed point $r$ for initial guesses sufficiently close to $r$.
DEFINITION 1.7
An iterative method is called locally convergent to r if the method converges to r for initial guesses sufficiently close to r.
Example
Use Fixed-Point Iteration to find a root of $cosx = sinx$
$x + \cos{x} - \sin{x} = x $
$\Rightarrow g(x) = x + \cos{x} - \sin{x}$
Can you write Python code for it?

g = lambda x : x + np.cos(x) - np.sin(x)
root = scipy.optimize.fixed_point(g, 0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
DEFINITION 1.8
Assume that $f$ is a function and that $r$ is a root, meaning that it satisfies $f(r) = 0$. Assume that $x_a$ is an approximation to $r$. For the root-finding problem, the backward error of the approximation $x_a$ is $\left | f(x_a) \right |$ and  the forward error  is $\left | r - x_a \right |$
DEFINITION 1.9
Assume that $r$ is a root of the differentiable function $f$ ; that is, assume that $f(r) = 0$. Then if $0 = f(r) = f'(r) = f''(r) = \dots = f^{(m-1)}(r)$, but $f^{(m)}(r) \neq 0$, we say that $f$ has a root of multiplicity $m$ at $r$. We say that $f$ has a multiple root at $r$ if the multiplicity is greater than one. The root is called simple if the multiplicity is one.
Example
The function $f(x) = sinx - x$ has  a triple root at $r = 0$. Find the forward and backward error of the approximate root $x_a = 0.001$.
$f(0) = \sin0 - 0 = 0$

$f'(0) = \cos0 - 1 = 0$

$f''(0) = -\sin0 - 0 = 0$

$f'''(0) = -\cos0 - 0 = -1$

The forward error is $\left | r - x_a \right | = 10^{-3}$

The backward error is $\left | f(x_a) \right | = \left | sin(0.001) - 0.001 \right | \approx 1.6667 \times 10^{-10}$
Sensitivity Formula for Roots
Assume that $r$ is a root of $f(x)$ and $r + \Delta r$ is a root of $f(x) + \epsilon g(x)$. Then
$$ \Delta r \approx -\frac{\epsilon g(r)}{f'(r)}$$
if $\epsilon \ll  f'(r)$
Error Magnification Factor
$$\textbf{error magnification factor} = \frac{\text{relative forward error}}{\text{relative backward error}}$$
$$
\text{error magnification factor}
= \left | \frac{\Delta{r}/r}{\epsilon{g(r)/g(r)}} \right |
= \left | \frac{-\epsilon{g(r)/(rf'(r))}}{\epsilon} \right |
= \frac{\left | g(r) \right |}{\left | rf'(r) \right |}
$$
Additional Examples

Find the multiplicity of the root $r = 0$ of $f(x) = 6x - 6\sin{x} - x^3$.

$f(x) = 6x - 6\sin{(x)} - x^3, f(x = 0) = 0$
$f'(x) = -3x^2 - 6\cos{(x)} + 6, f'(x = 0) = 0$
$f''(x) = -6x + 6\sin{(x)}, f''(x = 0) = 0$
$f^{(3)}(x) = -6 + 6\cos{(x)}, f^{(3)}(x = 0) = 0$
$f^{(4)}(x) = - 6\sin{(x)}, f^{(4)}(x = 0) =...
Can you write Python code for it?

f = lambda x : 6 * x - 6 * np.sin(x) - np.power(x, 3)
root = scipy.optimize.fsolve(g, 0.001)[0]
print('{:>.6f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Each equation has one real root. Use Newton’s Method to approximate the root to eight correct decimal places.

(a) $x^5 + x = 1$
Can you write Python code for it?

f = lambda x : np.power(x, 5) + x - 1
df = lambda x : 5 * np.power(x, 4) + 1
root = scipy.optimize.newton(f, 1, df)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Example
Apply the Method of False Position on interval $[-1,1]$ to find the root $r = 0$ of $f(x) = x^3 - 2x^2 + \frac{3}{2}x$
Can you write Python code for it?

f = lambda x : np.power(x, 3) - 2 * np.power(x, 2) + 1.5 * x
false_position_method(f, -1, 1)

def inverse_quadratic_interpolation(f, x0, x1, x2, k):
    a = x0
    b = x1
    c = x2
    for _ in range(k) :
        q = f(a) / f(b)
        r = f(c) / f(b)
        s = f(c) / f(a)

        denominator = (q - 1) * (r - 1) * (s - 1)
        if denominator == 0 :
            break

        tmp = c - (r * (r - q) * (c - b) + (1 - r) * s * (c - a)) / denominator
        a = b
        b = c
        c = tmp

    return c


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Example
Apply the Secant Method with starting guesses $x_0 = 0,x_1 = 1$ to find the root of $f(x)=x^3 + x + 1$
Can you write Python code for it?

f = lambda x : np.power(x, 3) + x - 1

# No fprime to use secant method instead
root = scipy.optimize.newton(f, 0)
print('r = {:>.8f}'.format(root))

def false_position_method(f, a, b, max_iter = 500, tol = 1e-8) :
    """
    Use false position method to find the root of the formula f

    Args:
        f (function prototype) : function handle
        a (real number) : the lowerbound of the bracket of initial guess
        b (real number) : the upperbound of the bracket of initial guess
        max_iter (integer) : number of iteration steps (default : 500)
        tol (real number) : tolerance

    Return:
        Approximate solution xc

    Raises:
        ValueError:
            - f(a) * f(b) must be smaller than 0 (exclude zero)

    """
    if f(a) * f(b) >= 0 :
        raise ValueError('f(a) * f(b) must be < 0')
    for _ in range(max_iter) :
        _tol = 0
        c = (b * f(a) - a * f(b)) / (f(a) - f(b))
        if f(c) == 0 :
            return c
        if f(a) * f(c) < 0 :
            _tol = np.abs(b - c)
            b = c
        else :
            _tol = np.abs(a - c)
            a = c
        if _tol <= tol:
            break
    return c


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Example
Calculate $\sqrt{2}$ by using FPI.
$x = \sqrt{2} $
$\Rightarrow x - \sqrt{2} = 0 $
$\Rightarrow x^2 - 2\sqrt{2}x + 2 = 0 $
$\Rightarrow x^2 + 2 = 2\sqrt{2}x $
$\Rightarrow g(x) = x = \sqrt{2} = \frac{x^2 + 2}{2x} $
Can you write Python code for it?

g = lambda x : (np.power(x, 2) + 2) / (2 * x)
root = scipy.optimize.fixed_point(g, 2.0, method='iteration')
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Example
Find a root of $f(x) = x^3 + x - 1$ by using the Bisection Method on the interval $[0, 1]$.
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : np.power(x, 3) + x - 1, 0, 1)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Example
Find the Newton's Method formula for the equation $x^3 + x - 1 = 0$.
Can you write Python code for it?

f = lambda x : np.power(x, 3) + x - 1
df = lambda x : 3 * np.power(x, 2) + 1
root = scipy.optimize.newton(f, 0, df)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Example 1.3 showed that $g(x) = \cos{x}$ is a convergent FPI. Is the same true for $g(x) = \cos^2{x}$? Find the fixed point to six correct decimal places, and report the number of FPI steps needed. Discuss local convergence, using Theorem 1.6.
Can you write Python code for it?

root = scipy.optimize.fixed_point(lambda x : np.power(np.cos(x), 2), 1.0, method='iteration')
print('{:>.6f}'.format(root))

dg = sympy.diff(sympy.cos(sympy.abc.x) ** 2)
display(dg)
S = np.abs(sympy.lambdify(sympy.abc.x, dg)(root))
print('S = {:>.6f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Find the height reached by 1 cubic meter of water stored in a spherical tank of radius 1 meter. Give your answer ±1 mm. (Hint: First note that the sphere will be less than half full. The volume of the bottom $H$ meters of a hemisphere of radius $R$ is $\pi H^2(R - 1/3H)$.)
Can you write Python code for it?

# First note implies that the range will be [0, 1]
ranges = [0, 1]

# Define f(x) = V(x, 1) - 1 where V(H, R) = pi * H^2 * (R - H / 3)
volume = lambda H, R : scipy.pi * np.power(H, 2) * (R - H / 3)
f = lambda x : volume(x, 1) - 1

root = scipy.optimize.bisect(f, *ranges)
print('{:>.6f} m'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
It is locally convergent due to S = 0.305228 < 1
(3) $ 2x \cdot x^2 = 6x + 1 $
$ \Rightarrow g(x) = x = \frac{\sqrt{6/x + 1/x^2}}{2} $
Can you write Python code for it?

f = lambda x : np.sqrt(6 / x + 1 / np.power(x, 2)) / 2
root = scipy.optimize.fixed_point(f, 2.0, method='iteration')
print('3rd root is {:>.6f}'.format(root))

dg = sympy.diff( ((6 / sympy.abc.x + 1 / sympy.abc.x ** 2) ** 0.5) / 2 )
S = np.abs(sympy.lambdify(sympy.abc.x, dg)(root))
print('S = {:>.6f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
It is locally convergent due to S = 0.400000 < 1
(2) $f(x) = 1 + 5x - 6x^3 - e^{2x}$
$ \Rightarrow 6x^3 = 1 + 5x - e^{2x}$
$ \Rightarrow x^3 = \frac{1 + 5x - e^{2x}}{6}$
$ \Rightarrow g(x) = x =  \sqrt[3]{\frac{1 + 5x - e^{2x}}{6}}$
Can you write Python code for it?

g = lambda x : np.power((1 + 5 * x - np.exp(2 * x)) / 6, 1 / 3)
root = scipy.optimize.fixed_point(g, 0.5, method='iteration')
print('2nd root is {:>.6f}'.format(root))

dg = sympy.diff((1 + 5 * sympy.abc.x - sympy.exp(2 * sympy.abc.x)) ** (1 / 3))
S = np.abs(sympy.lambdify(sympy.abc.x, dg)(root))
print('S = {:>.6f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
It is locally convergent due to S = 0.464096 < 1
(2) $x^3 = x - e^{x-2} $
$ \Rightarrow x = \sqrt[3]{x - e^{x-2}} $
$ \Rightarrow g(x) = \sqrt[3]{x - e^{x-2}} $
Can you write Python code for it?

g = lambda x : np.power(x - np.exp(x - 2), 1 / 3)
root = scipy.optimize.fixed_point(g, 1, method='iteration')
print('2nd root is {:>.6f}'.format(root))

dg = sympy.diff((sympy.abc.x - sympy.exp(sympy.abc.x - 2)) ** (1 / 3))
S = np.abs(sympy.lambdify(sympy.abc.x, dg)(root))
print('S = {:>.6f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
It is locally convergent due to S = 0.506308 < 1
(3) $f(x) = 1 + 5x - 6x^3 - e^{2x}$
$ \Rightarrow e^{2x} = 1 + 5x - 6x^3$
$ \Rightarrow 2x = \ln{(1 + 5x - 6x^3)}$
$ \Rightarrow g(x) = x = \frac{\ln{(1 + 5x - 6x^3)}}{2} $
Can you write Python code for it?

g = lambda x : np.log(1 + 5 * x - 6 * np.power(x, 3)) / 2
print('Diverge, cannot find 3rd root by FPI')

# We use other method to find 3rd root
root = scipy.optimize.fsolve(g, -1)[0]
print('3rd root is {:>.6f}'.format(root))

dg = sympy.diff(sympy.log(1 + 5 * sympy.abc.x - 6 * sympy.abc.x ** 3) / 2)
S = np.abs(sympy.lambdify(sympy.abc.x, dg)(root))
print('S = {:>.6f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
It is locally convergent due to S = 0.561172 < 1
(b) $f(x) = e^{x-2} + x^3 - x$
(1) $x = e^{x-2} + x^3$
$ \Rightarrow g(x) = e^{x-2} + x^3 $
Can you write Python code for it?

g = lambda x : np.exp(x - 2) + np.power(x, 3)
root = scipy.optimize.fixed_point(g, 0, method='iteration')
print('1st root is {:>.6f}'.format(root))

dg = sympy.diff(sympy.log(sympy.abc.x - 2) + sympy.abc.x ** 3)
S = np.abs(sympy.lambdify(sympy.abc.x, dg)(root))
print('S = {:>.6f}'.format(S))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Set $f(x) = 54x^6 + 45x^5 - 102x^4 - 69x^3 + 35x^2 + 16x - 4$. Plot the function on the interval $[-2,2]$, and use the Secant Method to ﬁnd all ﬁve roots in the interval. To which of the roots is the convergence linear, and to which is it superlinear?
Can you write Python code for it?

f = lambda x : 54 * np.power(x, 6) + 45 * np.power(x, 5) - 102 * np.power(x, 4) - 69 * np.power(x, 3) + 35 * np.power(x, 2) + 16 * x - 4

xpts = np.linspace(-1.4, 1.2, 120)
ypts = f(xpts)
myplot(xpts, ypts, r'$f(x) = 54x^6 + 45x^5 - 102x^4 - 69x^3 + 35x^2 + 16x - 4$')

root = scipy.optimize.newton(f, -1.5)
print('{:>.8f}'.format(root))

root = scipy.optimize.newton(f, -0.8)
print('{:>.8f}'.format(root))

root = scipy.optimize.newton(f, 0.1)
print('{:>.8f}'.format(root))

root = scipy.optimize.newton(f, 0.4)
print('{:>.8f}'.format(root))

root = scipy.optimize.newton(f, 1.2)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
THEOREM 1.12
Assume that the $(m + 1)$-times continuously differentiable function $f$ on $[a,b]$ has a multiplicity $m$ root at $r$. Then Newton’s Method is locally convergent to $r$, and the error $e_i$ at step $i$ satisfies
$$\large \lim_{i \rightarrow \infty}{\frac{e_{i + 1}}{e_i}} = S $$
where $ S = (m - 1)/m $.
THEOREM 1.13
If $f$ is $(m + 1)$-times continuously differentiable on $[a,b]$, which contains a root $r$ of multiplicity $m > 1$, then Modified Newton’s Method
$$
\large x_{i+1} = x_i - \frac{mf(x_i)}{f'(x_i)}
$$
converges locally and quadratically to $r$.
Example
Apply Newton’s Method to $f(x) = 4x^4 - 6x^2 - 11/4$ with starting guess $x_0 = 1/2$.
Can you write Python code for it?

try:
    f = lambda x : 4 * np.power(x, 4) - 6 * np.power(x, 2) - 11 / 4
    df = lambda x : 16 * np.power(x, 3) - 12 * x
    root = scipy.optimize.newton(f, 0.5, df)
    print('{:>.8f}'.format(root))
except RuntimeError as e:
    print(e)


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
The Hilbert Matrix  is the n × n matrix whose ijth entry is $\frac{1}{i + j - 1}$. Let $A$ denote the
5 × 5 Hilbert matrix. Its largest eigenvalue is about 1.567. Use the Bisection Method to decide
how to change the upper left entry $A_{11}$ to make the largest eigenvalue of $A$ equal to $\pi$. Determine $A_
{11}$ within six correct decimal places.
Can you write Python code for it?

def hilbert_matrix_eigvals(upper_left_element):
    hilbert_matrix = LA.hilbert(5)
    hilbert_matrix[0][0] = upper_left_element
    return LA.eigvals(hilbert_matrix)

f = lambda x : np.max(hilbert_matrix_eigvals(x)).real - scipy.pi

def fs(f, xpts):
    ypts = np.zeros(xpts.size)
    for i in range(len(xpts)):
        ypts[i] = f(xpts[i])
    return ypts

# Generate samples
xpts = np.linspace(-2, 4, 21)
ypts = fs(f, xpts)

# Plot f(x)
plt.plot(xpts,ypts)
myplot(xpts, ypts, 'Eigenvalue of Hilbert Matrix $f(x) = eigval(H(x)) - \pi$', ylabel = 'f(x)')

root = scipy.optimize.bisect(f, 2, 4)
print('Make A[1,1] to be {:>.6f} to make the largest eigenvalue equal to pi'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Use the Bisection Method to find the two real numbers x, within six correct decimal places, that make the determinant of the matrix

$A =
\begin{bmatrix}
1 & 2 & 3 & x \
4 & 5 & x & 6 \
7 & x & 8 & 9 \
x & 10 & 11 & 12
\end{bmatrix}
$
equal to 1000. For each solution you find, test it by computing the corresponding determinant and reporting how many correct decimal places (after the decimal point) the determinant has when your solution x is used.
Can you write Python code for it?

def A(x):
    template_A = '1 2 3 {0} ; 4 5 {0} 6 ; 7 {0} 8 9 ; {0} 10 11 12'.format(x)
    _A = np.array(np.mat(template_A))
    return _A

def As(x):
    _A = None
    for _x in x:
        template_A = '1 2 3 {0} ; 4 5 {0} 6 ; 7 {0} 8 9 ; {0} 10 11 12'.format(_x)
        if _A is None:
            _A = np.array(np.mat(template_A))
        else:
            newA = np.array(np.mat(template_A))
            _A = np.concatenate((_A, newA))
    _A = np.reshape(_A, (int(_A.size / 16), 4, 4))
    return _A

# define f(x) = det(A(x)) - 1000
f = lambda x : np.linalg.det(A(x)) - 1000
fs = lambda x : np.linalg.det(As(x)) - 1000

# plot f(x)
xpts = np.linspace(-17.9, 13, 41)
ypts = fs(xpts)
myplot(xpts, ypts, '$f(x) = det(A(x)) - 1000$', ylabel = 'f(x)')

# Use bisection method to find root
root1 = scipy.optimize.bisect(f, -20, -15)
root2 = scipy.optimize.bisect(f, 5, 15)
print('x is {:>.6f} and {:>.6f}'.format(root1, root2))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Use the Bisection Method to locate all solutions of the following equations. Sketch the function by using MATLAB’s plot command and identify three intervals of length one that contain a root. Then find the roots to six correct decimal places.
Can you write Python code for it?

def myplot(xpts, ypts, title = '', xlabel = 'x', ylabel = 'y'):
    plt.plot(xpts, ypts, color='black')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.axhline(0, color='black', linestyle=':', linewidth=1)
    plt.show()
    plt.close()


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Use the Bisection Method to ﬁnd the root to eight correct decimal places.

(a) $x^5 + x = 1$
Can you write Python code for it?

root = scipy.optimize.bisect(lambda x : np.power(x, 5) + x - 1, 0, 1)
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Use the data from Computer Problem 11 to find the volume of 1 mole of benzene vapor at 700 $K$ under a pressure of 20 atm. For benzene, $a = 18.0 L^2-atm/mole^2$ and $b = 0.1154 L/mole$.
Can you write Python code for it?


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
What happens if fzero is asked to ﬁnd the root of $f(x) = x^2$ near 1 (do not use a bracketing interval)? Explain the result.
Can you write Python code for it?

root = scipy.optimize.fsolve(lambda x : np.power(x, 2), 1)[0]
print('{:>.8f}'.format(root))


I am working on the file "1_Solving_Equations.ipynb".
The first task is:
Write a MATLAB program that uses the Secant Method to ﬁnd both roots of $f(x) = 8x^6 - 12x^5 + 6x^4 - 17x^3 + 24x^2 - 12x + 2$. Is the Secant Method superlinearly convergent to both roots?
Can you write Python code for it?

f = lambda x : 8 * np.power(x, 6) - 12 * np.power(x, 5) + 6 * np.power(x, 4) - 17 * np.power(x, 3) + 24 * np.power(x, 2) - 12 * x + 2

root = scipy.optimize.newton(f, 0.5)
print('r1 = {:>.8f}'.format(root))

root = scipy.optimize.newton(f, 1.5)
print('r2 = {:>.8f}'.format(root))


I am working on the file "1__Pandas_Basics.ipynb".
The first task is:
Indexing Series
Indexing series is exactly same as 1-D numpy arrays - index starts at 0.
Can you write Python code for it?

# Indexing pandas series: Same as indexing 1-d numpy arrays or lists
# accessing the fourth element
s[3]

# accessing elements starting index = 2 till the end
s[2:]

# accessing the second and the fourth elements
# note that s[1, 3] will not work, you need to pass the indices [1, 3] as a list inside the original []
s[[1, 3]]


I am working on the file "1__Pandas_Basics.ipynb".
The first task is:
Indices
An important concept in pandas dataframes is that of row indices. By default, each row is assigned indices starting from 0, and are represented at the left side of the dataframe.
Can you write Python code for it?


I am working on the file "1__Pandas_Basics.ipynb".
The first task is:
Now, arbitrary numeric indices are difficult to read and work with. Thus, you may want to change the indices of the df to something more meanigful.
Let's change the index to Ord_id (unique id of each order), so that you can select rows using the order ids directly.
Can you write Python code for it?

# Setting index to Ord_id
market_df.set_index('Ord_id', inplace = True)
market_df.head()


I am working on the file "1__Pandas_Basics.ipynb".
The first task is:
Usually, you will work with Series only as a part of dataframes. Let's study the basics of dataframes.
The Pandas Dataframe
Dataframe is the most widely used data-structure in data analysis. It is a table with rows and columns, with rows having an index and columns having meaningful names.
Creating dataframes from dictionaries
There are various ways of creating dataframes, such as creating them from dictionaries, JSON objects, reading from txt, CSV files, etc.
Can you write Python code for it?

# keys become column names
df = pd.DataFrame({'name': ['Vinay', 'Kushal', 'Aman', 'Saif'],
                   'age': [22, 25, 24, 28],
                    'occupation': ['engineer', 'doctor', 'data analyst', 'teacher']})
df


I am working on the file "1__Warmup.ipynb".
The first task is:
Also, notice that it is not necessary to perform an initial join with the data range of interest filtering out
non trading days, as padas does it for us , i.e.
Can you write Python code for it?

df_stock = get_data(symbols=['GOOG','SPY'],start='1/21/1999',end='4/15/2016')
print(">> Trading days from pandas:"+str(df_stock.shape[0]))
dates = pd.date_range('1/21/1999', '4/15/2016')
df = pd.DataFrame(index=dates)
print(">> Calendar days:"+str(df.shape[0]))
df = df.join(df_stock)
print(">> After join:"+str(df.shape[0]))
df = df.dropna(subset=["SPY"])
print(">> After removing non trading days:"+str(df.shape[0]))


I am working on the file "1__Warmup.ipynb".
The first task is:
Cumulative returns
Can you write Python code for it?

def cumulative_returns(df):
    return df/df.ix[0,:] - 1

ax = cumulative_returns(fill_missing_values(
        get_data(
            symbols=['GOOG','SPY','IBM','GLD'],
                             start='4/21/2016',
                             end='7/15/2016'))).plot(title="Cumulative returns")

ax.set_xlabel("Date")
ax.set_ylabel("Cumulative return")
plt.show()


I am working on the file "1__Warmup.ipynb".
The first task is:
Let's see how much time is necessary for 70,000,000 iterations intead of 100,000 iterations.
Can you write Python code for it?

tm = time.time()
C0 = bsm(S0=105,r=0.06,sigma=0.22,T=1.0,K=109,R = 70000000 , seed=500)
pm = time.time() - tm
print("Value of European Call Option: {0:.4g}".format(C0)+" - time[{0:.4g} secs]".format(pm))


I am working on the file "1__Warmup.ipynb".
The first task is:
Let's see how we can speed up the computation with the numexpr package.
Can you write Python code for it?

import numexpr as ne
def bsm_ne(S0,r,sigma,T,K,R = 70000000 , seed=500):
    np.random.seed(seed)
    z = np.random.standard_normal(R)
    ST = ne.evaluate('S0 * exp(( r - 0.5 * sigma ** 2) * T + sigma * sqrt(T) * z)')
    hT = np.maximum(ST - K, 0)
    C0 = np.exp(-r * T) * np.sum(hT) / R
    return C0

tm = time.time()
C0 = bsm_ne(S0=105,r=0.06,sigma=0.22,T=1.0,K=109,R = 70000000 , seed=500)
pm = time.time() - tm
print("Value of the European Call Option: {0:.4g}".format(C0)+" - time[{0:.4g} secs]".format(pm))


I am working on the file "1__Warmup.ipynb".
The first task is:
Normalizing prices
Can you write Python code for it?

def normalize_data(df):
    return df/df.ix[0,:]

ax = normalize_data(
    fill_missing_values(
        get_data(
            symbols=['GOOG','SPY','IBM','GLD'],
                             start='1/21/1999',
                             end='4/15/2016'))).plot(title="Stock Data", fontsize=9)
ax.set_xlabel("Date")
ax.set_ylabel("Normalized price")
plt.show()