MaplePrimes Posts

MaplePrimes Posts are for sharing your experiences, techniques and opinions about Maple, MapleSim and related products, as well as general interests in math and computing.

Latest Post
  • Latest Posts Feed
  • DataFrames: An example from the 2020 U.S. Presidential election

    (Or why DataFrames are more powerful and readable than spreadsheets.)

     

    In this example of working with DataFrames, the goal is to use a spreadsheet from a website, which contains polling data, to estimate the probability each of the two candidates from the major parties will win the US Presidential election in November.  I first tried doing the calculations with a spreadsheet, but I discovered DataFrames was far more powerful. Warning: This worksheet uses live data. Hence the outcome at the end of the worksheet is likely to change daily. A more extensive example with even more common DataFrame operations should be available soon.

     

    How the US Presidential election works - highly simplified version: In the US there are only two parties for which their candidate could win the election:  the Democratic party and Republican party. The Republican party is often referred to as the "Grand Old Party", or GOP. Each state executes its own election. The candidate who receives the most votes wins the states "electoral votes" (EV). The number of the electoral votes for each state is essentially proportional to the population of the state. A candidate who receives a total of 270 or more EVs out of 538, is declared the president of the US for the next term, which starts January 20 of 2021.

     

    Creating DataFrame from web based data:

    First I download the data from the website. It is a CSV spreadsheet.

     

    restart; interface(displayprecision = 3); interface(rtablesize = [6, 8]); web_data := Import("https://www.electoral-vote.com/evp2020/Pres/pres_polls.csv")

    _m2211970420352

    Each row contains information about a poll conducted in one of the states.  The first poll starts on row 2, hence the number of polls are:

    Npolls := upperbound(web_data, 1)-1

    572

    Now I want to create a new DataFrame containing only the most useful information. In web_data, many are the columns are not important. However I do want to keep the column label names from those columns I wish to retain.

     

    web_data_cols := [1, 3, 4, 5, 6]; column_labels := convert(web_data[1, web_data_cols], list)

    ["Day", "State", "EV", "Dem", "GOP"]

     

    Because  the first poll in web_data is labeled 2, I would like to relabel all the polls starting from 1

    row_labels := [seq(1 .. Npolls)]

     

    Creating a DataFrame from a Matrix or another DataFrame:  (with row labels and column labels)

     

    Now I can build the DataFrame that I will be working with:

     

    poll_data := DataFrame(web_data[2 .. (), web_data_cols], 'columns' = column_labels, 'rows' = row_labels)

    _m2211956910784

    What each column means

    * "Day" - day of the year in 2020 when the poll within the state was halfway completed. The larger the value, the more recent the poll.

    * "State" - the state in the US where the poll was conducted. The candidate that receives the most votes "wins the state".

    * "EV" - the number of electoral votes given to the candidate who receives the most votes within the state.

    * "Dem" - the percentage of people who said they are going to vote for the candidate from the Democratic party.

    * "GOP" - the percentage of people who said they are going to vote for the candidate from the Republican party.

    Sorting:

    By using the sort function, using the `>` operator, I can see which polls are the more recent. (If you run the worksheet yourself, the outcome will change as more polls are added to the website spreadsheet.)

    poll_data := sort(poll_data, "Day", `>`)

    _m2211960016288

     

    Selecting Unique entries - by column values:

    For the my simple analysis, I will use only the most recent poll, one from each state. Hence, using AreUnique, I can pull the first row that matches a state name. This new DataFrame called states.

     

    states := poll_data[AreUnique(poll_data["State"])]

    _m2211969565344

    (Note, one of the "states" is the District of Columbia, D.C., which is why there are 51 rows.)

     

    Removing a column: (and relabeling rows)

    This next example isn't necessary, but shows some of the cool features of DataFrames.

     

    Since there is only 1 entry per state, I'm going to remove the "State" column and relabel all the rows with the state names

    state_names := convert(states["State"], list); states := DataFrame(Remove(states, "State"), 'rows' = state_names)

    2

    _m2211957755840

     

    Indexing by row labels:


    This allow me to to display information by individual states. What is the data for California, Maine and Alaska?

    states[["California", "Maine", "Alaska"], () .. ()]

    _m2211977321984

     

    Mathematics with multiple-columns:

     

    My preference is to work with fractions, rather than percentages. Hence I want all the values in the "Dem" and "GOP" to be divided by 100 (or multiplied by 1/100).  Treating each column like a vector, the multiplication is performed individually on each cell. This is what the tilda, "~", symbol performs.

    states[["Dem", "GOP"]] := `~`[`*`](states[["Dem", "GOP"]], 1/100.); states

    _m2211957755840

     

    Mathematics: using a function to calculate a column

     

    For the next action, I want to use the power of the Statistics package to create a "probability of winning the state" function.

     

    For simplicity, I will assume the outcome of the voting in a state is purely random, but is conditional to popularity of each candidate as measured by the polls. I'll assume the likelihood of an outcome follows a normal (Gaussian) distribution with the peak being at point where the difference of the polling of the two candidates is zero. (Note, other than 2016, where there was an unusually larger percentage of undecided voters on election day, this simple model is reasonable accurate. For example, in 2012, of the states which appeared to be the "closest", the winner over-performed his polling in half of them, and under-performed in the other half with a mean difference of nearly zero.)  From previous elections, the standard deviation of differences between polling values and the actual outcome is at most 0.05, however, it does increase with the fraction of undecided voters.

     

    To mathematically model this situation, I have chosen to use the "Cumulative Density Function" CDF in the Statistics package. It will calculate the probability that a candidate polling with fraction f1 wins the election if the other candidate is polling with fraction f2.  The variable u is the fraction of undecided voters. It is included in the calculation to increase the spread of the possible outcomes.

     

    win_prob := Statistics:-CDF(Statistics:-RandomVariable(Normal(0., 0.5e-1+(1/4)*u)), f1-f2)

    1/2+(1/2)*erf((1/2)*(f1-f2)*2^(1/2)/(0.5e-1+(1/4)*u))

     

    Converting this expression into a function using the worst named function in Maple, unapply:

    win_prob_f := unapply(evalf(win_prob), [f1, f2, u])

    proc (f1, f2, u) options operator, arrow; .5000000000+.5000000000*erf(.7071067810*(f1-1.*f2)/(0.5e-1+.2500000000*u)) end proc

     

    Now I can calculate a DataFrames column of the "win probability", in this case, for the candidate from the Democratic platy. By apply the function, individually, using the columns "Dem" and "GOP", I produce:

    dem_win_prob := `~`[win_prob_f](states["Dem"], states["GOP"], `~`[`-`](1, `~`[`+`](states["Dem"], states["GOP"])))

    _m2212010910496

    Appending a column:

     

    I can add this column to the end of the states with the label "DemWinProb":

     

    states := Append(states, dem_win_prob, label = "DemWinProb")

    _m2212009017568

     

    Mathematics of adding the entries of a column:

     

    How many electoral votes are available? add them up.

    Total_EV := add(states["EV"])

    538

     

    While the number of EV a candidate wins is discrete, I can use the "win probability" from each state to estimate the total number of EV each of the candidates might win. This means adding up number of EV in each state times, individually, the probability of winning that state:

    Dem_EV := round(add(`~`[`*`](states["EV"], states["DemWinProb"])))

    354

    Currently, the candidate from the Democratic party is likely to win more then 300 electoral vtes.

     

    What about for the candidate from the Republican / "GOP" party?

    gop_win_prob := `~`[win_prob_f](states["GOP"], states["Dem"], `~`[`-`](1, `~`[`+`](states["Dem"], states["GOP"]))); GOP_EV := round(add(`~`[`*`](states["EV"], gop_win_prob)))

    184

    Summing the two EV values, we obtain the total number of electoral votes.

    Dem_EV+GOP_EV

    538

      NULL

     

    Download DataFrames_Example.mw

    Hi,
    Some people using the Windows platform have had problems installing MapleCloud packages, including the Maplesoft Physics Updates. This problem does not happen in Macintosh or Linux/Unix, also does not happen with all Windows computers but with some of them, and is not a problem of the MapleCloud packages themselves, but a problem of the installer of packages.

    I understand that a solution to this problem will be presented within an upcoming Maple dot release.

    Meantime, there is a solution by installing a helper library; after that, MapleCloud packages install without problems in all Windows machines. So whoever is having trouble installing MapleCloud packages in Windows and prefers not to wait until that dot release, instead wants to install this helper library, please email me at physics@maplesoft.com

    Edgardo S. Cheb-Terrab
    Physics, Differential Equations and Mathematical Functions, Maplesoft

    Caution, certain kinds of earlier input can affect the results from using the 2D Input syntax for operator assignment.

    kernelopts(version)

    `Maple 2020.1, X86 64 LINUX, Jun 8 2020, Build ID 1474533`

    restart

    f := proc (x) options operator, arrow; sqrt(x) end proc


    The following now produces a remember-table assignment,
    instead of assigning a procedure to name f, even though by default
         Typesetting:-Settings(functionassign)
    is set to true.

    "f(x):=x^(2)*sin(x)"

    x^2*sin(x)

    f(t)

    t^(1/2)

    f(1.4), 1.4^2*sin(1.4)

    1.183215957, 1.931481471

    restart

    NULL


    With the previous line of code commented-out the following
    line assigns a procedure to name f, as expected.

    If you uncomment the previous line, and re-execute the whole
    worksheet using !!! from the menubar, then the following will
    do a remember-table assignment instead.

    "f(x):=x^(2)*sin(x)"

    proc (x) options operator, arrow, function_assign; x^2*sin(x) end proc

    f(t)

    t^2*sin(t)

    f(1.4), 1.4^2*sin(1.4)

    1.931481471, 1.931481471

    ``

    Download operator_assignment_2dmath.mw

    HI,
     

    This post concerns the simulation of a physical system whose behavior is governed by ODEs.
    It is likely that some people will think that all which follows is nothing but embellishments  or a waste of time.
    And in some sense they will be right.
    I was thinking the same until I received some sharp remarks at the occasion of a few presentations of my works. 
    So experience has proven me that doing a presentation in front of project managers with only 2D curves often leads to smiles, not to speak about those who raise their eyes to heaven in front of the poverty of the slides. 
    Tired of this attitude, I decided to replace these 2D curves with a short film, which of course does not reveal more than what these 2D curves were already revealing, but which is pretty enough for the financing keeps going on.

    For those of you who might regret this situation, just consider this work as a demonstration of the capabilities of Maple in 3D rendering.


    PS: all the display outputs have been removed to avoid loading an unnecessary huge file.
          The two last commands must be uncommented to play the animation.

     

    Download ODE_Movie.mw

     

    Newton raphson method is used for optimization of functions and is based on taylor series expansion. Here is the code for a three level newton raphson method.
     

    restart; with(Student[MultivariateCalculus]); ff := proc (xx) xx^3-2*xx+2 end proc; ii := 0; XX[ii] := 2; while ii < 25 do GR := Gradient(ff(xx), [xx] = [XX[ii]]); GR1 := evalf(GR[1]); HESS := Student[VectorCalculus]:-Hessian(ff(xx), [xx] = [XX[ii]]); HESS1 := evalf(HESS[1]); YY[ii] := XX[ii]-GR1[1]/HESS1[1]; GR := Gradient(ff(xx), [xx] = [YY[ii]]); GR1 := evalf(GR[1]); HESS := Student[VectorCalculus]:-Hessian(ff(xx), [xx] = [YY[ii]]); HESS1 := evalf(HESS[1]); ZZ[ii] := YY[ii]-GR1[1]/HESS1[1]; GR := Gradient(ff(xx), [xx] = [ZZ[ii]]); GR1 := evalf(GR[1]); HESS := Student[VectorCalculus]:-Hessian(ff(xx), [xx] = [ZZ[ii]]); HESS1 := evalf(HESS[1]); ii := ii+1; XX[ii] := ZZ[ii-1]-GR1[1]/HESS1[1]; printf("%a\n", XX[ii]) end do

    .8180854533
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808
    .8164965808

     

    ff(.8164965808)

    .911337892

    (1)

    with(Optimization); Minimize(xx^3-2*xx+2, xx = -2 .. 2)

    [HFloat(0.9113378920963653), [xx = HFloat(0.8164965785244629)]]

    (2)

    NULL


     

    Download THREE_LEVEL_NEWTON_RAPHSON_METHOD1.mw

    What are the things you most like to see improved/add to next version of Maple? 

    This is my list for a starter:

    1.  Improve the debugger. Debugger is very useful but needs more work. At least be able to see code listing in larger view as one steps in for example. See Matlab debugger for inspiration.

    2.  Improve Latex. It still does not do fractions well. Posted about this before.

    3. Eliminate hangs when using timelimit(). On long runs, random hangs happen when timelimit() do not expire as requested. Posted about this before.

     

     

    In the present work we are going to demonstrate the importance of the study of vector analysis, with modeling and simulation criteria, using the MapleSim scientific software from MapleSoft. Nowadays, the majority of higher education centers direct their teaching of vector analysis in an abstract way and there are few or no teachers who carry out applications using modeling and simulation. (In spanish)

    IPN_CICATA_2020.pdf

    Expo_MapleSim_CICATA.zip

     

    We have just released an update to Maple, Maple 2020.1.1. This update includes the following:

    • Correction to a problem that occurred when printing or exporting documents to PDF. If the document included a 3-D plot, nearby text was sometimes missing from the printed/exported document.
    • Correction to an issue that prevented users from installing between-release updates to the Physics package

    This update is available through Tools>Check for Updates in Maple, and is also available from our website on the Maple 2020.1.1 download page. If you are a MapleSim user, you can obtain this update from the corresponding MapleSim menu or MapleSim 2020.1.1  download page.

    In particular, please note that this update fixes the problems reported on MaplePrimes in Maple 2020.1 issue with print to PDF  and installing the Maplesoft Physics updates. As always, we appreciate the feedback.

    The strandbeest is a walking machine developed by Theo Jansen. Its cleverly designed legs consist of single-degree-of-freedom linkage mechanisms, actuated by the turning of a wind-powered crankshaft.

    His working models are generally large - something of the order of the size of a bus. Look for videos on YouTube.  Commercially made small toy models are also available.  This one sells for under $10 and it's fun to assemble and works quite well. Beware that the kit consists of over 100 tiny pieces - so assembling it is not for the impatient type.

    Here is a Maple worksheet that produces an animated strandbeest. Link lengths are taken from Theo Jansen's video (go to his site above and click on Explains) where he explains that he calculated the optimal link lengths by applying a genetic algorithm.

    Here is a Maple animation of a single leg.  The yellow disk represents the crankshaft.

    And here are two legs working in tandem:

    Here is the complete beest, running on six legs. The crankshaft turns at a constant angular velocity.

    The toy model noted above runs on twelve legs for greater stability.

    Download the worksheet: strandbeest.mw

     

    This may be of interest to anyone curious about why the effective area of an isotropic antenna is λ^2/4π.


     

    Friis Transmission Equation

    NULL

    Initialise

       

    NULL``

    The Hertzian Dipole antenna

     

    The Hertzian Dipole is a conceptual antenna that carries a constant current along its length.

     

     

    By laying a number of these small current elements end to end, it is possible to model a physical antenna (such as a half-wave dipole for example).  But since we are only interested in obtaining an expression for the effective area of an Isotropic Antenna (in order to derive The Friis Transmission Equation) the Hertzian Dipole will be sufficient for our needs.``

    NULL

    ``

    Maxwell's Equations

     

    Since the purpose of a radio antenna is to either launch or to receive radio waves, we know that both the antenna, and the space surrounding the antenna, must satisfy Maxwell's Equations. We define Maxwell's Equations in terms of vector functions using spherical coordinates:

     

    Maxwell–Faraday equation:

    Maxwell_1 := Curl(E_(r, theta, `&varphi;`, t)) = -mu*(diff(H_(r, theta, `&varphi;`, t), t))

    Physics:-Vectors:-Curl(E_(r, theta, varphi, t)) = -mu*(diff(H_(r, theta, varphi, t), t))

    (3.1)

    Ampère's circuital law (with Maxwell's addition):

    Maxwell_2 := Curl(H_(r, theta, `&varphi;`, t)) = J_(r, theta, `&varphi;`, t)+epsilon*(diff(E_(r, theta, `&varphi;`, t), t))

    Physics:-Vectors:-Curl(H_(r, theta, varphi, t)) = J_(r, theta, varphi, t)+varepsilon*(diff(E_(r, theta, varphi, t), t))

    (3.2)

    Gauss' Law:

    Maxwell_3 := Divergence(E_(r, theta, `&varphi;`, t)) = rho/epsilon

    Physics:-Vectors:-Divergence(E_(r, theta, varphi, t)) = rho/varepsilon

    (3.3)

    Gauss' Law for Magnetism:

    Maxwell_4 := Divergence(H_(r, theta, `&varphi;`, t)) = 0

    Physics:-Vectors:-Divergence(H_(r, theta, varphi, t)) = 0

    (3.4)

    Where:

            E is the electric field strength [Volts/m]

            H is the magnetic field strength [Amperes/m]

            J is the current density (current per unit area) [Amperes/m2]

            ρ is the charge density (charge per unit volume) [Coulombs/m3]

            ε is Electric Permittivity

            μ is Magnetic Permeability

    NULL

    Helmholtz decomposition

     

    The Helmholtz Decomposition Theorem states that providing a vector field, (F) satisfies appropriate smoothness and decay conditions, it can be decomposed as the sum of components derived from a scalar field, (Φ) called the "scalar potential", and a vector field (A) called the "vector potential".

     

    F = -VΦ + V×A

     

    And that the scalar (Φ) and vector (A) potentials can be calculated from the field (F) as follows (image from https://en.wikipedia.org/wiki/Helmholtz_decomposition):

     

    Where:

            r is the vector from the origin to the observation point (P) at which we wish to know the scalar or vector potential.

            r' is the vector from the origin to the source of the scalar or vector potential (i.e. a point on the Hertzian Dipole antenna).

            V'·F(r')  is the Divergence of the vector field (F) at source position r'.

            V'×F(r')  is the Curl of the vector field (F) at source position r'.

     

     

    Calculating the Scalar Potential for the magnetic Field, H

     

    We know that the Divergence of the magnetic field (H) is zero:

    Maxwell_4

    Physics:-Vectors:-Divergence(H_(r, theta, varphi, t)) = 0

    (4.1.1)

    And so the magnetic field (H) must have a scalar vector potential of zero:

    `&Phi;__H` := 0

    0

    (4.1.2)

     

    Calculating the Vector Potential for the magnetic Field, H

     

    We know that the Curl of the magnetic field (H) is equal to the sum of current density (J) and the rate of change of the electric filled (E):

    Maxwell_2

    Physics:-Vectors:-Curl(H_(r, theta, varphi, t)) = J_(r, theta, varphi, t)+varepsilon*(diff(E_(r, theta, varphi, t), t))

    (4.2.1)

    Since the Hertzian Dipole is a conductor, we need only concern ourselves with the current density (J) when calculating the vector potential (A). Integrating current density (J) over the volume of the antenna, is equivalent to integrating current along the length of the antenna (L).

     

    We know that Maxwell's Equations can be solved for single frequency (monochromatic) fields, so we will excite our antenna with a single frequency current:

    "`I__antenna`(t):=`I__0`*(e)^(j*omega*t);"

    proc (t) options operator, arrow, function_assign; Physics:-`*`(I__0, exp(Physics:-`*`(I, omega, t))) end proc

    (4.2.2)

    We can simplify the integral for the vector potential (A) by recognising that:

     

    1. 

    Our observation point (P) will be a long way from the antenna and so (r) will be very large.

    2. 

    The length of the antenna (L) will be very small and so (r') will be very small.

     

    Since |r|>>|r'|, we can substitute |r-r'| with r.

     

    Because we have decided that the observation point at r will be a long way from the antenna, we must allow for the fact that the observed antenna current will be delayed.  The delay will be equal to the distance from the antenna to the observation point |r-r'| (which we have simplified to r), divided by the speed of light (c).  The time delay will therefore be approximately equal to r/c and so the observed antenna current becomes:

    "`I__observed`(t):=`I__0`*(e)^(j*omega*(t-r/(c)));"

    proc (t) options operator, arrow, function_assign; Physics:-`*`(I__0, exp(Physics:-`*`(I, omega, Physics:-Vectors:-`+`(t, -Physics:-`*`(r, Physics:-`^`(c, -1)))))) end proc

    (4.2.3)

     

    Since the length, L of the antenna will be very small, we can assume that the current is in phase at all points along its length.  Working in the Cartesian coordinate system, the final integral for the vector potential for the magnetic field is therefore:

    A__H_ := (int(I__0*exp(I*omega*(t-r/c))*_k/r, z = -(1/2)*L .. (1/2)*L))/(4*Pi)

    (1/4)*I__0*exp(I*omega*(t-r/c))*_k*L/(Pi*r)

    (4.2.4)

     

    We will now convert to the spherical coordinate system, which is more convenient when working with radio antenna radiation patterns:

    The radial component of the observed current (and therefore vector potential), will be at a maximum when the observer is on the z-axis (that is when θ=0 or θ=π) and will be zero when the observer is in the x-y-plane:

    A__Hr := (A__H_._k)*cos(theta)

    (1/4)*I__0*exp(I*omega*t-I*omega*r/c)*L*cos(theta)/(Pi*r)

    (4.2.5)

    The angular component of the observed current (and therefore vector potential), in the θ direction will be zero when the observer is on the z-axis (that is when θ=0 or θ=π) and will be at a maximum when the observer is in the x-y-plane:

    `A__H&theta;` := -(A__H_._k)*sin(theta)

    -(1/4)*I__0*exp(I*omega*t-I*omega*r/c)*L*sin(theta)/(Pi*r)

    (4.2.6)

    Since the observed current (and therefore vector potential) flows along the z-axis, there will be no variation in the Ï• direction.  That is to say, that varying Ï• will have no impact on the observed vector potential.

    `A__H&varphi;` := 0

    0

    (4.2.7)

    And so the vector potential for the magnetic field (H) expressed using spherical coordinate system is:

    A__H_ := A__Hr*_r+_theta*`A__H&theta;`+`A__H&varphi;`*`_&varphi;`

    (1/4)*I__0*exp(I*omega*t-I*omega*r/c)*L*cos(theta)*_r/(Pi*r)-(1/4)*I__0*exp(I*omega*t-I*omega*r/c)*L*sin(theta)*_theta/(Pi*r)

    (4.2.8)

    NULLNULL

    Calculating the Magnetic Field components

     

    The Helmholtz Decomposition Theorem states that providing a vector field (F) satisfies appropriate smoothness and decay conditions, it can be decomposed as the sum of components derived from a scalar field (Φ) called "scalar potential", and a vector field (A) called the vector potential.

     

    F = -VΦ + V×A

    NULL

    And so the magnetic field, H will be:

    NULL

    H_ = -(Gradient(`&Phi;__H`))+Curl(A__H_)

    H_ = ((1/4)*I)*I__0*L*exp(I*omega*t-I*omega*r/c)*sin(theta)*omega*_phi/(c*Pi*r)+(1/4)*I__0*L*exp(I*omega*t-I*omega*r/c)*sin(theta)*_phi/(Pi*r^2)

    (4.3.1)

    We see that the magnetic field comprises two components, one is inversely proportional to the distance from the antenna (r) and the other falls off with r2.  Since we are interested in the far-field radiation pattern for the antenna, we can ignore the r2 component and so the expression for the magnetic field reduces to:

    H_ := I*omega*I__0*L*exp(I*omega*(t-r/c))*sin(theta)*_phi/(4*Pi*c*r)

    ((1/4)*I)*omega*I__0*L*exp(I*omega*(t-r/c))*sin(theta)*_phi/(Pi*c*r)

    (4.3.2)

    We can further simplify by substituting ω/c for 2π/λ:``

    H_ := (I*2)*Pi*L*I__0*exp(I*omega*t-(I*2)*Pi*r/lambda)*sin(theta)*_phi/(4*Pi*lambda*r)

    ((1/2)*I)*L*I__0*exp(I*omega*t-(2*I)*Pi*r/lambda)*sin(theta)*_phi/(lambda*r)

    (4.3.3)

    ````

    ````

     

    Calculating the Poynting Vector

     

    We know that the magnitude of the Poynting Vector (S) can be calculated as the cross product of the electric field vector (E) and the magnetic field vector (H) :

            S = -E x H which is analogous to a resistive circuit where power is the product of voltage and current: P=V*I.

    We also know that the impedance of free space (Z) can be calculated as the ratio of the electric field (E) and magnetic field (H) vectors: Z = E /H = "sqrt((mu)/(`&epsilon;`))."

    This is analogous to a resistive circuit where resistance is the ratio of voltage and current: R=V/I.

     

    This provides two more methods for calculating the Poynting Vector (S):

            S = -E·E/Z which is analogous to a resistive circuit where power, P=V2/R, and:

            S = -H·H*Z which is analogous to a resistive circuit where power, P=I2R.

     

    Since we have obtained an expression for the magnetic field vector (H), we can derive an expression for the Poynting Vector (S):

    S_ = -(H_.H_)*Z*_r

    S_ = (1/4)*L^2*I__0^2*(exp(I*omega*t-(2*I)*Pi*r/lambda))^2*sin(theta)^2*Z*_r/(lambda^2*r^2)

    (5.1)

    We can separate out the time variable part to yield:

    S_ := S__0*(exp(I*omega*t-(I*2)*Pi*r/lambda))^2*_r

    S__0*(exp(I*omega*t-(2*I)*Pi*r/lambda))^2*_r

    (5.2)

    Where:

    S__0 := L^2*I__0^2*sin(theta)^2*Z/(4*lambda^2*r^2)

    (1/4)*L^2*I__0^2*sin(theta)^2*Z/(lambda^2*r^2)

    (5.3)

    And we can visualise this radiation pattern using Maple's plotting tools:

    AntennaAxis := arrow(`<,>`(0, 0, -1), `<,>`(0, 0, 1), difference, color = "LightSteelBlue")``

    AntennaPattern := plot3d(sin(theta)^2, phi = 0 .. 2*Pi, theta = 0 .. Pi, coords = spherical, scaling = constrained, size = [800, 800], labels = [x, y, z], title = ["The Electromagnetic radiation pattern of a Hertzian Dipole\n\nThe blue arrow represents the axis of the antenna", font = [Times, bold, 20]])
    ``

    display(AntennaAxis, AntennaPattern, scaling = constrained, axes = frame)

     

    So the Hertzian Dipole produces a electromagnetic radiation pattern with a pleasing doughnut shape :-)``

    NULL``

    Calculating Antenna Gain

     

    We can calculate the total power radiated by the Hertzian Dipole by integrating the power flux density over all solid angles dΩ=sin(θ) dθ dφ.  Since we have expressed power flux density in terms of watts per square meter, we multiply the solid angle by r2 to convert the solid angle expressed in steradians into an area expressed in m2.

    NULL

    P__tx := int(int(S__0*r^2*sin(theta), theta = 0 .. Pi), phi = 0 .. 2*Pi)

    (2/3)*L^2*I__0^2*Z*Pi/lambda^2

    (6.1)

    We can now use this power to calculate the power flux density that would be produced by an isotropic antenna by dividing the total transmitted power by the area of a sphere with radius r:

    S__Isotropic := P__tx/(4*Pi*r^2)

    (1/6)*L^2*I__0^2*Z/(lambda^2*r^2)

    (6.2)

    ``

    ``

    The Gain of the Hertzian Dipole is defined as the ratio between the maximum power flux density produced by the Hertzian Dipole and the maximum power flux density produced by the isotropic antenna:

    G__HertzianDipole := S__0/S__Isotropic

    (3/2)*sin(theta)^2

    (6.3)

    AntennaAxis := arrow(`<,>`(-1, 0), `<,>`(1, 0), difference, color = "LightSteelBlue")

    Gain := polarplot(G__HertzianDipole, theta = -Pi .. Pi, axis[radial] = [color = "Blue"], angularorigin = top, angulardirection = clockwise, size = [800, 800], labels = [x, z], title = ["The Gain of a Hertzian Dipole over an isotropic antenna  \n\nThe blue arrow represents the axis of the antenna", font = [Times, bold, 20]])

    display(AntennaAxis, Gain, scaling = constrained, axes = frame)

     

    ````

    ````

    Calculating Radiation Resistance

     

    The input impedance of the Hertzian Dipole will have both a real and a reactive part.  The reactive part will be associated with energy storage in the near field and will not contribute to the Poynting Vector in the far-field.  For an ideal antenna (with no resistive power loss) the real part will be responsible for the radiated power:

    P__tx = I__0^2*R__rad

    (2/3)*L^2*I__0^2*Z*Pi/lambda^2 = I__0^2*R__rad

    (7.1)

    R__rad := solve((2/3)*L^2*I__0^2*Z*Pi/lambda^2 = I__0^2*R__rad, R__rad)

    (2/3)*L^2*Z*Pi/lambda^2

    (7.2)

    ````

    ``

    Calculating the power received by a Hertzian Dipole

     

    If an electromagnetic field (E) is incident on the Hertzian Dipole antenna, it will generate an Electro-Motive Force (EMF) at the antenna terminals.  The EMF will be at a maximum when the transmitter is on the x-y-plane (that is when θ=π/2) and will be zero when the transmitter is on the z-axis.

     

    For and incident E-field:

    E := E__0*exp(I*omega*t)

    E__0*exp(I*omega*t)

    (8.1)

    The z-axis component will be:

    E__z := E*sin(theta)

    E__0*exp(I*omega*t)*sin(theta)

    (8.2)

    The z-axis component of the E-field will create an EMF at the antenna terminals that will draw charge out of the receiver to each tip of the antenna. We can calculate the work done per unit charge by integrating the z-axis component of (E) over the length of the antenna (L):

    V__emf := int(E__z, z = -(1/2)*L .. (1/2)*L)

    E__0*exp(I*omega*t)*sin(theta)*L

    (8.3)

    In order to extract the maximum possible power from the antenna, we will form a conjugate match between the impedance of the antenna and the load.  This means that the load resistance must be the same as the radiation resistance of the antenna.  The voltage developed across the load resistance will therefore be half of the open circuit EMF:

    V__pd := (1/2)*V__emf

    (1/2)*E__0*exp(I*omega*t)*sin(theta)*L

    (8.4)

    And so the power delivered to the load will be:

    P__rx := V__pd^2/R__rad

    (3/8)*E__0^2*(exp(I*omega*t))^2*sin(theta)^2*lambda^2/(Pi*Z)

    (8.5)

    NULL

    ``

    Calculating the Effective area of an Isotropic Antenna

     

    We can also calculate the power received by the Hertzian Dipole by multiplying the power flux density arriving at the antenna with the effective area of an isotropic antenna and the gain of the Hertzian Dipole relative to an isotropic antenna:

    P__rx = G__HertzianDipole*A__Isotropic*S__rx

    (3/8)*E__0^2*(exp(I*omega*t))^2*sin(theta)^2*lambda^2/(Pi*Z) = (3/2)*sin(theta)^2*A__Isotropic*S__rx

    (9.1)

    We can express the incident power flux density in terms of electric field strength and wave impedance:

    subs(S__rx = E^2/Z, (3/8)*E__0^2*(exp(I*omega*t))^2*sin(theta)^2*lambda^2/(Pi*Z) = (3/2)*sin(theta)^2*A__Isotropic*S__rx)

    (3/8)*E__0^2*(exp(I*omega*t))^2*sin(theta)^2*lambda^2/(Pi*Z) = (3/2)*sin(theta)^2*A__Isotropic*E__0^2*(exp(I*omega*t))^2/Z

    (9.2)

    Rearranging, we obtain an expression for the effective area of the isotropic antenna:

    A__Isotropic := solve((3/8)*E__0^2*(exp(I*omega*t))^2*sin(theta)^2*lambda^2/(Pi*Z) = (3/2)*sin(theta)^2*A__Isotropic*E__0^2*(exp(I*omega*t))^2/Z, A__Isotropic)

    (1/4)*lambda^2/Pi

    (9.3)

    NULL

    ``

    The Friis Transmission Equation

     

    P__tx := 'P__tx'

    We can calculate the power flux density that would be produced by an isotropic antenna at a distance r from the antenna by dividing the total transmitted power Ptx by the area of a sphere with radius r:

    P__tx/(4*Pi*r^2)

    (1/4)*P__tx/(Pi*r^2)

    (10.1)

    And so the power flux density that would be produced by an antenna with gain Gtx is:

    S__tx := (1/4)*G__tx*P__tx/(Pi*r^2)

    (1/4)*G__tx*P__tx/(Pi*r^2)

    (10.2)

    We can calculate the power received by an isotropic antenna by multiplying the power flux density incident onto the antenna with the effective area of an isotropic antenna:

    S__tx*A__Isotropic

    (1/16)*G__tx*P__tx*lambda^2/(Pi^2*r^2)

    (10.3)

    And so the power that would be received by an antenna with gain Grx is:

    P__rx := (1/16)*G__rx*G__tx*P__tx*lambda^2/(Pi^2*r^2)

    (1/16)*G__rx*G__tx*P__tx*lambda^2/(Pi^2*r^2)

    (10.4)

    The free space path loss is defined as the ratio between the received power and the transmitted power:

    P__rx/P__tx

    (1/16)*G__rx*G__tx*lambda^2/(Pi^2*r^2)

    (10.5)

    And so:

    PathLoss := G__tx*G__rx*(lambda/(4*Pi*r))^2

    (1/16)*G__rx*G__tx*lambda^2/(Pi^2*r^2)

    (10.6)

    ````

    ````

    NULL


     

    Download Friis_Transmission_Equation.mw

    Question about deflection and vibration of beams occur with some regularity in this forum.  Search for "beam" to see several pages of hits.

    In this post I present a general approach to calculating the vibrational modes of a beam that applies to both single-span and multi-span beams.  The code is not perfectly polished, but it is sufficiently documented to enable the interested user to modify/extend it as needed.

    Vibrational modes of multi-span Euler-Bernoulli beams

    through Krylov-Dunction functions

    Rouben Rostamian
    2020-07-19

    restart;

    Note:  Maple defines the imaginary unit I = sqrt(-1). We want to use the
    symbol I as the beam's cross-sectional moment of inertia.
    Therefore we redefine the imaginary unit (for which we have no

    use) as II and free up the symbol I for our use.

    interface(imaginaryunit=II):

    with(LinearAlgebra):

     

    The Euler-Bernoulli beam equation
    "rho*A*((&PartialD;)^2u)/((&PartialD;)^( )t^2)+E*I*((&PartialD;)^(4)u)/((&PartialD;)^( )x^(4))=0".

     

    We wish to determine the natural modes of vibration of

    a possibly multi-span Euler-Bernoulli beam.


    Separate the variables by setting u(x, t) = X(x)*T(t).   We get
    -
    "(rho*A)/(E*I)*(T ' ')/(T)=(X^((4)))/(X)=mu^(4)  "
    whence
    "T ' ' +(E*I)/(rho*A)*mu^(4)*T =0,           X^((4))-mu^(4)*X=0".

    Let omega = sqrt(I*E/(rho*A))*mu^2.  Then

    T(t) = C__1*cos(omega*t)+C__2*sin(omega*t)

     and
    "X(x)=`c__1`*cosh(mu*x)+`c__2`*sinh(mu*x)+`c__3`*sin(mu*x)+`c__4`*cos(mu*x)."

     

    The idea behind the Krylov-Duncan technique is to express X(x) 

    in terms an alternative (and equivalent) set of basis
    functions K__1 through K__4,, as
    X(x) = a__1*K__1(mu*x)+a__2*K__2(mu*x)+a__3*K__3(mu*x)+a__4*K__4(mu*x),

    where the functions K__1 through K__4 are defined in the next section.

    In some literature the symbols S, T, U, V, are used for these

    functions but I find it more sensible to use the indexed function

    notation.

    The Krylov-Duncan approach is particularly effective in formulating
    and finding a multi-span beam's natural modes of vibration.

     

     

    The Krylov-Duncan functions

     

    The K[i](x) defined by this proc evaluates to the ith

    Krylov-Duncan function.

     

    Normally the index i will be in the set{1, 2, 3, 4}, however the proc is

    set up to accept any integer index (positive or negative).  The proc evaluates

    the index modulo 4 to bring the index into the set {1, 2, 3, 4}.   For

    instance, K[5](x) and K[-3](x)i are equivalent to K[1](x) .

    K := proc(x)
            local n := op(procname);

            if not type(n, integer) then
                    return 'procname'(args);
            else
                    n := 1 + modp(n-1,4);  # reduce n modulo 4
            end if;

            if n=1 then
                    (cosh(x) + cos(x))/2;
            elif n=2 then
                    (sinh(x) + sin(x))/2;
            elif n=3 then
                     (cosh(x) - cos(x))/2;
            elif n=4 then
                    (sinh(x) - sin(x))/2;
            else
                    error "shouldn't be here!";
            end if;

    end proc:

    Here are the Krylov-Duncan basis functions:

    seq(print(cat(`K__`,i)(x) = K[i](x)), i=1..4);

    K__1(x) = (1/2)*cosh(x)+(1/2)*cos(x)

    K__2(x) = (1/2)*sinh(x)+(1/2)*sin(x)

    K__3(x) = (1/2)*cosh(x)-(1/2)*cos(x)

    K__4(x) = (1/2)*sinh(x)-(1/2)*sin(x)

    and here is what they look like.  All grow exponentially for large x
    but are significantly different near the origin.

    plot([K[i](x) $i=1..4], x=-Pi..Pi,
            color=["red","Green","blue","cyan"],
            thickness=2,
            legend=['K[1](x)', 'K[2](x)', 'K[3](x)', 'K[4](x)']);

    The cyclic property of the derivatives: 
    We have diff(K__i(x), x) = `K__i-1`.  Let's verify that:

    diff(K[i](x),x) - K[i-1](x) $i=1..4;

    0, 0, 0, 0

    The fourth derivative of each K__i  function equals itself. This is a consequence of the cyclic property:

    diff(K[i](x), x$4) - K[i](x) $ i=1..4;

    0, 0, 0, 0

    The essential property of the Krylov-Duncan basis function is that their

    zeroth through third derivatives at x = 0 form a basis for R^4:

    seq((D@@n)(K[1])(0), n=0..3);
    seq((D@@n)(K[2])(0), n=0..3);
    seq((D@@n)(K[3])(0), n=0..3);
    seq((D@@n)(K[4])(0), n=0..3);

    1, 0, 0, 0

    0, 1, 0, 0

    0, 0, 1, 0

    0, 0, 0, 1

    As noted earlier, in the case of a single-span beam, the modal  shapes

    are expressed as
    X(x) = a__1*K__1(mu*x)+a__2*K__2(mu*x)+a__3*K__3(mu*x)+a__4*K__4(mu*x).

    Then, due to the cyclic property of the derivatives of the Krylov-Duncan

    functions, we see that:
    "X '(x) = mu*(`a__1`*`K__4`(mu*x)+`a__2`*`K__1`(mu*x)+`a__3`*`K__2`(mu*x)+`a__4`*`K__3`(mu*x))".
    X*('`&InvisibleTimes;`')(x) = mu^2*(a__1*K__3(mu*x)+a__2*K__4(mu*x)+a__3*K__1(mu*x)+a__4*K__2(mu*x)).
    "X ' ' '(x) = mu^(3)*(`a__1`*`K__2`(mu*x)+`a__2`*`K__3`(mu*x)+`a__3`*`K__4`(mu*x)+`a__4`*`K__1`(mu*x))".
    Let us note, in particular, that
    X(0) = a__1,
    "X '(0)=mu*`a__2`",
    X*('`&InvisibleTimes;`')(0) = mu^2*a__3,
    "X ' ' '(0)=mu^(3)*`a__4`".

     

    A general approach for solving multi-span beams

     

    In a multi-span beam, we write X__i(x) for the deflection of the ith span, where

    0 < x and x < L__i and where L__i is the span's length.  The x coordinate indicates the

    location within the span, with x = 0 corresponding to the span's left endpoint.

    Thus, each span has its own x coordinate system.

     
    We assume that the interface of the two adjoining spans is supported on springs

    which (a) resist transverse displacement proportional to the displacement (constant of

    proportionality of k__d  (d for displacement), and (b) resist rotation proportional to the
    slope (constant of proportionality of k__t  (t for torsion or twist). The spans are numbered

    from left to right. The interface conditions between spans i and i+1 are

     

    1. 

    The displacements at the interface match:
    X__i(L__i) = `X__i+1`(0).

    2. 

    The slopes at the interface match
    X*`'i`(L__i) = X*`'i+1`(0).

    3. 

    The difference of the moments just to the left and just to the right of the
    support is due to the torque exerted by the torsional spring:
    "E*I*(X ' `'i+1`(0)-X ' `'i `(`L__i`))=-`k__t` * X `'i+1`(0),"

    4. 

    The difference of the shear forces just to the left and just to the right of the
    support is due to the force exerted by the linear spring:

    "E*I*(X ' ' `'i+1`(0)-X ' ' '(`L__i`))= -`k__d` * `X__i+1`(0).  "

    The special case of a pinned support corresponds to k__t = 0 and k__d = infinity.
    In that case, condition 3 above implies that X*'`'i+1`(0) = X'*`'i`(L__i),
    and condition 4 implies that `X__i+1`(0) = 0.


    Let us write the displacements X__i and `X__i+1` in terms of the Krylov-Duncan

    functions as:

     

    "`X__i`(x)=`a__i,1`*`K__1`(mu*x)+`a__i,2`*`K__2`(mu*x)+`a__i,3`*`K__3`(mu*x)+`a__i,4`*`K__4`(mu*x),  "
    "`X__i+1`(x)=`a__i+1,1`*`K__1`(mu*x)+`a__I+1,2`*`K__2`(mu*x)+`a__i+1,3`*`K__3`(mu*x)+`a__i+1,4`*`K__4`(mu*x)."


    Then applying the cyclic properties of the Krylov-Duncan functions described

    earlier, the four interface conditions translate to the following system of four
    equations involving the eight coefficients