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

  •  

    A geometric construction for the Summer Holiday

     
    Does every plane simple closed curve contain all four vertices of some square?

     This is an old classical conjecture. See:
    https://en.wikipedia.org/wiki/Inscribed_square_problem

    Maybe someone finds a counterexample (for non-analytic curves) using the next procedure and becomes famous!

     

    SQ:=proc(X::procedure, Y::procedure, rng::range(realcons), r:=0.49)
    local t1:=lhs(rng), t2:=rhs(rng), a,b,c,d,s;
    s:=fsolve({ X(a)+X(c) = X(b)+X(d),
                Y(a)+Y(c) = Y(b)+Y(d),
                (X(a)-X(c))^2+(Y(a)-Y(c))^2 = (X(b)-X(d))^2+(Y(b)-Y(d))^2,
                (X(a)-X(c))*(X(b)-X(d)) + (Y(a)-Y(c))*(Y(b)-Y(d)) = 0},
              {a=t1..t1+r*(t2-t1),b=rng,c=rng,d=t2-r*(t2-t1)..t2});  #lprint(s);
    if type(s,set) then s:=rhs~(s)[];[s,s[1]] else WARNING("No solution found"); {} fi;
    end:

     

    Example

     

    X := t->(10-sin(7*t)*exp(-t))*cos(t);
    Y := t->(10+sin(6*t))*sin(t);
    rng := 0..2*Pi;

    proc (t) options operator, arrow; (10-sin(7*t)*exp(-t))*cos(t) end proc

     

    proc (t) options operator, arrow; (10+sin(6*t))*sin(t) end proc

     

    0 .. 2*Pi

    (1)

    s:=SQ(X, Y, rng):
    plots:-display(
       plot([X,Y,rng], scaling=constrained),
       plot([seq( eval([X(t),Y(t)],t=u),u=s)], color=blue, thickness=2));

     

    It appears google doesn't know about the haversine formula.  Huh?  Well at least google can't draw the proper path for it.  I typed in google "distance from Pyongyang to NewYork city"  and got 10,916km.  Ok that's fine but then it drew a map

    The map path definitely did not look right.  Pulled out my globe traced a rough path of the one google showed and I got 13 inches (where 1 inch=660miles) -> 8580 miles = 13808 km .. clearly looks like google goofed. 

    So we need Maple to show us the proper path.
     

    with(DataSets):
    with(Builtin):
    m := WorldMap();
    AddPath(m, [-74.0059, 40.7128], [125.7625, 39.0392]):
    Display(m):
    

    Ok so you say that really doesn't look like the shortest path.  Well, lets visualize that on the globe projection

    Display(m, projection = Globe, orientation = [-180, 0, 0])

    Ah, now it is clear
    Pyonyang_to_NewYork.mw

     

    As a momentary diversion, I threw together a package that downloads map images into Maple using the Google Static Maps API.

    If you have Maple 2017, you can install the package using the MapleCloud Package Manager or by executing PackageTools:-Install("5769608062566400").

    This worksheet has several examples, but I thought I'd share a few below .

    Here's the Maplesoft office

     

    Let's view a roadmap of Waterloo, Ontario.

     

    The package features over 80 styles for roadmaps. These are examples of two styles (the second is inspired by the art of Piet Mondrian and the De Stijl movement)

     

    You can also find the longitude and latitude of a location (courtesy of Google's Geocoding API). Maple returns a nested list if it finds multiple locations.

     

    The geocoding feature can also be used to add points to Maple 2017's built-in world maps.

     

    Let me know what you think!

    The representation of the tangent plane in the form of a square with a given length of the side at any point on the surface.

    The equation of the tangent plane to the surface at a given point is obtained from the condition that the tangent plane is perpendicular to the normal vector. With the aid of any auxiliary point not lying on this normal to the surface, we define the direction on the tangent plane. From the given point in this direction, we lay off segments equal to half the length of the side of our square and with the help of these segments we construct the square itself, lying on the tangent plane with the center at a given point.

    An examples of constructing tangent planes at points of the same intersection line for two surfaces.
    Tangent_plane.mw

    This app is used to study the behavior of water in its different properties besides air. Also included is the study of the fluids in the state of rest ie the pressure generated on a flat surface. Integral developed in Maple for the community of users in space to the civil engineers.

    App_for_fluids_in_flat_state_of_rest.mw

    Lenin Araujo Castillo

    Ambassador of Maple

     

    Yahoo Finance recently discontinued their (largely undocumented) historical stock quote API.

    Previously, you simply send a HTTP:-Get request like this…

    HTTP:-Get(“http://ichart.yahoo.com/table.csv?s=AAPL&a=00&b=1&c=2016&d=00&e=1&f=2017&g=d&ignore=.csv")

    …and get historical OHLCV (open, high, low, close, trading volume) data in your worksheet (in this case for AAPL between 1 January 2016 and 1 January 2017).

    This no longer works! Yahoo shut the door on this easy-to-use and widely disseminated API.

    You can still download historical stock quotes from Yahoo Finance into Maple, but the process is now somewhat more involved. My complete code in this worksheet but I'll step through the process below.

    If you visit the updated Yahoo Finance website and download historical data for a ticker, you see a URL like this in the status bar of your browser

    https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=1497727945&period2=1500319945&interval=1d&events=history&crumb=C9luNcNjVkK

    Let's examine how ths URL is constructed.

    • period1 and period2 are Unix time stamps for your start and end date
    • interval is the data retrieval interval (this can be either 1d, 1w or 1m)
    • crumb is an alphanumeric code that’s periodically regenerated every time you download new historical data from from the Yahoo Finance website using your browser. Moreover, crumb is paired with a cookie that’s stored by your browser.

    Here’s how to extract and supply the cookie-crumb pair to Yahoo Finance so you can still use Maple to retrieve historical stock quotes

    Send a dummy request to get a cookie-crumb pair

    res:=HTTP:-Get("https://finance.yahoo.com/lookup?s=bananas"):

    Grab the crumb from the response

    i:=StringTools:-Search("CrumbStore\":{\"crumb\":\"",res[2]):
    crumbValue := res[2][i+22..i+32]
                      crumbValue := "btW01FWTBn3"

    Store the cookie from the response

    cookieHeader:=res[3]["Set-Cookie"]
        cookieHeader := "B=702eqhdcmq7cl&b=3&s=0t; expires=Mon,17-Jul-2018 20:27:01 GMT; path=/; domain=.yahoo.com

    Construct the URL

    • Your desired start and end dates have to be defined as Unix time stamps. Converting a human readable date (like 1st January 2017) to a Unix timestamp is simple, so I won't cover it here.
    • The previously retrieved crumb has to be added to the URL.
    ticker:="AAPL":
    p1 := 1497709183:
    p2 := 1500301183:
    url:=cat("https://query1.finance.yahoo.com/v7/finance/download/",ticker,"?period1=",p1,"&period2=",p2,"&interval=1d&events=history&crumb=", crumbValue):

    Send the request to Yahoo Finance, including the cookie in the header

    data:=HTTP:-Get(url,headers = ["Cookie" = cookieHeader])

    Your historical data is now returned

    The historical data is now easily parsed into a matrix.

    Please note that any use of Yahoo Finance has to be consistent with their terms of service.

    The Lattice package to investigate particle accelerator magnet lattices (original post) has been updated to V1.1. This is a significant update, addressing a number of inaccuracies and bugs of V1.0 as well as introducing new elements: Octupole, Fringe effect in dipoles, a MatchedSection allowing to insert a piece of beamline when the details are irrelevant, and a few experimental elements like WireQuad. New functions include the 6th synchrotron-radiation integral I6x, momentum compaction alphap and TaylorMap, which allows to compute the Taylor expansion of  the non-linear map to any degree.

    The code and documentation are available in the Application Center.

    U. Wienands, aka Mac Dude

     

    A couple of weeks ago, I recorded a short video that discussed various applications for the Statistics:-Fit command. One of the more interesting examples examined how manually adjusting the number of parameters used for a regression model affected the resulting adjusted r-squared value.

    I won’t go into detail about r-squared here, but to briefly summarize: In a linear regression model, r-squared measures the proportion of the variation in a model's dependent variable explained by the independent variables. Basically, r-squared gives a statistical measure of how well the regression line approximates the data. R-squared values usually range from 0 to 1 and the closer it gets to 1, the better it is said that the model performs as it accounts for a greater proportion of the variance (an r-squared value of 1 means a perfect fit of the data). When more variables are added, r-squared values typically increase. They can never decrease when adding a variable; and if the fit is not 100% perfect, then adding a variable that represents random data will increase the r-squared value with probability 1. The adjusted r-squared attempts to account for this phenomenon by adjusting the r-squared value based on the number of independent variables in the model.

    The formula for the adjusted r-squared is:

    Where:

    n is the number of points in the data sample

    k is the number of independent variables in the model excluding the constant

    By taking the number of independent variables into consideration, the adjusted r-squared behaves different than r-squared; adding more variables doesn’t necessarily produce better fitting models. In many cases, more variables can often lead to lower adjusted r-squared values. In particular, if you add a variable representing random data, the expected change in the adjusted r-squared is 0.

    As such, the adjusted r-squared has a slightly different interpretation than the r-squared. While r-squared is perceived to give an indication of the measure of fit for a chosen regression model, the adjusted r-squared is perceived more as a comparative tool that can be useful for picking variables and designing models that may require less predictors than other models. The science of “gaming” models is a broad topic, so I won’t go into any more detail here, but there’s lots of great information out there if you are looking to learn more (here’s a good place to start).

    The following example adjusts a fitted model by adding or removing variables in order to find better adjusted r-squared values.

    with(Statistics):

    The Import command reads a datafile into a new DataFrame.

    ExperimentalData := Import(FileTools:-JoinPath(["Excel", "ExperimentalData.xls"], base = datadir));

    The dataset has seven variables: time and experimental readings for 6 various concentrations. Removing “time” from our variable set, the convert command converts the values in the DataFrame to a Matrix of values.

    ExMat := convert( ExperimentalData, Matrix )[..,2..7];

    We start by fitting a model that includes predicting variables for each of the columns of data. We mark “Concentration A” as our dependent variable.

    Fit( C + C2*v + C3*w + C4*x + C5*y + C6*z, ExMat[..,2..6], ExMat[..,1], [v,w,x,y,z], summarize=embed ):

    From the above, we can observe that both the r-squared and adjusted r-squared are reasonably high, however only one of the coefficient values has a significant p-value, C3.

    Note: Maple shows all p-values less than 0.05 in bold.

    Let's try to fit the data again, this time keeping the two coefficients with the lowest p-values and the intercept.

    Fit( C + C3*v + C5*w, ExMat[..,[3,5]], ExMat[..,1], [v,w], summarize=embed ):

    From the above, we can see that the r-squared value does go down, however the adjusted r-squared goes up! Let's fit the model one last time to see if removing C5 increases or decreases the adjusted r-squared.

    Fit( C + C3*v, ExMat[..,3], ExMat[..,1], [v], summarize=embed ):

    We can see that the final adjusted r-squared value is lower than the previous two, so we are probably better to keep the additional C5 coefficient value.

    You can see this example as well as a couple of other examples of using the Fit command in the following video:

    You can download the worksheet here: https://www.maplesoft.com/applications/view.aspx?SID=154246

    We have just released the 3rd edition of the Mathematics Survival Kit – Maple Edition.

    The Math Survival Kit helps students get unstuck when they are stuck. Sometimes students are prevented from solving a problem, not because they haven’t understood the new concept, but because they forget how to do one of the steps, like completely the square, or dealing with log properties.  That’s where this interactive e- book comes in. It gives students the opportunity to review exactly the concept or technique they are stuck on, work through an example, practice as much (or as little) as they want using randomly generated, automatically graded questions on that exact topic, and then continue with their homework.

    This book covers over 150 topics known to cause students grief, from dividing fractions to integration by parts. This 3rd edition contains 31 additional topics, deepening the coverage of mathematical topics at every level, from pre-high school to university.

    See the Mathematics Survival Kit for more information about this updated e-book, including the complete list of topics.

    eithne

    This post is the answer to this question.

    The procedure named  IntOverDomain  finds a double integral over an arbitrary domain bounded by a non-selfintersecting piecewise smooth curve. The code of the procedure uses the well-known Green's theorem.

    Each section in the border should be specified by a list in the following formats :    
    1. If a section is given parametrically, then  [[f(t), g(t)], t=t1..t2]    
    2. If several consecutive sections of the border or the entire border is a broken line, then it is sufficient to set vertices of this broken line  [ [x1,y1], [x2,y2], .., [xn,yn] ] (for the entire border should be  [xn,yn]=[x1,y1] ).

    Required parameters of the procedure:  f  is an expression in variables  x  and  y , L  is the list of all the sections. The sublists of the list  L  must follow in the positive direction (counterclockwise).

    The code of the procedure:

    restart;
    IntOverDomain := proc(f, L) 
    local n, i, j, m, yk, yb, xk, xb, Q, p, P, var;
    n:=nops(L);
    Q:=int(f,x);  
    for i from 1 to n do 
    if type(L[i], listlist(algebraic)) then
    m:=nops(L[i]);
    for j from 1 to m-1 do
    yk:=L[i,j+1,2]-L[i,j,2]; yb:=L[i,j,2];
    xk:=L[i,j+1,1]-L[i,j,1]; xb:=L[i,j,1];
    p[j]:=int(eval(Q*yk,[y=yk*t+yb,x=xk*t+xb]),t=0..1);
    od;
    P[i]:=add(p[j],j=1..m-1) else
    var := lhs(L[i, 2]);
    P[i]:=int(eval(Q*diff(L[i,1,2],var),[x=L[i,1,1],y=L[i,1,2]]),L[i,2]) fi;
    od; 
    add(P[i], i = 1 .. n); 
    end proc:

     

    Examples of use.

    1. In the first example, we integrate over a quadrilateral:

    with(plottools): with(plots):
    f:=x^2+y^2:
    display(polygon([[0,0],[3,0],[0,3],[1,1]], color="LightBlue"));  
    # Visualization of the domain of integration
    IntOverDomain(x^2+y^2, [[[0,0],[3,0],[0,3],[1,1],[0,0]]]);  # The value of integral

     

    2. In the second example, some sections of the boundary of the domain are curved lines:

    display(inequal({{y<=sqrt(x),y>=sin(Pi*x/3)/2,y<=3-x}, {y>=-2*x+3,y>=sqrt(x),y<=3-x}}, x=0..3,y=0..3, color="LightGreen", nolines), plot([[t,sqrt(t),t=0..1],[t,-2*t+3,t=0..1],[t,3-t,t=0..3],[t,sin(Pi*t/3)/2,t=0..3]], color=black, thickness=2));
    f:=x^2+y^2: L:=[[[t,sin(Pi*t/3)/2],t=0..3],[[3,0],[0,3],[1,1]], [[t,sqrt(t)],t=1..0]]:
    IntOverDomain(f, L);

     

    3. If  f=1  then the procedure returns the area of the domain:

    IntOverDomain(1, L);  # The area of the above domain
    evalf(%);

     

    IntOverDomain.mw

    Edit.

    The help page for  ?procedure has the following example.

    addList := proc(a::list,b::integer)::integer;
        local x,i,s;
        description "add a list of numbers and multiply by a constant";
        x:=b;
        s:=0;
        for i in a do
            s:=s+a[i];
        end do;
        s:=s*x:
    end proc:

    sumList:=addList([1,2,3,4,5],2);

    30

    (1)

    Of course it's a bug (actually a typo) here:  s:=s+a[i];   should be   s:=s+i;

    A strange/funny fact is that the result is correct but, for almost any other list the call will produce an error or a wrong answer.

    This app shows the calculation of the final speed of a body after it made contact with a variable force; Taking as reference the initial velocity, mass and graph of the variation of F as a function of time. That is, given the variable forces represented by the lines in the time intervals, we will show the equation of momentum and momentum; With their respective values, followed by their response.

    Momentum_with_two_variable_force.mw

    https://www.youtube.com/watch?v=2xWkF7JhkpI

    Lenin Araujo C.

    Ambassador of Maple

     

     

     

     

     

     

    When we first started trying to use Maple to create a maple leaf like the one in the Canada 150 logo, we couldn’t find any references online to the exact geometry, so we went back to basics. With our trusty ruler and protractor, we mapped out the geometry of the maple leaf logo by hand.

    Our first observation was that the maple leaf could be viewed as being comprised of 9 kites. You can read more about the meaning of these shapes on the Canada 150 site (where they refer to the shapes as diamonds).

    We also observed that the individual kites had slightly different scales from one another. The largest kites were numbers 3, 5 and 7; we represented their length as 1 unit of length. Also, each of the kites seemed centred at the origin, but was rotated about the y-axis at a certain angle.

    As such, we found the kites to have the following scales and rotations from the vertical axis:

    Kites:

    1, 9: 0.81 at +/- Pi/2

    2, 8: 0.77 at +/- 2*Pi/5

    3, 5, 7: 1 at +/-Pi/4, 0

    4, 6: 0.93 at +/- Pi/8

    This can be visualized as follows:

    To draw this in Maple we put together a simple procedure to draw each of the kites:

    # Make a kite shape centred at the origin.
    opts := thickness=4, color="#DC2828":
    MakeKite := proc({scale := 1, rotation := 0})
        local t, p, pts, x;

        t := 0.267*scale;
        pts := [[0, 0], [t, t], [0, scale], [-t, t], [0, 0]]:
        p := plot(pts, opts);
        if rotation<>0.0 then
            p := plottools:-rotate(p, rotation);
        end if;
        return p;
    end proc:

     

    The main idea of this procedure is that we draw a kite using a standard list of points, which are scaled and rotated. Then to generate the sequence of plots:

    shapes := MakeKite(rotation=-Pi/4),
              MakeKite(scale=0.77, rotation=-2*Pi/5),

              MakeKite(scale=0.81, rotation=-Pi/2),
              MakeKite(scale=0.93, rotation=-Pi/8),
              MakeKite(),
              MakeKite(scale=0.93, rotation=Pi/8),
              MakeKite(scale=0.81, rotation=Pi/2),
              MakeKite(scale=0.77, rotation=2*Pi/5),
              MakeKite(rotation=Pi/4),
              plot([[0,-0.5], [0,0]], opts): #Add in a section for the maple leaf stem
    plots:-display(shapes, scaling=constrained, view=[-1..1, -0.75..1.25], axes=box, size=[800,800]);

    This looked pretty similar to the original logo, however the kites 2, 4, 6, and 8 all needed to be moved behind the other kites. This proved somewhat tricky, so we just simply turned on the point probe in Maple and drew in the connected lines to form these points.

    shapes := MakeKite(rotation=-Pi/4),
              plot([[-.55,.095],[-.733,.236],[-.49,.245]],opts),

              MakeKite(scale=0.81, rotation=-Pi/2),
              plot([[-.342,.536],[-.355,.859],[-.138,.622]],opts),
              MakeKite(),
              plot([[.342,.536],[.355,.859],[.138,.622]],opts),
              MakeKite(scale=0.81, rotation=Pi/2),
              plot([[.55,.095],[.733,.236],[.49,.245]],opts),
              MakeKite(rotation=Pi/4),
              plot([[0,-0.5], [0,0]], opts):
    plots:-display(shapes, scaling=constrained, view=[-1..1, -0.75..1.25], axes=box, size=[800,800]);

    Happy Canada Day!

    With Maple, you can create amazing visualizations that go far beyond the standard mathematical plots that you might typically expect (I wince every time I see yet another sine curve).

    At your fingertips, you have

    • plotting primitives that can be assembled in new and novel ways
    • precise control over coloring (yay for ColorTools) and placement
    • an interactive coding environment with inline plots, giving you quick visual feedback over aesthetic changes
    • and a comprehensive mathematical programming language to glue everything together

    Here, I thought I'd share a few of the visualizations I've really enjoyed creating over the last few years (and I'd like to emphasize 'enjoy' - doing this stuff is fun!)

    Let me know if you want any of the worksheets.

     

    Psychrometric chart with historical weather data for Waterloo, Ontario.

     

    Ternary plot of the color of gold-silver-copper alloys

     

    Spectrogram of a violin note played with vibrato

     

    Colored zoom of the Mandelbrot set

     

    Reporting dashboard for an Organic Rankine Cycle

     

    Temperature-entropy plot of an ideal Rankine Cycle

     

    Quaternion fractal

     

    Historical sunpot data

     

    Earthquake data

     

    African literacy rates

    First 48 49 50 51 52 53 54 Last Page 50 of 299