Product Tips & Techniques

Tips and Tricks on how to get the most about Maple and MapleSim

I would like to be able to read Maple manuals and the AEM book that I have bought on the ipad. I can understand that I will not be able to run the commands. But it woud be nice to read through the different sections while reclining on my bed. Hope that you will make it possible.


On several occasions, while working with lists or Matrices, I have been drawn to using a combination of seq and if, as in the following:

seq(`if`(a,b,c), i = 1 .. 10 )

This appears to be a powerful approach. Unfortunately, I have not found much documentation on it.

I have been able to pattern-guess to a limited extent for my limited needs.

Would you know of a good place to go for information?

My understanding is: "a" is the conditional...

I have found very little help about the Generate command of the RandomTools package.

I also have minor gripes about the syntax. And what better way to deal with these than to voice them?

This is how I was able to generate random lists and random Matrices.

A list of 10 random integers between 1 and 100:

L := RandomTools:-Generate(list(integer(range=1..100),10));

      L := [47, 8, 46, 44, 9, 77, 59, 16, 1, 70]

 

In it's recent edition of Mathematics Today (in print and online), the UK-based Institute of Mathematics and it's Applications, compared 4 symbolic solvers: Maple 15, Mathcad 15, the student edition of Matlab v5 and the Casio CFX-9970G calculator, concluding that "Maple would be the natural choice for research mathematicians, theortetical physicists, those working in any area where mathematics is demanding or for mathematics undergraduates for whom costs are lower"

I wanted to point the MaplePrimes community in the direction of the new MapleSim training videos. These videos cover a variety of common tasks within MapleSim, and demonstrate the concept in just a few minutes each. I'd highly recommend you take a look at them to learn more about using MapleSim.

They're located here: http://www.maplesoft.com/support/training/videos.aspx

 

-Graham

It is the first time  I post a Maple bug in MaplePrimes because I use to submit an SCR.
There is a serious reason to do so. Let us look at the output of
> with(plots):
> implicitplot(sqrt(x^2+y^2)-sqrt((x-4)^2+(y-3)^2) = 5, x = -20 .. 20, y = -20 .. 20,
numpoints = 10^6, thickness = 5, scaling = constrained);
(both in Maple 13 and in Maple 16)

Let's see how we can display patterns, or even images, on 3D plot surfaces. Here's a simple example.

The underlying mechanism is the COLOR() component of a POLYGONS(), GRID(), or MESH() piece of a PLOT3D() data structure. (See here, here, and here for some older posts which relate to that.)

The data stored in the MESH() of a 3D plot structure can be a list-of-lists or, more efficient, an Array. The dimensions of that Array are m-by-n-by-3 where m and n are usually the size of the grid of points in the x-y plane (or of points in the two independent parameter spaces). In modern Maple quite a few kinds of 3D plots will produce a GRID() or a MESH() which represent the m-by-n independent data points that can be controlled with the usual grid=[m,n] option.

The plot,color help-page describes how colors may specified (for each x-y point pair to be plotted) using a procedure f(x,y). And that's fine for explicit plots, though there are some subtleties there. What is not documented on that help-page is the possibility of efficiently using an m-by-n-by-3 or an m*n-by-3 datatype=float[8], order=C_order Array of RGB values or am m*n float[8] Vector of hue values to specify the color data. And that's what I've been learning about, by experiment.

A (three-layer, RGB or HSV) color image used by the ImageTools package is also an m-by-n-by-3 Array. And all these Arrays under discussion have m*n*3 entries, and with either some or no manipulation they can be interchanged. I wrote earlier about converting ImageTools image structures to and from 2D density-plots. But there is also an easy way to get a 3D density-plot from an ImageTools image with a single command. That command is ImageTools:-Preview, and it even has a useful options to rescale. The rescaling is often necessary so that the dimensions of the COLOR() Array in the result match the dimensions of the grid in the MESH() Array.

For the first example, producing the banded torus above, we can get the color data directly from a densityplot, without reshaping/manipulating the color Array or using any ImageTools routines. The color data is stored in a m*n Vector of hue values.

But first a quick note: Some plots/plottools commands produce a MESH() with the data in a list-of-lists-of-lists, or a POLYGONS() call on a sequence of listlists (eg. `torus` in Maple 14). For convenience conversion of the data to a 3-dimensional Array may be done. It's handy to use `op` to see the contents of the PLOT3D() structure, but a possible catastrophe if a huge listlist gets printed in the Standard GUI.

restart:
with(ImageTools):with(plots):with(plottools):
N:=128:

d:=densityplot((x,y)->frem((x-2*y),1/2),0..1,0..1,
                      colorstyle=HUE,style=patchnogrid,grid=[N,N]):
#display(d);

c:=indets(d,specfunc(anything,COLOR))[1];

                         /     [ 1 .. 16384 Vector[column] ]\
                         |     [ Data Type: float[8]       ]|
               c := COLOR|HUE, [ Storage: rectangular      ]|
                         \     [ Order: C_order            ]/

T:=display(torus([0,0,0],1,2,grid=[N,N]),
           style=surface,scaling=constrained,axes=none,
           glossiness=0.7,lightmodel=LIGHT3):
#op(T); # Only view the operands in full with Maple 16!

# The following commands both produce the banded torus.

#op(0,T)(MESH(op([1,1..-1],T),c),op([2..-1],T)); # alternate way, M16 only

subsop([1,1]=[op([1,1],T),c][],T);

Most of the examples in this post use the command `op` or `indets` extract or replace the various parts of of the strcutures. Perhaps in future there could be an easy mechanism to pass the COLOR() Array directly to the plotting commands, using their `color` optional parameter.

In the next example we'll use an image file that is bundled with Maple as example data, and we'll use it to cover a sphere. We won't downsize the image, so that it looks sharp and clear (but note that this may make your Standard GUI session act a bit sluggish). Because we're not scaling down the image we must specify a grid=[m,n] size in the plotting command that matches the dimensions of the image. We'll use ImageTools:-Preview as a convenient mechanism to produce both the color Array as well as a 3D densityplot so that we can view the original image. Note that the data portion of the sphere plot structure is an m-by-n-by-3 Array in a MESH() which matches the dimensions of the m-by-n-by-3 Array in the COLOR() portion of the result from ImageTools:-Preview.

restart:
with(ImageTools):with(plots):with(plottools):
im:=Read(cat(kernelopts(mapledir),"/data/images/tree.jpg")):

p:=Preview(im):

op(1,p);

                 /                    [ 235 x 354 2-D  Array ]  
                 |                    [ Data Type: float[8]  ]  
             GRID|0 .. 266, 0 .. 400, [ Storage: rectangular ], 
                 \                    [ Order: C_order       ]  

                    /     [ 235 x 354 x 3 3-D  Array ]\\
                    |     [ Data Type: float[8]      ]||
               COLOR|RGB, [ Storage: rectangular     ]||
                    \     [ Order: C_order           ]//

q:=plot3d(1, x=0..2*Pi, y=0..Pi, coords=spherical, style=surface,
          grid=[235,354]):

display(PLOT3D(MESH(op([1,1],q), op([1,4..-1],p)), op(2..-1,q)),
           orientation=[-120,30,160]);

Apart from the online description of this new Maple 16 feature here, there is also the help-page for subexpressionmenu.

I don't know of a complete listing of its current functionality, but the key thing is that it acts in context. By that I mean that the choice of displayed actions depends on the kind of subexpression that one has selected with the mouse cursor.

Apart from arithmetic operations, rearrangements and some normalizations of equations, and plot previews, one of the more interesting pieces of functionality is the various trigonometric substitutions. Some of the formulaic trig substitutions provide functionality that has otherwise been previously (I think) needed in Maple.

In Maple 16 it is now much easier to do some trigonometric identity solving, step by step.

Here is an example executed in a worksheet. (This was produced by merely selecting subexpressions of the output at each step, and waiting briefly for the new Smart Popup menus to appear automatically. I did not right-click and use the traditional context-sensitive menus. I did not have to type in any of the red input lines below: the GUI inserts them as a convenience, for reproduction. This is not a screen-grab movie, however, and doesn't visbily show my mouse cursor selections. See the 2D Math version further below for an alternate look and feel.)

expr:=sin(3*a)=3*sin(a)-4*sin(a)^3:

expr;

sin(3*a) = 3*sin(a)-4*sin(a)^3

# full angle reduction identity: sin(3*a)=-sin(a)^3+3*cos(a)^2*sin(a)
-sin(a)^3+3*cos(a)^2*sin(a) = 3*sin(a)-4*sin(a)^3;

-sin(a)^3+3*cos(a)^2*sin(a) = 3*sin(a)-4*sin(a)^3

# subtract -sin(a)^3 from both sides
(-sin(a)^3+3*cos(a)^2*sin(a) = 3*sin(a)-4*sin(a)^3) -~ (-sin(a)^3);

3*cos(a)^2*sin(a) = 3*sin(a)-3*sin(a)^3

# divide both sides by 3
(3*cos(a)^2*sin(a) = 3*sin(a)-3*sin(a)^3) /~ (3);

cos(a)^2*sin(a) = sin(a)-sin(a)^3

# divide both sides by sin(a)
(cos(a)^2*sin(a) = sin(a)-sin(a)^3) /~ (sin(a));

cos(a)^2 = (sin(a)-sin(a)^3)/sin(a)

# normal 1/sin(a)*(sin(a)-sin(a)^3)
cos(a)^2 = normal(1/sin(a)*(sin(a)-sin(a)^3));

cos(a)^2 = 1-sin(a)^2

# Pythagoras identity: cos(a)^2=1-sin(a)^2
1-sin(a)^2 = 1-sin(a)^2;

1-sin(a)^2 = 1-sin(a)^2

 

The very first step above could also be done as a pair of simpler sin(x+y) reductions involving sin(2*a+a) and sin(a+a), depending on what one allows onself to use. There's room for improvement to this whole approach, but it looks like progress.

Download trigident1.mw

In a Document, rather than using 1D Maple notation in a Worksheet as above, the actions get documented in the more usual way, similar to context-menus, with annotated arrows between lines.

expr := sin(3*a) = 3*sin(a)-4*sin(a)^3:

expr

sin(3*a) = 3*sin(a)-4*sin(a)^3

(->)

2*cos(a)*sin(2*a)-sin(a) = 3*sin(a)-4*sin(a)^3

(->)

4*cos(a)^2*sin(a)-sin(a) = 3*sin(a)-4*sin(a)^3

(->)

4*cos(a)^2*sin(a) = 4*sin(a)-4*sin(a)^3

(->)

cos(a)^2*sin(a) = sin(a)-sin(a)^3

(->)

cos(a)^2 = (sin(a)-sin(a)^3)/sin(a)

(->)

cos(a)^2 = 1-sin(a)^2

(->)

1-sin(a)^2 = 1-sin(a)^2

(->)

1 = 1

``

Download trigident2.mw

 

I am not quite sure what is the best way to try and get some of the trig handling in a more programmatic way, ie. by using the "names" of the various transformational formulas. But some experts here may discover such by examination of the code. Ie,

eval(SubexpressionMenu);

showstat(SubexpressionMenu::TrigHandler);

The above can leads to noticing the following (undocumented) difference, for example,

> trigsubs(sin(2*a));
              
                                 1       2 tan(a)
[-sin(-2 a), 2 sin(a) cos(a), --------, -----------,
                              csc(2 a)            2
                                        1 + tan(a)

    -1/2 I (exp(2 I a) - exp(-2 I a)), 2 sin(a) cos(a), 2 sin(a) cos(a)]

> trigsubs(sin(2*a),annotate=true);

["odd function" = -sin(-2 a), "double angle" = 2 sin(a) cos(a),

                               1                       2 tan(a)
    "reciprocal function" = --------, "Weierstrass" = -----------,
                            csc(2 a)                            2
                                                      1 + tan(a)

    "Euler" = -1/2 I (exp(2 I a) - exp(-2 I a)),

    "angle reduction" = 2 sin(a) cos(a),

    "full angle reduction" = 2 sin(a) cos(a)]

And that could lead one to try constructions such as,

> map(rhs,indets(trigsubs(sin(a),annotate=true),
>                identical("double angle")=anything));

                             {2 sin(a/2) cos(a/2)}

Since the `annotate=true` option for `trigsubs` is not documented in Maple 16 there is more potential here for useful functionality.

Here is a hacked-up and short `convert/identifier` procedure.

The shortness of the procedure should is a hint that it's not super robust. But it can be handy, in some simple display situations.

If I had made into a single procedure (named `G`, or whatever) then I could have declared its first parameter as x::uneval and thus avoided the need for placing single-right (uneval) quotes around certain examples. But for fun I wanted it to be an extension of `convert`. And while I could code special-evaluation rules on my `convert` extension I suppose that there no point in doing so since `convert` itself doesn't have such rules.

For the first two examples below I also typed in the equivalent expressions in 2D Math input mode, and then used the right-click context-menu to convert to Atomic Identifier. Some simple items come out the same, while some other come out with a different underlying structure and display.

 

restart:

`convert/identifier`:=proc(x)
   cat(`#`,convert(convert(:-Typesetting:-Typeset(x),`global`),name));
end proc:

convert( 'sqrt(4)', identifier);

`#msqrt(mn("4"))`

eval(value(%));
lprint(%);

`#msqrt(mn("4"))`

`#msqrt(mn("4"))`

`#msqrt(mn("4"))`

`#msqrt(mn("4"))`

lprint(%);

`#msqrt(mn("4"))`

convert( 'int(BesselJ(0,Pi*sqrt(t)),t)', identifier);

`#mrow(mo("∫"),mrow(msub(mi("J",fontstyle = "normal",msemantics = "BesselJ"),mn("0")),mo("⁡"),mfenced(mrow(mi("π"),mo("⁢"),msqrt(mi("t"))))),mspace(width = "0.3em"),mo("ⅆ"),mi("t"))`

eval(value(%));
#lprint(%);

`#mrow(mo("∫"),mrow(msub(mi("J",fontstyle = "normal",msemantics = "BesselJ"),mn("0")),mo("⁡"),mfenced(mrow(mi("π"),mo("⁢"),msqrt(mi("t"))))),mspace(width = "0.3em"),mo("ⅆ"),mi("t"))`

`#mrow(mo("∫"),msub(mo("J"),mn("0")),mfenced(mrow(mi("π",fontstyle = "normal"),mo("⁢"),msqrt(mi("t")))),mo("⁢"),mo("ⅆ"),mi("t"))`

`#mrow(mo("∫"),msub(mo("J"),mn("0")),mfenced(mrow(mi("π",fontstyle = "normal"),mo("⁢"),msqrt(mi("t")))),mo("⁢"),mo("ⅆ"),mi("t"))`

#lprint(%);

convert( Vector[row](['Zeta(0.5)', a.b.c, 'limit(sin(x)/x,x=0)', q*s*t]), identifier);

Vector[row](4, {(1) = Zeta(.5), (2) = a.b.c, (3) = limit(sin(x)/x, x = 0), (4) = q*s*t})

eval(value(%));
#lprint(%);

Vector[row](4, {(1) = Zeta(.5), (2) = a.b.c, (3) = limit(sin(x)/x, x = 0), (4) = q*s*t})

 

Download atomic1.mw

As it stands this hack may be useful in a pinch for demos and purely visual effect, but unless it's robustified then it won't allow you to programmatically generate atomic names which match and inter-operate computationally with those from the context-menu conversion. Identifiers (names) with similar typeset appearance still have to match exactly if they are to be properly compared, added, subtracted with each other.

Extra points for commenting that the round-brackets (eg. in function-application) are displayed as black while the rest is in blue by default, if you have a workaround.  That also happens when using the usual context-menu driven convert-to-atomic-identifier of the Standard GUI.

Extra points for noticing that function names like `sin` are italicized and not in an upright font, if you have a workaround. How to discern which instances of fontstyle="normal" should be removed?

Points off for commenting that this whole hack doesn't provide anything new or extra for getting around automatic simplification.  :)

This is a one-liner hack. But maybe together we could turn it into something that closely matched what the context-menu generates.

Many of us know that issuing plotting commands produces various kinds of plot data structure, the details of which are documented on the plot,structure help-page. That page covers most of the details, and a thorough read can reveal that the numeric data of a plot is often stored within such structures as either Array or Matrix.

But what about the result of a call to

MapleNet 16 is now available. New features include the ability to programmatically execute Maple documents from your MapleNet application and support for the Symbolic Computation Software Composability Protocol (SCSCP) framework, which promotes interoperability with special-purpose computer algebra systems. For more details, see What’s New in MapleNet 16.

 

eithne

Someone asked me the other week whether a color gradient could be easily applied to a high density point-plot, either vertically or horizontally graded.

Without thinking, I said, "Sure, easy." But when I got to a computer, and gave it a little thought, I realized that it's not that easy to do it efficiently. And it really ought to be, even for tens of thousands of points.

There is a help-page plot,color which briefly describes some things that can be done with coloring plots. As of Maple 16, it mentions a "color data structure" which can be created by calls to the new ColorTools package. There is an example on that page for a single color, but not for several colors concurrently. Using Colortools to get a list of colors, for many points, can be done. (And there ought to be such an example.) But for the case of many data points that uses quite a lot of memory, and is slow.

Also, there is no 2D plotting equivalent to the 3D plotting colorfunc functionality. There ought to be. And just as the 3D colorfunc should be fixed to take three arguments (x,y, & z) any new 2D colorfunc should be made to take two arguments (x & y).

So, how can we apply a color gradient on a 25000 2D-point-plot, shaded by y-value? One way is to notice that the various 2D and 3D plot data structures can now store an efficient m-by-3 (or m-by-n-by-3) C_order, float[8] Array for the purpose of representing the chosen colors. (That is not documented, but can be learned by observation and inspection of various example plot structures.) We know that such an Array is relatively memory-light, and can be produced very quickly.

What this task has become is a 2D version of this method of inserting a custom made color sequence into a 3D plot, but more efficient on account of using a float[8] Array.

To get some decent timings the attached worksheet uses the time[real] command. Timings are computed both immediately after computation (same execution block) as well as after plot rendering (next execution block).

It takes about 1 sec for the Maple 16.01 64bit Standard GUI on Windows 7 to throw up and render the plot, for both methods.

It takes 3.4 sec, and a 108 MB increase in allocated memory, to compute the plot data structure result using ColorTools and a list. But it takes only 0.45 sec, and a 20.5 MB increase in allocated memory, to compute an equivalent plot data structure using the float[8] Array. (Timings on an Intel i7-960.)

[worksheet upload is misbehaving. So inlining the code.]

restart:
N:=25000:

xy:=LinearAlgebra:-RandomMatrix(N,2,generator=0.0..1.0,
                                outputoptions=[datatype=float[8]]):

str:=time[real]():

plots:-pointplot(xy,
                    color=[seq(ColorTools:-Color([xy[i,2],0,0]),i=1..N)],
                    symbolsize=4);

time[real]()-str;

                             3.323

time[real]()-str; # in new execution group

                             4.400
kernelopts(bytesalloc);

                           107646976


restart:
N:=25000:

xy:=LinearAlgebra:-RandomMatrix(N,2,generator=0.0..1.0,
                                outputoptions=[datatype=float[8]]):

str:=time[real]():

p:=plots:-pointplot(xy,color=red,symbolsize=4):

c:=Array(1..N*3,(i)->`if`(irem(i,3)=1,xy[(i+2)/3,2],0),
         datatype=float[8],order=C_order):

subsindets(p,specfunc(anything,COLOUR),z->'COLOUR'('RGB',c));

time[real]()-str;

                             0.483

time[real]()-str; # in new execution group

                             1.357
kernelopts(bytesalloc);

                            20545536

This is an important topic which is why I have labelled it as a post.  Many users would like to know how to implement a minor fix to versions where fixes have not been applied.

I will start with one example.

   pdsolve had an issue where the fourth order term was not evaluated in the pdsolve command.  The issue 
   works Maple 16.  To those users of earlier versions where the code didn't work, it was ...

   showstat(pdsolve)

Way back in Maple 6, the rtable was introduced. You might be more familiar with its three types: Array, Matrix, and Vector. The name rtable is named after "rectangular table", since its entries can be stored contiguously in memory which is important in the case of "hardware" datatypes. This is a key aspect of the external-calling mechanism which allows Maple to use functions from the NAG and CLAPACK external libraries. In essence, the contiguous data portion of a hardware datatype rtable can be passed to a compiled C or Fortran function without any need for copying or preliminary conversion. In such cases, the data structure in Maple is storing its numeric data portion in a format which is also directly accessible within external functions.

You might have noticed that Matrices and Arrays with hardware datatypes (eg. float[8], integer[4], etc) also have an order. The two orders, Fortran_order and C_order, correspond to column-major and row-major storage respectively. The Wikipedia page row-major  explains it nicely.

There is even a help-page which illustrates that the method of accessing entries can affect performance. Since Fortran_order means that the individual entries in any column are contiguous in memory then code which accesses those entries in the same order in which they are stored in memory can perform better. This relates to the fact that computers cache data: blocks of nearby data can be moved from slower main memory (RAM) to very fast cache memory, often as a speculative process which often has very real benefits.

What I'd like to show here is that the relatively small performance improvement (due to matching the entry access to the storage order) when using evalhf can be a more significant improvement when using Maple's Compile command. For procedures which walk all entries of a hardware datatype Matrix or multidimensional Array, to apply a simple operation upon each value, the improvement can involve a significant part of the total computation time.

What makes this more interesting is that in Maple the default order of a float[8] Matrix is Fortran_order, while the default order of a float[8] Array used with the ImageTools package is C_order. It can sometimes pay off, to write your for-do loops appropriately.

If you are walking through all entries of a Fortran_order float[8] Matrix, then it can be beneficial to access entries primarily by walking down each column. By this I mean accessing entries M[i,j] by changing i in ther innermost loop and j in the outermost loop. This means walking the data entries, one at a time as they are stored. Here is a worksheet which illustrates a performance difference of about 30-50% in a Compiled procedure (the precise benefit can vary with platform, size, and what else your machine might be doing that interferes with caching).

Matrixorder.mw

If you are walking through all entries of an m-by-n-by-3 C_order float[8] Array (which is a common structure for a color "image" used by the ImageTools package) then it can be beneficial to access entries A[i,j,k] by changing k in the innermost loop and i in the outermost loop. This means walking the data entries, one at a time as they are stored. Here is a worksheet which illustrates a performance difference of about 30-50% in a Compiled procedure (the precise benefit can vary with platform, size, and what else your machine might be doing that interferes with caching).

Arrayorder.mw

Just wanted to let everyone know that there is a Maple 16 update available. Maple 16.01 includes improvements to the mathematics, interface, and plotting capabilities of Maple, including:

  • Enhancements to the Physics package in the area of general relativity
  • Translations of tutors and assistants into French and Brazilian Portuguese
  • A correction to the problem in plotting multiple plots at once in non-Cartesian coordinates, as
First 26 27 28 29 30 31 32 Last Page 28 of 64