© B.J. Korites 2018
B.J. KoritesPython Graphicshttps://doi.org/10.1007/978-1-4842-3378-8_10

10. Demonstrations

B. J. Korites1 
(1)
Duxbury, Massachusetts, USA
 

In this chapter, you will apply some of the techniques developed in previous chapters to produce some interesting images. These images should give you some idea of the things that can be accomplished with Python graphics.

10.1 Saturn

Saturn is famous for its rings. While Jupiter, Saturn, Uranus, and Neptune also have rings, Saturn’s are the largest, brightest, and most well known in our solar system. They consist of particles as small as dust up to boulder-sized objects. These objects are composed mostly of ice and are thought to have originated when a comet or large asteroid collided with one of Saturn’s moons, shattering both into small pieces. Saturn has been known from ancient times but in 1610 Galileo was the first to observe it with a telescope. The planet is named after Saturn, the Roman god of agriculture, as is our sixth day, Saturday.

Listing 10-1 builds on an earlier program, Listing 7-2 from Chapter 7. That program is left mostly intact here except for the introduction of algorithms that construct Saturn’s rings and the shadow of the planet on the rings.

Figures 10-1 through 10-5 show images produced by Listing 10-1. They are at different angles of orientation, which are listed in the captions. Also listed are the unit vector components of the incoming light rays. For example, lx=+.707, ly=+.707, lz=0 indicates a source in the upper left quadrant; lx=-1, ly=0, lz=0 indicates a light source coming from the right. In the images, please notice the shadow cast by the planet on the rings, especially in Figure 10-5, which shows the curvature of the planet.

For comparison, a photographic image of Saturn can be found at www.jpl.nasa.gov/spaceimages/?search=saturn&category=#submit .
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig1_HTML.jpg
Figure 10-1

Saturn with rings and shadow 1: Rx=-20, Ry=0, Rz=-10, lx=1, ly=0, lz=0 (produced by Listing 10-1)

../images/456962_1_En_10_Chapter/456962_1_En_10_Fig2_HTML.jpg
Figure 10-2

Saturn with rings and shadow 2: Rx=-8, Ry=0, Rz=30, lx=.707, ly=.707, lz=0 (produced by Listing 10-1)

../images/456962_1_En_10_Chapter/456962_1_En_10_Fig3_HTML.jpg
Figure 10-3

Saturn with rings and shadow 3, Rx=-20, Ry=0, Rz=25, lx=.707, ly=.707, lz=0 (produced by Listing 10-1)

../images/456962_1_En_10_Chapter/456962_1_En_10_Fig4_HTML.jpg
Figure 10-4

Saturn with rings and shadow 4: Rx=-10, ry=0, Rz=25, lx=-.707, ly=-.707, lz=0 (produced by Listing 10-1)

../images/456962_1_En_10_Chapter/456962_1_En_10_Fig5_HTML.jpg
Figure 10-5

Saturn with rings and shadow 5: Rx=20, Ry=0, Rz=30, lx=-1, ly=0, lz=0 (produced by Listing 10-1)

Figure 10-6 shows the model used to construct the rings. In Chapter 7, you developed the shaded sphere algorithm by first creating an upright sphere. That is, the longitudes were vertical and the latitudes were horizontal (i.e. parallel to the x,z plane). From this starting orientation you rotated the sphere around the x,y, and z axes. You do a similar thing here for the rings. You create horizontal rings, which are parallel to the x,z plane, and then rotate them through the same angles along with the spherical planet body. The rings lie in a plane that passes through the sphere’s center so both the sphere and the rings have the same center of rotation.
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig6_HTML.jpg
Figure 10-6

Rings model: top view of planet and rings looking down on the x,z plane with Rx=0, Ry=0, Rz=0

The band is drawn as a series of adjacent concentric circles, each of which is composed of short line segments. Referring to Figure 10-6 and Listing 10-1, program lines 42 and 43 set the inner and outer radii of the rings. Line 44 sets the distance between circles. The rings are divided into seven annular bands (not shown in Figure 10-6) to accommodate different colors; their width is deltar in line 45.

Each line segment is rotated and plotted separately. Line 48 starts a radial direction loop from r1 to r2 plotting the circle segments. Line 49 starts a loop plotting in the circumferential direction. Lines 50-61 do the rotating producing global plotting coordinates xpg and ypg in lines 62 and 63. The rotation functions are the same as in previous programs.

Next, you set the colors of the segments. The rings are arranged in bands of different colors, which are a result of their physical composition as seen in the NASA image. This is done in lines 66-75. The first band, which goes from r=r1 to r1+deltar, has color clr=(.63,.54,.18) and so on for the remaining bands. You omit the fifth band, which is empty; the background color shows through. The sixth band is twice as wide as the others. This provides the colors for the seven bands.

For a given light direction, in most orientations the planet’s body will cast a shadow on the rings. Referring to Figure 10-7, your objective is to determine if point p lies inside or outside the planet’s shadow zone. The spherical planet casts a circular shadow. The shadow’s diameter will equal the size of the planet, or more precisely, the sphere’s “great circle.” This is the largest circle that can be obtained by cutting a sphere with a plane through its center. It’s like cutting an orange in half; what you see is the orange’s great circle. In Figure 10-7, the shadow could as well be caused by a circular disk of this size as by the spherical planet; the shadow will have the same size in either case. The side view of Saturn’s great circle is shown as the heavy line that passes through the plane’s center. From the geometry in Figure 10-7, you can see that if p lies in a position such that |B| > rs, where rs is Saturn’s radius, it is outside the shadow zone; if |B| < rs, p is inside the shadow zone. Once you determine where p is, if it is inside the shadow zone, when you plot the rings you will color that point grey. If it is outside, you will give it one of the band colors set in lines 66-75.
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig7_HTML.jpg
Figure 10-7

Shadow model

Your job now is to get |B| for a given position of p. You see from Figure 10-7 that
$$ left|mathrm{B}
ight|=left|mathrm{V}
ight|mathit{sin}left(phi 
ight) $$
(10-1)
You know that
$$ mathrm{V}	imes widehat{mathrm{u}}=left|mathrm{V}
ight|left|widehat{mathrm{u}}
ight|mathit{sin}left(phi 
ight) $$
(10-2)
where uˆ=-ˆl. Combining the above equations with |uˆ|=1,
$$ mathrm{B}=mathrm{V}	imes widehat{mathrm{u}} $$
(10-3)
$$ left|mathrm{B}
ight|=left|mathrm{V}	imes widehat{mathrm{u}}
ight| $$
(10-4)

In Listing 10-1, line 78 establishes the length of the incident light vector, ˆl. This should equal 1, but it may not if the components entered in lines 23-25 do not compute to 1 (i.e. $$ sqrt{l{x}^2+l{y}^2+l{y}^2}
e 1 $$). Lines 79-81 then reestablish the components if necessary. Lines 82-84 establish the components of vector V. Lines 85-87 compute components of B. Line 88 gives its magnitude magB=|B|. Line 89 determines if p lies within the shadow zone. If it does, line 90 is executed. This is the dot product of V with ˆl. It determines whether p lies on the side of the planet that is toward the light source, in which case it is opposite the dark side of the planet and not in the shadow zone. This is necessary since the shadow algorithm in lines 78-89 does not make this distinction. If p does lie on the dark side within the shadow zone, the color is set to a medium grey in line 91.

You will notice in the images above that there is a dark band within the rings. This is because Saturn’s rings have a void in that band: there are no particles there to reflect light; what you see is the background color, 'midnightblue', showing through. This creates a problem since the shadow color will overplot the background color in that void. Lines 93 and 94 reestablish it as 'midnightblue'.

Now that the band colors have been established, you can plot the rings. This is done by plotting short line segments. Lines 97-100 compute the starting location of the first segment. Referring to Figure 10-6, lines 100-101 determine if the segment is in front of the planet, in which case it is plotted. Lines 103-108 determine if it is behind the planet, in which case it is not plotted. This is done by calculating the distance c of the point’s global coordinates from the planet’s center. Line 107 says, if c is greater than the sphere’s radius times 1.075, then plot the segment. The factor of 1.075 is included to prevent the line segments from nibbling into the sphere’s edges. It is necessary to go through this logic; otherwise the front visible segments, which are within the radius of the sphere, won’t be plotted.

Two things can be noted regarding the above images produced by Listing 10-1. First is the color. The NASA photographic image shows a greyish hue, almost devoid of color. But many observers of Saturn have described it as having a golden hue, hence my choice of colors. As any photographer knows, capturing an object’s true colors in a photographic image is difficult; so much depends on the color of the incident light and the image-capturing medium. Perhaps it is best to rely on the observations of stargazers. If you do not agree with the colors in the images produced by Listing 10-1, you can tinker with them by altering the clr definitions in the program. The second thing to notice is the curvature of the shadow that follows the planet’s curvature in Figure 10-5. It shows that the shading algorithm works as expected.

Regarding use of the program, you can change the direction of the incident light in lines 24-26 and the angles of rotation in lines 32-34. Listing 10-1 takes a while to run so be patient.

1   """
2   SATURN
3   """
4  
5   import numpy as np
6   import matplotlib.pyplot as plt
7   from math import sin, cos, radians, sqrt
8  
9   plt.axis([0,150,100,0])
10  plt.axis('off')
11  plt.grid(False)
12
13  print('running')
14  #—————————————————parameters
15  g=[0]*3
16
17  xc=80 #———sphere center
18  yc=50
19  zc=0
20
21  rs=25 #———sphere radius
22
23  lx=-1 #———light ray unit vector components
24  ly=0
25  lz=0
26
27  IA=0
28  IB=.8
29  +n=2
30
31  Rx=radians(-20)
32  Ry=radians(0)
33  Rz=radians(30)
34
35  #————————same as SHADESPHERE—————–
36
37  #———————————————————rings
38  alpha1=radians(-10)
39  alpha2=radians(370)
40  dalpha=radians(.5)
41
42  r1=rs*1.5
43  r2=rs*2.2
44  dr=rs*.02
45  deltar=(r2-r1)/7 #———ring band width
46
47  #—————————————rotate ring point p which is at r, alpha
48  for r in np.arange(r1,r2,dr):
49      for alpha in np.arange(alpha1,alpha2,dalpha):
50          xp=r*cos(alpha)
51          yp=0
52          zp=-r*sin(alpha)
53          rotx(xc,yc,zc,xp,yp,zp,Rx)
54          xp=g[0]-xc
55          yp=g[1]-yc
56          zp=g[2]-zc
57          roty(xc,yc,zc,xp,yp,zp,Ry)
58          xp=g[0]-xc
59          yp=g[1]-yc
60          zp=g[2]-zc
61          rotz(xc,yc,zc,xp,yp,zp,Rz)
62          xpg=g[0]
63          ypg=g[1]
64
65  #—————————————————select ring band color
66      if r1 <= r < r1+1*deltar:
67          clr=(.63,.54,.18)
68      if r1+1*deltar <= r <= r1+2*deltar:
69          clr=(.78,.7,.1)
70      if r1+2*deltar <= r <= r1+3*deltar:
71          clr=(.95,.85,.1)
72      if r1+3*deltar <= r <= r1+4*deltar:
73          clr=(.87,.8,.1)
74      if r1+5*deltar <= r <= r1+7*deltar:
75          clr=(.7,.6,.2)
76
77  #———————————————————————shadow
78      magu=sqrt(lx*lx+ly*ly+lz*lz)
79      ux=-lx/magu
80      uy=-ly/magu
81      uz=-lz/magu
82      vx=xc-xpg
83      vy=yc-ypg
84      vz=zc-zpg
85      Bx=uy*vz-uz*vy
86      By=uz*vx-ux*vz
87      Bz=ux*vy-uy*vx
88      magB=sqrt(Bx*Bx+By*By+Bz*Bz)
89      if magB < rs: #—————————if in the shadow region
90          if vx*lx+vy*ly+vz*lz <= 0: #———if v points toward light source
91              clr=(.5,.5,.2) #———shadow color
92
93      if r1+4*deltar <= r <= r1+5*deltar: #———overplot empty band
94          clr='midnightblue' #———with background color
95
96  #——————————————————–plot line segment
97      if alpha == alpha1:
98          xstart=xpg
99          ystart=ypg
100     if zpg <= zc: #–front (z axis points into the screen)
101         plt.plot([xstart,xpg],[ystart,ypg],linewidth=2,color=clr)
102
103     if zpg >= zc: #–back
104         a=xpg-xc
105         b=ypg-yc
106         c=sqrt(a*a+b*b)
107         if c > rs*1.075: #——plot only the visible portion of rings
108             plt.plot([xstart,xpg],[ystart,ypg],linewidth=2,color=clr)
109         xstart=xpg
110         ystart=ypg
111
112 plt.show()
Listing 10-1

Program SATURN

10.2 Solar Radiation

This section illustrates a typical scenario: using Python to plot and label curves that represent mathematical functions. Here you plot Max Planck’s spectrum of radiation. You use it to represents the energy spectrum emitted by the Sun, calculate the Sun’s total power output, and the amount that reaches Earth, which is called the solar constant . The scientific aspects of this section are quite interesting, as is the history of their development. The major benefit from a Python programming aspect is seeing how the programs perform numerical integration, set up the plots, and display numerical data.

10.2.1 Photons and the Sun

The Sun, like all radiating bodies, emits electromagnetic energy in the form of photons. We know that photons are emitted at different frequencies or wavelengths, a wavelength being inversely proportional to frequency, as in
$$ lambda =frac{s_m}{v} $$
(10-5)
where λ is the wavelength, s m is the speed of light within the medium, and ν is the frequency of a wave travelling in that medium. Since we are concerned primarily with light travelling through empty space, (i.e. from the Sun to Earth), s m =c where c is the speed of light in empty space, Equation 10-5 thus becomes
$$ lambda =frac{c}{v} $$
(10-6)
A function such as solar power, when represented over a range of frequencies or wavelengths, is called a spectrum . In the case of electromagnetic radiation, we are mostly concerned with the power of light at different frequencies or equivalently, wavelengths. This is called a power spectrum . An example is the curve shown in Figure 10-8 where the power spectral density, often called simply the power spectrum, S(λ), is plotted vs. wavelength λ. This curve originated from Equation 10-7.
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig8_HTML.jpg
Figure 10-8

Max Planck’s Solar Spectrum

Most of the frequencies emitted by the Sun, which range from high frequency, short wavelength ultraviolet to low frequency, long wavelength infrared, are invisible to our human eyes. We are able to see only a small range of the spectrum which, fortunately for us, lies near the peak of the Sun’s emitted power spectrum. This must have pleased our hunter-gatherer ancestors since it enabled them to hunt and gather earlier and later in the day. While we can thank the shape of the Sun’s power spectrum for this, it is also a characteristic of our eyes’ biology which, if we believe Charles Darwin, probably evolved to be optimized at the frequencies near the Sun’s maximum power output.

10.2.2 Max Planck’s Black Body Radiation

As mentioned, light is photons. But what is a photon? We know photons are quantized forms of electromagnetic energy. But in the late 19th century, that was still a mystery. There were many attempts to explain the light spectrum that was emitted from heated materials. For example, when we heat up an iron poker, at first we don’t see any change in color but then, after a certain temperature is reached, we visually observe it glowing through a progression of colors: dull red, brighter red, orange, yellow, white, blue, and then violet. These colors correspond to different frequencies of the electromagnetic radiation emitted by the object. Early attempts to explain this phenomenon were based on the classical theory at that time called Maxwell’s Equations. These equations describe an electromagnetic field where the electromagnetic energy is assumed to be a smooth continuum. Despite many attempts, this approach failed to explain what was being observed.

Many scientists at the time struggled with this problem. Then in 1900, Max Planck, a German physicist, sent a postcard to a colleague. On the back he had written an equation that accurately described the spectrum. Plank’s breakthrough was to assume, contrary to the prevailing theories at the time, that the electromagnetic field was not a continuum of energy. Rather, he guessed that electromagnetic energy exists in discrete packets and not as a continuous field, as was assumed by Maxwell’s equations. This led to his breakthrough formulation, shown in Equation 10-7. He presented his idea to the German Physical Society on December 14, 1900, a date that has become known as the birth of quantum mechanics. His equation is known as the blackbody radiation formula . You will see more of it later.

In 1901, Planck published his results in an article in Annalen der Physik in which he hypothesized that electromagnetic energy could only be released by a source, such as the Sun, in the form of discrete packets of energy rather than as continuous waves. Since it was known that light exhibits wave characteristics, in 1905 Albert Einstein extended this idea by suggesting Planck’s discrete “packets” could only exist as discrete “wave-packets.” He called such a packet a Lichtquant or “light quantum.” Later, in 1928, Arthur Compton used the term “photon” which derives from Phos, the Greek word for light.

Planck also assumed that the source of the wave packets are thermally excited charges, each emitting a packet of electromagnetic energy, a photon, at a particular frequency. The more charges emitting photons at the same frequency, the greater the power of the emitted light at that frequency. He further theorized that the energy of a wave packet could only occur at specific fixed energy levels or states.

Returning to 1900, the equation Planck wrote on the back of a postcard, which predicts the power spectrum of light S(λ) emitted by a black body is
$$ Sleft(lambda 
ight)=frac{2pi {c}^2h}{lambda^5}frac{varepsilon }{e^{frac{hc}{lambda kT}}-1}kern1em J/s/{m}^3=W/{m}^3 $$
(10-7)
where c is the speed of light (m/s), h is Planck’s Constant (J·s), λ is the wavelength (m), k is Boltzman’s Constant (J/K), T is temperature (K), and ε is the emissivity of the radiating body’s surface. ϵ is essentially a measure of the effectiveness of a surface’s radiating ability. It can range from 0 to 1. As you might imagine, there was a lot of thought behind the development of this equation, which I won’t go into here.

Over the past 100+ years this relation has withstood the test of time and gives very accurate results. Displayed in Figure 10-8, it is often referred to as Planck’s black body radiation formula . It applies equally well to all radiating bodies as well as the Sun. Even though the Sun certainly doesn’t look like a black body, as far as its radiation characteristics are concerned it behaves like one—a very hot one. As an analogy, you might think of the Sun as being a very hot (about 5800°K) black stove glowing very brightly.

Figure 10-8 shows the solar output spectrum (red curve) of the Sun as predicted by Equation 10-7. This is called a power spectral density, or simply a power spectrum. Each point on the curve gives the power density S(λ) at a corresponding wavelength λ. The green band shown in the figure will be explained later.

10.2.3 The Sun’s Total Power Output

The quantity S(λ) displayed in Figure 10-8 is a power density . What is a power density and how does it differ from a simple power? Notice in Equation 10-7 that the units of S(λ) are power per cubic volume. These are the units of a density. You might think of this “density” as analogous to mass density that has units of mass per cubic volume. In the case of S(λ) you are dealing with a power density.

The feature of Equation 10-7 that makes the power spectrum resemble the Sun’s output, and not that of any other black body, is the temperature T. For the Sun, T is approximately 5800°K. To get the power emitted by the Sun, P(λ), over a bandwidth λ1 to λ2, it is necessary to sum S(λ) across that band. In calculus, this amounts to taking the integral of S vs. λ, which is equivalent to finding the area under the S(λ) curve between these limits.
$$ {P}_{lambda_1	o {lambda}_2}={int}_{lambda_1}^{lambda_2}Sleft(lambda 
ight) dlambda kern2.1em J/s/{m}^2=W/{m}^2 $$
(10-8)
With Equation 10-7 this becomes
$$ {P}_{lambda_1	o {lambda}_2}=2pi {c}^2hkern0.34em {int}_{lambda_1}^{lambda_2}frac{lambda^{-5}varepsilon }{e^{frac{hc}{lambda kT}}-1} dlambda kern0.72em J/s/{m}^2=W/{m}^2 $$
(10-9)

Equation 10-9 gives the power emitted by the Sun over the bandwidth λ1 to λ2. It equals the integral of S(λ) times the infinitesimally small bandwidth dλ. In other words, if you pick a point along the S(λ) curve, as shown in Figure 10-9, and multiply it by dλ and then sum all those values from λ1 to λ2, you would get the total electromagnetic power emitted by the wavelengths in the waveband λ1 to λ2. This is the area under the S(λ) curve from λ1 to λ2.

To get the power generated by the entire solar spectrum, you integrate Equation 10-9 from wavelengths beginning at λ=0 and extending to λ=. For those who prefer to integrate Equation 10-9 mathematically, I show how to do so in Appendix B. Integration is simply finding the area under the S(λ) curve. You can avoid the math by doing it numerically. To do so, replace the infinitesimally small wave band dλ with a small band of finite width ∆λ and replace the integral with a summation, as in
$$ Pleft(lambda 
ight)=2pi {c}^2hsum limits_{i=1}^{i=N}frac{1}{lambda_i^5}frac{varepsilon }{e^{frac{hc}{lambda_i kT}}-1}varDelta lambda kern0.84em J/s/{m}^2=W/{m}^2 $$
(10-10)
where i refers to the i th band centered at λ i and N is the number of bands of width ∆λ between λ i and λ N . A typical band of width ∆λ is illustrated in Figure 10-9. The width of the band shown is exaggerated for illustrative purposes. In reality, it should appear much narrower.
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig9_HTML.jpg
Figure 10-9

Numerical integration of power S(λ)dλ emitted by spectrum bandi across a .01 μm bandwidth at λi=1.5 (produced by Listing 10-2)

Equation 10-10 is an approximation to Equation 10-9 because it assumes the value of S(λ) is constant across the width of each band ∆λ. However, if ∆λ is chosen small enough, the curve S(λ i λ/2) → S(λ i + ∆λ/2) can be approximated by the constant value S(λ i ) across the bandwidth ∆λ, in which case the results can be quite accurate. With this simple integration scheme, the power in the band equals the band’s rectangular area. While there are more sophisticated integration schemes you could use, this one is simple, easy to program, and adequate for your purposes.

Let’s calculate the power P(λ) emitted by the wavelengths across the small band ∆λ. Figure 10-9 shows an enlargement of the band shown in Figure 10-8 centered at λ=1.5 um. This might be considered a typical band i in Equation 10-10. Listing 10-2 evaluates the power generated by the wavelengths across this bandwidth. The curve S(λ) has been generated according to Equation 10-7. According to this simplified integration scheme, the power generated by this band, which is just its rectangular area, is given by
$$ Pleft(lambda 
ight)=Sleft(lambda 
ight)varDelta lambda kern3em J/s/{m}^2=W/{m}^2 $$
(10-11)

In Listing 10-2, which plots Figure 10-9, the area of the band is calculated according to Equation 10-11. The magnitude of ∆λ is arbitrary. In the program, it is the parameter dla , which is set to .01x106 meters or .01 μm. Whether ∆λ is large or small, the power it emits will be the power radiated by the wavelengths across that bandwidth. Wider bandwidths will generate proportionally more power, narrower ones less. Later, when you do a numerical integration of the area under the entire S(λ) curve to get the total power radiated by the Sun across its entire spectrum, choosing a small value of ∆λ will lead to more accurate results.

In Figure 10-9, the band is shown at λ=1.5 um. The corresponding value of S, as calculated by the program, is 1.164x107 MW/m3. With a bandwidth of .01 μm, which equals 1.0x108 meters, the power generated by this band is (1.164x107)x(1x108)=.1164 MW/m2, about what a small power plant produces.

Note that the units of S(λ) will be consistent with those of the input parameters: speed of light, Planck’s Constant, Boltzman’s Constant, and wavelength λ. The units of these parameters should be consistent with one another. To avoid confusion, in this work you will keep all of these quantities in the spatial dimension of meters when evaluating Equation 10-7. S(λ) will then have the units (J/s)/m3, which is the same as W/m3. If output is needed in another power dimension, such as kW or MW, the conversion can be done after S(λ) has been evaluated by multiplying S(λ) in watts by 103 to get kilowatts or 106 to get megawatts. When calculating power emitted across a waveband, the width of that band ∆λ should also be in meters. For example, 1.5μm should be specified as 1.5x106m. Conversion from meters back to micrometers μm for display or other purposes later can be done by multiplying λ meters by 10+6. This is shown in Listing 10-2 in the section plot s curve in line lag=la*10**6.

In the figure, S i is shown with a value of 1.164x107 MW/m3. The S(λ) axis indicates a value of 11.64 MW/m3x106, which indicates that the value of 11.64 has been multiplied by 106 for display purposes. This would make its actual value 11.64x10+6, which equals the value calculated by the program. This is displayed on the plot as 1.164x10+7 MW/m3.

In Listing 10-2, which created Figure 10-9, the section plot S curve solves Equation 10-7 for values of wavelength la, which go from la=lamin to lamax in increments dla . The comments within the code trace the evolution of the units of S. As given by Equation 10-7, when the parameters are as indicated in section establish parameters, the units of s start off as Joules/second per cubic meter (remember s(λ) is a density). Since one Joule per second defines the watt, the units are watts per cubic meter. These are converted to megawatts per cubic meter and then scaled to be plotted against the vertical axis in the units (MW/m3)x106 as the variable sg. The 106 factor indicates the actual values have been multiplied by that amount. Next, the green band is plotted and the values of temperature and emissivity are displayed.

The value of S(λ) at λ=1.5 is calculated using Equation 10-7, converted to MW/m3, and then multiplied by the bandwidth dl=.01x106 to get pl MW/m2, the power within that bandwidth. The remainder of the program displays the data and cleans up the plot.

"""
BANDINTEGRAL
"""
import numpy as np
import matplotlib.pyplot as plt
#---------------------------------------------------------- set up axes
ymax=20
plt.axis([1.,2.,0,ymax])
plt.xlabel('Wavelength $lambda$ ($mu$m)')
plt.ylabel('S($lambda$) (MW/m$^{3}$) x 10$^{-6}$')
plt.grid(True)
plt.title('Max Planck's Solar Spectrum - Band Integral')
#------------------------------------------------ establish parameters
c=2.9979*(10.**8)           # speed of light in a vacuum m/s
h=6.63*(10.**-34)           # Planck's Constant J.s
kb=1.38*(10**-23)           # Boltzmann's Constant J/K
t=5800.                     # temperature K
e=1.0                       # emissivity
lamin=.01*10**-6            # starting wavelength m
lamax=2.*10**-6             # ending wavelength m
dla=.01*10**-6              # incremental wavelength m
#———————————————————————————————————————————— plot s curve
for la in np.arange(lamin,lamax,dla):
    a1=2.*np.pi*c*c*h/(la**5.)
    a2=h*c/(la*kb*t)
    sl=e*a1/(np.exp(a2)-1.)                 # J/s/m^3 = W/m^3
    sl=sl*10**-6                            # MW/m^3
    slg=sl*10**-6                           # scale plot at 10^-6 scale
    lag=la*10**6                            # scale to plot at 10^6 scale
    plt.scatter(lag,slg,s=1,color='r')
#——————————————————————————————————————————————— plot band
plt.plot([1.495,1.495],[0.,11.64],color='g')
plt.plot([1.4975,1.4975],[0.,11.64],color='g')
plt.plot([1.5,1.5],[0,11.64],color='g')
plt.plot([1.5025,1.5025],[0.,11.64],color='g')
plt.plot([1.5005,1.505],[0.,11.64],color='g')
#——————————————————————————————— plot temperature and emissivity
d=str(t)
plt.text(1.6,15,'T=')
plt.text(1.65,15,d)
plt.text(1.6,14,'e=')
d=str(e)
plt.text(1.65,14,d)
#———————————————————— calculate s and band power pl at lambda=1.5
la=1.5*10**-6
a1=2.*np.pi*c*c*h/(la**5.)
a2=h*c/(la*kb*t)
sl=e*a1/(np.exp(a2)-1.)  # J/s/m^3 = W/m^3
sl=sl*10**-6             # MW/m^3
dl=.01*10**-6            # bandwidth m
pl=sl*dl
#———————————————————————————————— plot results and labels
plt.plot([1.53,1.59],[11.6,11.6],'k')
plt.text(1.6,11.5,'si=')
d='%7.3e'%(sl)
plt.text(1.65,11.5,d)
plt.text(1.83,11.5,'MW/m^3')
plt.arrow(1.4,5,.085,0,head_width=.5,head_length=.01,linewidth=.2)
plt.arrow(1.6,5,-.085,0,head_width=.5,head_length=.01,linewidth=.2)
plt.text(1.15,5,'$Delta lambda$=')
dle='%7.3e'% (dl)
dls=str(dle)
plt.text(1.18,5,dls)
plt.text(1.35,5,'m')')
plt.text(1.145,4,'=')
dl=dl*10**6
dle='%7.3e'%(dl)
dls=str(dle)
plt.text(1.18,4,dls)
plt.text(1.35,4,'um')
plt.text(1.35,16.5,'s($lambda$)')
plt.text(1.52,2.5,'power$_{i}$=')
pl='%7.3e'%(pl)
pl=str(pl)
plt.text(1.65,2.5,pl)
plt.text(1.823,2.5,'MW/m^2')
plt.text(1.45,-1.1,'$lambda_{i}$=1.5')
plt.show()
Listing 10-2

Program BANDINTEGRAL

Next, let’s look at Max Planck’s entire black body spectrum as shown in Figure 10-8. It’s titled as “Max Planck’s Solar Spectrum” since the temperature used is that of the Sun, approximately 5800 ° K.

The program that produced this plot, Listing 10-3, follows the logic in the preceding program, Listing 10-2, but here you sum the individual band powers from λ=.01x106 to 10.x106 meters (.01μm to 10.μm) to get the area under the entire (almost) S(λ) curve. The band you looked at in Listing 10-2 is shown at λ=1.5 um.

The process used here is to simply advance along wavelengths, calculate the value of S(λ) at each wavelength, multiply it by ∆λ to get the power within that band, and then sum the power generated by each band in accordance with Equation 10-10. This will give you the total power emitted by all wavelengths.

You extend the range of integration to 10x106 meters in order to get a more accurate measure of the total power under the S(λ) curve. This will be the total spectral power emitted by each square meter of the Sun’s surface. Then you multiply that by the Sun’s spherical surface area to get the total power emitted by the Sun, which is known as the solar luminosity . In Figure 10-8, it is called the “total solar output.” As shown on the plot, its value as calculated by the program is 3.816x1026 watts. This is in close agreement with published values.

Many researchers use e=1.0 for emissivity, which is an idealization that assumes the Sun is a perfect radiator (you can assume it isn’t). Here you use an emissivity of e=.984. When you use Planck’s spectrum to calculate the solar constant, which has been measured by satellite (next section), you must either reduce the temperature of the Sun in your calculations or lower its emissivity to less than 1.0 in order to get the results to agree with measured values. If you choose to stay with a Sun temperature of 5800°K, then you must lower the emissivity to .984 in order to obtain agreement. Another option, as you will see, is to keep e=1.0 and lower the Sun’s temperature to 5777 ° K.

"""
PLANCKSSOLARSPECTRUM
"""
import numpy as np
import matplotlib.pyplot as plt
#—————————————————————————————————————————————————— set up axes
ymax=100
plt.axis([0,3,0,ymax])
plt.xlabel('Wavelength _ (_m)')
plt.ylabel('S(λ) (MW/m^{3}) x 10^-6')
plt.grid(True)
plt.title('Max Planck's Solar Spectrum')
#———————————————————————————————————————— establish parameters
c=2.9979*(10.**8)           # speed of light in a vacuum m/s
h=6.63*(10.**-34)           # Planck's Constant J.s
kb=1.38*(10**-23)           # Boltzmann's Constant J/K
e=.984                      # emissivity
t=5800.                     # K
lamin=.01*10**-6            # m
lamax=10.*10**-6            # m
dla=.01*10**-6              # m
st=0.                       # set area under s curve to zero
#—————————————————————————————— plot s curve and calculate area
for la in np.arange(lamin,lamax,dla):
    a1=2.*np.pi*c*c*h/(la**5.)
    a2=h*c/(la*kb*t)
    sl=e*a1/(np.exp(a2)-1.)                # W/m^3
    sl=sl*10**-6                           # MW/m^3
    bandarea=sl*dls                        # band area MW/m^2
    st=st+bandarea                         # sum band areas MW/m^2
    slg=sl*10**-6                          # scale to plot
    lag=la*10**6                           # scale to plot
    plt.scatter(lag,slg,s=1,color='r')
#—————————————————————————————————— multiply the Sun's surface area
ds=1.39*10**9                # Sun's diameter m
spas=np.pi*ds**2.            # Sun's spherical area m^2
to=spas*st                   # Sun's total output MW
to=to*10**6                  # Sun's total output W
#———————————————————————————————————————————————— plot results
plt.text(.8,58.,'5800')
plt.text(1.05,58, '°K')
plt.plot([.39,.39],[-0.,100.],'b–')
plt.plot([.7,.7],[-0.,100.],'b–')
plt.text(.3,-10,'.390')
plt.text(.6,-10,'.700')
plt.text(.15,90.,'UV')
plt.text(.8,90.,'long wave infrared')
plt.arrow(1.75,91.,.8,0.,head_width=1.,head_length=.1,color='r')
plt.text(1.2,40.,'total solar output =')
so='dd=str(so)
plt.text(2.1,40,dd)
plt.text(2.7,40,'W')
plt.text(1.2,34,'emissivity =')
e=str(e)
plt.text(1.8,34,e)
plt.text(.5,75.,'v')
plt.text(.53,70.,'i')
plt.text(.5,65.,'s')
plt.text(.53,60.,'i')
plt.text(.5,55.,'b')
plt.text(.53,50.,'l')
plt.text(.5,45.,'e')
plt.plot([1.49,1.49],[0.,11.61],color='g')
plt.plot([1.5,1.5],[0.,11.61],color='g')
plt.plot([1.51,1.51],[0.,11.61],color='g')
#—————————————————— calculate s at la=1.5x10^-6 m and band power pband
laband=1.5*10**-6
a1=2.*np.pi*c*c*h/(laband**5.)
a2=h*c/(laband*kb*t)
sband=a1/(np.exp(a2)-1.)
sband=sband*10**-12
pband=sband*dla # MW/sq meter
pband=pband*10**6 # W/sq meter
#———————————————————————————————————————————————— plot band
plt.plot([1.55,1.7],[12.5,15.],color='k')
plt.text(1.72,14.,' p=')
pband='pband=str(pband)
plt.text(1.9,14,pband)
plt.text(2.4,14,'MW/m^2')
plt.arrow(1.35,5,.1,0,head_width=1, head_length=.05, ec="k", fc="k")
plt.arrow(1.65,5,-.1,0,head_width=1, head_length=.05, ec="k", fc="k")
plt.text(.82,4.9,'Δλ = :01μm' )
plt.show()
Listing 10-3

Program PLANCKSSOLARSPECTRUM

10.3 Earth’s Irradiance

Figure 10-10 shows the spectrum of solar radiation that reaches Earth. Figure 10-11 shows the Earth orbiting the Sun. This is the model used to calculate the amount of the Sun’s total power output that is intercepted by Earth, the solar constant. The distance between the two orbs is an average of 1 AU, about 93,000,000 miles. It varies during an orbit. The circular disk labelled A p has an area equal to the Earth’s cross-section. The solar power intercepted by A p is responsible for heating the Earth.
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig10_HTML.jpg
Figure 10-10

Svpectrum of solar power reaching Earth, the Earth’s solar irradiance, produced by Listing 10-3, which has been modified by inclusion of the inverse square law

Notice how much lower the values are than in Figure 10-8. This is because the power intensity of the Sun’s output that reaches Earth and is intercepted by A p diminishes over the distance from Sun to Earth according to the inverse square law of
$$ {p}_p={p}_s{left(frac{r_s}{r_{es}}
ight)}^2 $$
(10-12)
where p s is the intensity of power at the Sun’s surface, p p is the intensity intercepted by A p , r s is the radius of the Sun, and r es is the distance from the Sun to the Earth. The total power intercepted by A p is thus
$$ {P}_p={A}_p{p}_p $$
(10-13)
$$ {P}_p={A}_p{p}_s{left(frac{r_s}{r_{es}}
ight)}^2 $$
(10-14)

When Equation 10-13 is included in Listing 10-3, the spectrum reduces to Figure 10-10. Again, notice how much lower the values are than in Figure 10-8 as a result of the inverse square law.

P p , which is the solar power reaching the top of the Earth’s atmosphere, is called the solar constant . Its value as measured by satellite is about 1361 W/m2. About 30% of this is reflected off the Earth’s surface and atmosphere by albedo effects such as snow, ice, clouds, water, etc. The remainder is absorbed by the Earth. Much of that is reradiated back into space, allowing the planet to reach a thermal equilibrium. The Earth is also a hot (warm) body and it exhibits its own thermal radiation out into space. But some of what should be reradiated is blocked by greenhouse gasses including CO2, contributing to global warming. All this is, as we know, being actively investigated by climate researchers.

10.3.1 The Earth Sun Model

Figure 10-11 shows the Earth orbiting the Sun and Listing 10-4 contains the code.
../images/456962_1_En_10_Chapter/456962_1_En_10_Fig11_HTML.jpg
Figure 10-11

The Earth-Sun Model produced by Listing 10-4

"""
EARTHSUN
"""
import matplotlib.pyplot as plt
import numpy as np
from math import radians, sin, cos, sqrt
plt.axis([-100,150,-100,150])
plt.grid(False)
plt.axis('off')
sfx=2.5/3.8
#———————————————————————background
for x in range(-100,150,2):
    for y in range(-100,150,2):
        plt.scatter(x,y,s=40,color='midnightblue')
phimin=0.
phimax=2.*np.pi
dphi=phimax/100.
rs=40.
re=20.
ys=15.
ye=2.
xos=50.
yos=0.
zos=0.
#———————————————————Sun's core
plt.scatter(xos,yos,s=4300,color='yellow')
#———————————————————Sun horizontals
rx=radians(20)
for ys in np.arange(-rs,rs,5):
    for phi in np.arange(phimin,phimax,dphi):
        rp=np.sqrt(rs*rs-ys*ys)
        xp=rp*np.sin(phi)
        yp=ys
        zp=rp*np.cos(phi)
        px=xos +sfx*xp*1. +yp*0. +zp*0.
        py=yos +xp*0. +yp*np.cos(rx) -zp*np.sin(rx)
        pz=zos +xp*0. +yp*np.sin(rx) +zp*np.cos(rx)
        if pz > 0 :
            plt.scatter(px,py,s=1,color='red')
#————————————————————Sun verticals
alphamin=0.
alphamax=2.*np.pi
dalpha=alphamax/30.
for alpha in np.arange(alphamin,alphamax,dalpha):
    for phi in np.arange(phimin,phimax,dphi):
        xp=rs*np.sin(phi)*np.sin(alpha)
        yp=rs*np.cos(phi)
        zp=rs*np.sin(phi)*np.cos(alpha)
        px=xos +sfx*(xp*1. +yp*0. +zp*0.)
        py=yos +xp*0. +yp*np.cos(rx) -zp*np.sin(rx)
        pz=zos +xp*0. +yp*(np.sin(rx)) +zp*np.cos(rx)
        if pz > 0 :
            plt.scatter(px,py,s=1,color='red')
#——————————————————————Earth's clouds
xoe=-50.
yoe=20.
zoe=-10.
plt.scatter(xoe,yoe,s=800,color='white')
#———————————————————— Earth horizontals
rx=20.*np.pi/180.
dphi=phimax/100.
for ys in np.arange(-re,re,2):
    for phi in np.arange(phimin,phimax,dphi):
        rp=np.sqrt(re*re-ys*ys)
        xp=rp*np.sin(phi)
        yp=ys
        zp=rp*np.cos(phi)
        px=xoe +sfx*(+xp*1. +yp*0. +zp*0.)
        py=yoe +xp*0. +yp*np.cos(rx) -zp*np.sin(rx)
        pz=zoe +xp*0. +yp*(np.sin(rx)) +zp*np.cos(rx)
        if pz > 0 :
            plt.scatter(px,py,s=.1,color='#add8e6')
#—————————————————————Earth verticals
alphamin=0.
alphamax=2.*np.pi
dalpha=alphamax/30.
for alpha in np.arange(alphamin,alphamax,dalpha):
    for phi in np.arange(phimin,phimax,dphi):
        xp=re*np.sin(phi)*np.sin(alpha)
        yp=re*np.cos(phi)
        zp=re*np.sin(phi)*np.cos(alpha)
        px=xoe +sfx*(xp*1. +yp*0. +zp*0.)
        py=yoe +xp*0. +yp*np.cos(rx) -zp*np.sin(rx)
        pz=zoe +xp*0. +yp*(np.sin(rx)) +zp*np.cos(rx)
        if pz > 0 :
            plt.scatter(px,py,s=.1,color='#add8e6')
plt.arrow(xos-rs*sfx-3,yos+2,xoe-(xos-rs*sfx)+re+3,yoe-yos-6.2,color='r',
                              head_length=4.,head_width=3.)
plt.text(-14,16,'1 AU',color='white')
plt.text(80,-29,'Sun',color='white')
plt.text(-84,10,'Earth',color='white')
#———————————————————————front orbit
deltamin=0.*np.pi/180.
deltamax=195.*np.pi/180.
ddelta=deltamax/60.
for delta in np.arange(deltamin,deltamax,ddelta):
    r=108./sfx
    xp=r*np.cos(delta)
    yp=0.
    zp=r*np.sin(delta)
    px=xos +sfx*(xp*1. +yp*0. +zp*0.)
    py=yos +xp*0. +yp*np.cos(rx) -zp*np.sin(rx)
    pz=zos +xp*0. +yp*(np.sin(rx)) +zp*np.cos(rx)
    plt.scatter(px,py,s=1,color='white')
#———————————————————————back orbit
deltamin=220.*np.pi/180.
deltamax=360.*np.pi/180.
for delta in np.arange(deltamin,deltamax,ddelta):
    r=108./sfx
    xp=r*np.cos(delta)
    yp=0.
    zp=r*np.sin(delta)
    px=xos +sfx*xp*1. +yp*0. +zp*0.
    py=yos +xp*0. +yp*np.cos(rx) -zp*np.sin(rx)
    pz=zos +xp*0. +yp*(np.sin(rx)) +zp*np.cos(rx)
    plt.scatter(px,py,s=1,color='white')
#———————————————————Ap disc
xoc=xoe+re*sfx
yoc=yoe-2.5
zoc=zoe
rc=.83*re
phi1=0
phi2=2*np.pi
dphi=(phi2-phi1)/200
ry=-25*np.pi/180
for phi in np.arange(phi1,phi2,dphi):
    xc=xoc
    yc=rc*np.sin(phi)
    zc=rc*np.cos(phi)
    px=xoc+zc*np.sin(ry)
    py=yoc+yc
    pz=zoc+zc*np.cos(ry)
    plt.scatter(px,py,s=.03 ,color='white')
plt.scatter(xoe+re*sfx,yoe-2,s=6,color='white')
plt.arrow(-20,60,(xoe+re*sfx)+24,(yoe+re/2)-60-2,color='white',
                             linewidth=.5,head_width=2.,head_length=3)
plt.text(-18,60,'A p ',color='white')
plt.show()
Listing 10-4

Program EARTHSUN

10.4 Summary

In this chapter you have seen some typical applications of Python graphics programming. In the first section you saw how relatively easy it is the create the image of Saturn. The planet’s body utilized the sphere and shading algorithms developed in earlier chapters; the bands were developed by constructing concentric rings flat in the x,z plane. The shadow algorithm required a bit of original geometry. The whole thing was then rotated in space about the x,y,z axes. In the section on solar radiation you learned about the physics of solar radiation, especially Max Planck’s black body radiation formula, and Python’s ability to construct technical illustrations. Of special note are the techniques used to scale variables for plotting. Then you learned how to build images such as Figure 10-8 which displays the model used to understand Earth’s solar irradiance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.148