Applications, Examples and Libraries

Share your work here

1 Introduction

Three tanks are connected with two pipes. Each tank is initially filled to a different level. A valve in each pipe opens, and the liquid levels gradually reach equilibrium. Here, we model the system in MapleSim (including the influence of flow inertia), and also derive and solve the analytical equations in Maple.

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]);

Many years ago, I played Scrabble competitively. One of the first things a beginner tournament player should do is learn the two-letter word list. Recently, I created a worksheet that tests your knowledge of all the valid two-letter words accepted in official tournament play in North America. The worksheet makes extensive use of the StringTools package which has terrific tools for manipulating words.

The worksheet link is below if you'd like to try it out, and I'll...

Here are 30 all-time men's best 100m  (see http://en.wikipedia.org/wiki/100_metres
 and  http://www.alltime-athletics.com/m_100ok.htm )
        1      9.58       +0.9    Usain Bolt          16.08.2009

I would like to pay attention to http://www.scientificcomputing.com/atlas-032408.aspx . It seems to be a powerful tool to research, to teach, and to learn.

With the addition of ten new Clickable-Calculus examples to the Teaching Concepts with Maple section of the Maplesoft website, we've now posted 63 of the 154 solved problems in my data-base of syntax-free calculations. Once again, these examples and associated videos illustrate point-and-click computations, but more important, they embody the

At first I wanted to post this message as a response to a question

http://www.mapleprimes.com/questions/136153-AnimateDisplay 

But for some reason the message is not loaded.

Look at the example of animation of astroid. First you need to create animation frames as separate graphical structure (in my example - it is E[k] ). And only then by  plots [display]

The MRB constant can be computed in Maple by evalf(sum((-1)^n*(n^(1/n)-1),n=1..infinity)).

On my laptop restart; st := time(); evalf(sum((-1)^n*(n^(1/n)-1), n = 1 .. infinity), 500); time()-st gives a timming of 37.908 seconds.

Using the procedure posted at the bottom of this message st := time(); A037077(500); time()-st gives a much faster timing of 1.903 seconds.

My fastest timing for 500 digits of MRB comes from my...

My list of problems solved with Clickable-Calculus syntax-free techniques now numbers 154, spread over eight subject areas. Recently, Maplesoft posted to its website 44 of these problems, along with videos of their point-and-click solutions. Not only do these solutions demonstrate Maple functionalities, but they also have a pedagogic message, that is resequencing skills and concepts. They show how Maple can be used to obtain a solution, then show how Maple can be used to implement...

Using techniques previously used for generating color images of logistic maps and complex argument, attached is a first draft of a new Mandelbrot set fractal image applet.

A key motive behind this is the need for a faster fractal generator than is currently available on the Application Center as the older Fractal Fun! and Mandelbrot Mania with Maple entries. Those older apps warn against being run with too high a resolution for the final image, as it would take too long. In fact, even at a modest size such as 800x800 the plain black and white images can take up to 40 seconds to generate on a fast Intel i7 machine when running those older applications.

The attached worksheet can produce the basic 800x800 black and white image in approximately 0.5 seconds on the same machine. I used 64bit Maple 15.01 on Windows 7 for the timings. The attached implementration uses the Maple Compiler to attain that speed, but should fall back to Maple's quick evalhf mode in the case that the Compiler is not properly configured or enabled.

The other main difference is that this new version is more interactive: using sliders and other Components. It also inlines the image directly (using a Label), instead of as a (slow and resource intensive) density plot.

Run the Code Edit region, to begin. Make sure your GUI window is shown large enough for you to see the sides of the GUI Table conveniently.

The update image appearing in the worksheet is stored in a file, the name of which is currently set to whatever the following evaluates to in your Maple,

cat(kernelopts('homedir'),"/mandelbrot.jpg"):

You can copy the current image file aside in your OS while experimenting with the applet, if you want to save it at any step. See the start of the Code Edit region, to change this filename setting.

Here's the attachment. Comments are welcome, as I'd like to make corrections before submitting to the Application Center. Some examples of images (reduced in size for inclusion here) created with the applet are below.

 

 

The Locator object is a nice piece of Mathematica's Manipulate command's functionality. Perhaps Maple's Explore command could do something as good.

Here below is a roughly laid out example, as a Worksheet. Of course, this is not...

Here is a short wrapper which automates repeated calls to the DirectSearch 2 curve-fitting routine. It offers both time and repetition (solver restart) limits.

The global optimization package DirectSearch 2 (see Application Center link, and here) has some very nice features. One aspect which I really like is that it can do curve-fitting: to fit an expression using tabular data. By this, I mean that it can find optimal values of parameters present in an expression (formula) such that the residual error between that formula and the tabular data is minimized.

Maple itself has commands from the CurveFitting and Statistics packages for data regression, such as NonlinearFit, etc. But those use local optimization solvers, and quite often for the nonlinear case one may need a global optimizer in order to produce a good fit. The nonlinear problem may have local extrema which are not even close to being globally optimal or provide a close fit.

Maplesoft offers the (commercially available) GlobalOptimization package as an add-on to Maple, but its solvers are not hooked into those mentioned curve-fitting commands. One has to set up the proper residual-based objective function onself in order to use this for curve-fitting, and some of the bells and whistles may be harder to do.

So this is why I really like the fact that the DirectSearch 2 package has its own exported commands to do curve-fitting, integrated with its global solvers.

But as the DirectSearch package's author mentions, the fitting routine may sometimes exit too early. Repeat starts of the solver, for the very same parameter ranges, can produce varying results due to randomization steps performed by the solver. This post is branched off from another thread which involved such a problematic example.

Global optimization is often a dark art. Sometimes one may wish to simply have the engine work for 24 hours, and produce whatever best result it can. That's the basic enhancement this wrapper offers.

Here is the wrapper, and a few illustrative calls to it on the mentioned curve-fitting example that show informative  progress status messages, etc. I've tried to make the wrapper pretty generic. It could be reused for other similar purposes.

Other improvements are possible, but might make it less generic. A target option is possible, where attainment of the target would cause an immediate stop. The wrapper could be made into an appliable module, and the running best result could be stored in a module local so that any error (and ensuing halt) would not wipe out the best result from potentially hours and hours worth of conputation.

restart:
randomize():

repeater:=proc(  funccall::uneval
               , {maxtime::numeric:=60}
               , {maxiter::posint:=10}
               , {access::appliable:=proc(a) SFloat(a[1]); end proc}
               , {initial::anything:=[infinity]}
              )
          local best, current, elapsed, i, starttime;
            starttime:=time[real]();
            elapsed:=time[real]()-starttime;
            i:=1; best:=[infinity];
            while elapsed<maxtime and i<=maxiter do
              userinfo(2,repeater,`iteration `,i);
              try
                timelimit(maxtime-elapsed,assign('current',eval(funccall)));
              catch "time expired":
              end try;
              if is(access(current)<access(best)) then
                best:=current;
                userinfo(1,repeater,`new best `,access(best));
              end if;
              i:=i+1;
              elapsed:=time[real]()-starttime;
              userinfo(2,repeater,`elapsed time `,elapsed);
            end do;
            if best<>initial then
              return best;
            else
              error "time limit exceeded during first attempt";
            end if;
          end proc:


X := Vector([seq(.1*j, j = 0 .. 16), 1.65], datatype = float): 

Y := Vector([2.61, 2.62, 2.62, 2.62, 2.63, 2.63, 2.74, 2.98, 3.66,
             5.04, 7.52, 10.74, 12.62, 10.17, 5, 2.64, 11.5, 35.4],
            datatype = float):

F := a*cosh(b*x^c*sin(d*x^e));

                                    /   c    /   e\\
                         F := a cosh\b x  sin\d x //

infolevel[repeater]:=2: # or 1, or not at all (ie. 0)
interface(warnlevel=0): # disabling warnings. disable if you want.

repeater(DirectSearch:-DataFit(F
                      , [a=0..10, b=-10..10, c=0..100, d=0..7, e=0..4]
                      , X, Y, x
                      , strategy=globalsearch
                      , evaluationlimit=30000
                              ));
repeater: iteration  1
repeater: new best  9.81701944539358706
repeater: elapsed time  15.884
repeater: iteration  2
repeater: new best  2.30718902535293857
repeater: elapsed time  22.354
repeater: iteration  3
repeater: new best  0.627585701120743822e-4
repeater: elapsed time  30.777
repeater: iteration  4
repeater: elapsed time  47.959
repeater: iteration  5
repeater: new best  0.627585700905294148e-4
repeater: elapsed time  55.221
repeater: iteration  6
repeater: elapsed time  60.009
 [0.0000627585700905294, [a = 2.61748237902808, b = 1.71949329097179, 

   c = 2.30924401405164, d = 1.50333106110324, e = 1.84597267458055], 4333]


# without userinfo messages printed
infolevel[repeater]:=0:
repeater(DirectSearch:-DataFit(F
                      , [a=0..10, b=-10..10, c=0..100, d=0..7, e=0..4]
                      , X, Y, x
                      , strategy=globalsearch
                      , evaluationlimit=30000
                              ));

 [0.0000627585701341043, [a = 2.61748226209478, b = 1.71949332125427, 

   c = 2.30924369227236, d = 1.50333090706676, e = 1.84597294290477], 6050]


# illustrating early timeout
infolevel[repeater]:=2:
repeater(DirectSearch:-DataFit(F
                      , [a=0..10, b=-10..10, c=0..100, d=0..7, e=0..4]
                      , X, Y, x
                      , strategy=globalsearch
                      , evaluationlimit=30000
                              ),
         maxtime=2);

repeater: iteration  1
repeater: elapsed time  2.002
Error, (in repeater) time limit exceeded during first attempt

# illustrating iteration limit cutoff
infolevel[repeater]:=2:
repeater(DirectSearch:-DataFit(F
                      , [a=0..10, b=-10..10, c=0..100, d=0..7, e=0..4]
                      , X, Y, x
                      , strategy=globalsearch
                      , evaluationlimit=30000
                              ),
         maxiter=1);

repeater: iteration  1
repeater: new best  5.68594272127419575
repeater: elapsed time  7.084
 [5.68594272127420, [a = 3.51723075672918, b = -1.48456068506828, 

   c = 1.60544055207338, d = 6.99999999983179, e = 3.72070034285212], 2793]


# giving it a large total time limit, with reduced userinfo messages
infolevel[repeater]:=1:
Digits:=15:
repeater(DirectSearch:-DataFit(F
                      , [a=0..10, b=-10..10, c=0..100, d=0..7, e=0..4]
                      , X, Y, x
                      , strategy=globalsearch
                      , evaluationlimit=30000
                              ),
         maxtime=2000, maxiter=1000);

repeater: new best  3.10971990123465947
repeater: new best  0.627585701270853103e-4
repeater: new best  0.627585700896181428e-4
repeater: new best  0.627585700896051324e-4
repeater: new best  0.627585700895833535e-4
repeater: new best  0.627585700895607885e-4
 [0.0000627585700895608, [a = 2.61748239185387, b = -1.71949328487160, 

   c = 2.30924398692221, d = 1.50333104262348, e = 1.84597270535142], 6502]

I did not come across with a sorting algorithm animation that allows me to enter my own data, so I decided to write one in Maple.

In this worksheet, you can create an animation on sorting the integers that you have entered. If you let the worksheet to generate the data for you, you can specify the sortedness of the data. This feature allows you to visualize how some algorithms perform better or worse on data of a certain characteristic: The time complexity may not be...

First 57 58 59 60 61 62 63 Last Page 59 of 76