http://ftp.aanet.ru/pub/Linux/X11/apps/xscreensaver-2.31.tar.gz
[xscreensaver] / hacks / xlyap.c
1 /* Lyap - calculate and display Lyapunov exponents */
2
3 /* Written by Ron Record (rr@sco) 03 Sep 1991 */
4
5 /* The idea here is to calculate the Lyapunov exponent for a periodically
6  * forced logistic map (later i added several other nonlinear maps of the unit
7  * interval). In order to turn the 1-dimensional parameter space of the
8  * logistic map into a 2-dimensional parameter space, select two parameter
9  * values ('a' and 'b') then alternate the iterations of the logistic map using
10  * first 'a' then 'b' as the parameter. This program accepts an argument to
11  * specify a forcing function, so instead of just alternating 'a' and 'b', you
12  * can use 'a' as the parameter for say 6 iterations, then 'b' for 6 iterations
13  * and so on. An interesting forcing function to look at is abbabaab (the
14  * Morse-Thue sequence, an aperiodic self-similar, self-generating sequence).
15  * Anyway, step through all the values of 'a' and 'b' in the ranges you want,
16  * calculating the Lyapunov exponent for each pair of values. The exponent
17  * is calculated by iterating out a ways (specified by the variable "settle")
18  * then on subsequent iterations calculating an average of the logarithm of
19  * the absolute value of the derivative at that point. Points in parameter
20  * space with a negative Lyapunov exponent are colored one way (using the
21  * value of the exponent to index into a color map) while points with a
22  * non-negative exponent are colored differently.
23  *
24  * The algorithm was taken from the September 1991 Scientific American article
25  * by A. K. Dewdney who gives credit to Mario Markus of the Max Planck Institute
26  * for its creation. Additional information and ideas were gleaned from the
27  * discussion on alt.fractals involving Stephen Hall, Ed Kubaitis, Dave Platt
28  * and Baback Moghaddam. Assistance with colormaps and spinning color wheels
29  * and X was gleaned from Hiram Clawson. Rubber banding code was adapted from
30  * an existing Mandelbrot program written by Stacey Campbell.
31  */
32
33 #define LYAP_PATCHLEVEL 4
34 #define LYAP_VERSION "#(@) lyap 2.3 2/20/92"
35
36 #include <assert.h>
37 #include <math.h>
38
39 #include "screenhack.h"
40 #include "yarandom.h"
41 #include "hsv.h"
42 #include "vroot.h"
43
44 #include <X11/cursorfont.h> 
45 #include <X11/Xutil.h> 
46
47 char *progclass = "XLyap";
48
49 char *defaults [] = {
50   ".background:         black",
51   ".foreground:         white",
52   "*randomize:          false",
53   "*builtin:            -1",
54   "*minColor:           1",
55   "*maxColor:           256",
56   "*dwell:              50",
57   "*useLog:             false",
58   "*colorExponent:      1.0",
59   "*colorOffset:        0",
60   "*randomForce:        ",              /* 0.5 */
61   "*settle:             50",
62   "*minA:               2.0",
63   "*minB:               2.0",
64   "*wheels:             7",
65   "*function:           10101010",
66   "*forcingFunction:    abbabaab",
67   "*bRange:             ",              /* 2.0 */
68   "*startX:             0.65",
69   "*mapIndex:           ",              /* 0 */
70   "*outputFile:         ",
71   "*beNegative:         false",
72   "*rgbMax:             65000",
73   "*spinLength:         256",
74   "*show:               false",
75   "*aRange:             ",              /* 2.0 */
76   0
77 };
78
79 XrmOptionDescRec options [] = {
80   { "-randomize", ".randomize", XrmoptionNoArg, "true" },
81   { "-builtin",   ".builtin",   XrmoptionSepArg, 0 },
82   { "-C", ".minColor",          XrmoptionSepArg, 0 },   /* n */
83   { "-D", ".dwell",             XrmoptionSepArg, 0 },   /* n */
84   { "-L", ".useLog",            XrmoptionNoArg, "true" },
85   { "-M", ".colorExponent",     XrmoptionSepArg, 0 },   /* r */
86   { "-O", ".colorOffset",       XrmoptionSepArg, 0 },   /* n */
87   { "-R", ".randomForce",       XrmoptionSepArg, 0 },   /* p */
88   { "-S", ".settle",            XrmoptionSepArg, 0 },   /* n */
89   { "-a", ".minA",              XrmoptionSepArg, 0 },   /* r */
90   { "-b", ".minB",              XrmoptionSepArg, 0 },   /* n */
91   { "-c", ".wheels",            XrmoptionSepArg, 0 },   /* n */
92   { "-F", ".function",          XrmoptionSepArg, 0 },   /* 10101010 */
93   { "-f", ".forcingFunction",   XrmoptionSepArg, 0 },   /* abbabaab */
94   { "-h", ".bRange",            XrmoptionSepArg, 0 },   /* r */
95   { "-i", ".startX",            XrmoptionSepArg, 0 },   /* r */
96   { "-m", ".mapIndex",          XrmoptionSepArg, 0 },   /* n */
97   { "-o", ".outputFile",        XrmoptionSepArg, 0 },   /* filename */
98   { "-p", ".beNegative",        XrmoptionNoArg, "true" },
99   { "-r", ".rgbMax",            XrmoptionSepArg, 0 },   /* n */
100   { "-s", ".spinLength",        XrmoptionSepArg, 0 },   /* n */
101   { "-v", ".show",              XrmoptionNoArg, "true" },
102   { "-w", ".aRange",            XrmoptionSepArg, 0 },   /* r */
103   { 0, 0, 0, 0 }
104 };
105
106
107 #define ABS(a)  (((a)<0) ? (0-(a)) : (a) )
108 #define Min(x,y) ((x < y)?x:y)
109 #define Max(x,y) ((x > y)?x:y)
110
111 #ifdef SIXTEEN_COLORS
112 #define MAXPOINTS  128
113 #ifdef BIGMEM
114 #define MAXFRAMES 4
115 #else
116 #define MAXFRAMES 2
117 #endif
118 #define MAXCOLOR 16
119 static int maxcolor=16, startcolor=0, color_offset=0, mincolindex=1;
120 static int dwell=50, settle=25;
121 static int width=128, height=128, xposition=128, yposition=128;
122 #else
123 #define MAXPOINTS  256
124 #ifdef BIGMEM
125 #define MAXFRAMES 8
126 #else
127 #define MAXFRAMES 2
128 #endif
129 #define MAXCOLOR 256
130 static int maxcolor=256, startcolor=17, color_offset=96, mincolindex=33;
131 static int dwell=100, settle=50;
132 static int width=256, height=256;
133 #endif
134
135 #ifndef TRUE
136 #define TRUE 1
137 #define FALSE 0
138 #endif
139
140 static int screen;
141 static Display* dpy;
142 static Visual *visual;
143
144 static unsigned long foreground, background;
145
146 static Window canvas;
147
148 typedef struct {
149         int x, y;
150 } xy_t;
151
152 typedef struct {
153         int start_x, start_y;
154         int last_x, last_y;
155         } rubber_band_data_t;
156
157 typedef struct {
158         Cursor band_cursor;
159         double p_min, p_max, q_min, q_max;
160         rubber_band_data_t rubber_band;
161         } image_data_t;
162
163 typedef struct points_t {
164         XPoint data[MAXCOLOR][MAXPOINTS];
165         int npoints[MAXCOLOR];
166         } points_t;
167
168 static points_t Points;
169 static image_data_t rubber_data;
170
171 #ifndef TRUE
172 #define TRUE 1
173 #define FALSE 0
174 #endif
175
176 static GC Data_GC[MAXCOLOR], RubberGC;
177
178 #define MAXINDEX 64
179 #define FUNCMAXINDEX 16
180 #define MAXWHEELS 7
181 #define NUMMAPS 5
182
183 typedef double (*PFD)(double,double);
184
185 static double logistic(double,double), circle(double,double), leftlog(double,double), rightlog(double,double), doublelog(double,double);
186 static double dlogistic(double,double), dcircle(double,double), dleftlog(double,double), drightlog(double,double), ddoublelog(double,double);
187 static PFD map, deriv;
188 static PFD Maps[NUMMAPS] = { logistic, circle, leftlog, rightlog, doublelog };
189 static PFD Derivs[NUMMAPS] = { dlogistic, dcircle, dleftlog, drightlog, ddoublelog };
190
191 static int aflag=0, bflag=0, wflag=0, hflag=0, Rflag=0;
192 static double pmins[NUMMAPS] = { 2.0, 0.0, 0.0, 0.0, 0.0 };
193 static double pmaxs[NUMMAPS] = { 4.0, 1.0, 6.75, 6.75, 16.0 };
194 static double amins[NUMMAPS] = { 2.0, 0.0, 0.0, 0.0, 0.0 };
195 static double aranges[NUMMAPS] = { 2.0, 1.0, 6.75, 6.75, 16.0 };
196 static double bmins[NUMMAPS] = { 2.0, 0.0, 0.0, 0.0, 0.0 };
197 static double branges[NUMMAPS] = { 2.0, 1.0, 6.75, 6.75, 16.0 };
198
199 static int   forcing[MAXINDEX] = { 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
200                         0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
201                         0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1 };
202 static int   Forcing[FUNCMAXINDEX] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
203
204 static int   maxindex = MAXINDEX;
205 static int   funcmaxindex = FUNCMAXINDEX;
206 static double   min_a=2.0, min_b=2.0, a_range=2.0, b_range=2.0, minlyap=1.0;
207 static double  max_a=4.0, max_b=4.0;
208 static double  start_x=0.65, lyapunov, a_inc, b_inc, a, b;
209 static int      numcolors=16, numfreecols, displayplanes, lowrange;
210 static xy_t     point;
211 static Pixmap  pixmap;
212 static Colormap cmap;
213 static XColor   Colors[MAXCOLOR];
214 static double  *exponents[MAXFRAMES];
215 static double  a_minimums[MAXFRAMES], b_minimums[MAXFRAMES];
216 static double  a_maximums[MAXFRAMES], b_maximums[MAXFRAMES];
217 static double  minexp, maxexp, prob=0.5;
218 static int     expind[MAXFRAMES]={0}, resized[MAXFRAMES]={0};
219 static int      numwheels=MAXWHEELS, force=0, Force=0, negative=1;
220 static int     rgb_max=65000, nostart=1, stripe_interval=7;
221 static int      save=1, show=0, useprod=1, spinlength=256, savefile=0;
222 static int      maxframe=0, frame=0, dorecalc=0, mapindex=0, run=1;
223 static char     *outname="lyap.out";
224
225
226 const char * const version = LYAP_VERSION;
227
228 static void resize(void);
229 static void redisplay(Window w, XExposeEvent *event);
230 static void Spin(Window w);
231 static void show_defaults(void);
232 static void StartRubberBand(Window w, image_data_t *data, XEvent *event);
233 static void TrackRubberBand(Window w, image_data_t *data, XEvent *event);
234 static void EndRubberBand(Window w, image_data_t *data, XEvent *event);
235 static void CreateXorGC(void);
236 static void InitBuffer(void);
237 static void BufferPoint(Display *display, Window window, int color,
238                         int x, int y);
239 static void FlushBuffer(void);
240 static void init_canvas(void);
241 static void init_data(void);
242 static void init_color(void);
243 static void parseargs(void);
244 static void Clear(void);
245 static void setupmem(void);
246 static void main_event(void);
247 static int complyap(void);
248 static void Getkey(XKeyEvent *event);
249 static int sendpoint(double expo);
250 static void save_to_file(void);
251 static void setforcing(void);
252 static void check_params(int mapnum, int parnum);
253 static void usage(void);
254 static void Destroy_frame(void);
255 static void freemem(void);
256 static void Redraw(void);
257 static void redraw(double *exparray, int index, int cont);
258 static void recalc(void);
259 static void SetupCorners(XPoint *corners, image_data_t *data);
260 static void set_new_params(Window w, image_data_t *data);
261 static void go_down(void);
262 static void go_back(void);
263 static void go_init(void);
264 static void jumpwin(void);
265 static void print_help(void);
266 static void print_values(void);
267
268
269 void
270 screenhack (Display *d, Window window)
271 {
272   XWindowAttributes xgwa;
273   int builtin = -1;
274   dpy = d;
275   XGetWindowAttributes (dpy, window, &xgwa);
276   width = xgwa.width;
277   height = xgwa.height;
278   visual = xgwa.visual;
279   cmap = xgwa.colormap;
280
281   parseargs();
282
283   if (get_boolean_resource("randomize", "Boolean"))
284     builtin = random() % 22;
285   else {
286     char *s = get_string_resource("builtin", "Integer");
287     if (s && *s)
288       builtin = atoi(s);
289     if (s) free (s);
290   }
291     
292   if (builtin >= 0)
293     {
294       char *ff = 0;
295       switch (builtin) {
296       case 0:
297         min_a = 3.75; aflag++;
298         min_b = 3.299999; bflag++;
299         a_range = 0.05; wflag++;
300         b_range = 0.05; hflag++;
301         dwell = 200;
302         settle = 100;
303         ff = "abaabbaaabbb";
304         break;
305
306       case 1:
307         min_a = 3.8; aflag++;
308         min_b = 3.2; bflag++;
309         b_range = .05; hflag++;
310         a_range = .05; wflag++;
311         ff = "bbbbbaaaaa";
312         break;
313
314       case 2:
315         min_a =  3.4; aflag++;
316         min_b =  3.04; bflag++;
317         a_range =  .5; wflag++;
318         b_range =  .5; hflag++;
319         ff = "abbbbbbbbb";
320         settle = 500;
321         dwell = 1000;
322         break;
323
324       case 3:
325         min_a = 3.5; aflag++;
326         min_b = 3.0; bflag++;
327         a_range = 0.2; wflag++;
328         b_range = 0.2; hflag++;
329         dwell = 600;
330         settle = 300;
331         ff = "aaabbbab";
332         break;
333
334       case 4:
335         min_a = 3.55667; aflag++;
336         min_b = 3.2; bflag++;
337         b_range = .05; hflag++;
338         a_range = .05; wflag++;
339         ff = "bbbbbaaaaa";
340         break;
341
342       case 5:
343         min_a = 3.79; aflag++;
344         min_b = 3.22; bflag++;
345         b_range = .02999; hflag++;
346         a_range = .02999; wflag++;
347         ff = "bbbbbaaaaa";
348         break;
349
350       case 6:
351         min_a = 3.7999; aflag++;
352         min_b = 3.299999; bflag++;
353         a_range = 0.2; wflag++;
354         b_range = 0.2; hflag++;
355         dwell = 300;
356         settle = 150;
357         ff = "abaabbaaabbb";
358         break;
359
360       case 7:
361         min_a = 3.89; aflag++;
362         min_b = 3.22; bflag++;
363         b_range = .028; hflag++;
364         a_range = .02999; wflag++;
365         ff = "bbbbbaaaaa";
366         settle = 600;
367         dwell = 1000;
368         break;
369
370       case 8:
371         min_a = 3.2; aflag++;
372         min_b = 3.7; bflag++;
373         a_range = 0.05; wflag++;
374         b_range = .005; hflag++;
375         ff = "abbbbaa";
376         break;
377
378       case 9:
379         ff = "aaaaaabbbbbb";
380         mapindex = 1;
381         dwell =  400;
382         settle =  200;
383         minlyap = maxexp = ABS(-0.85);
384         minexp = -1.0 * minlyap;
385         break;
386
387       case 10:
388         ff = "aaaaaabbbbbb";
389         mapindex = 1;
390         dwell =  400;
391         settle = 200;
392         minlyap = maxexp = ABS(-0.85);
393         minexp = -1.0 * minlyap;
394         break;
395
396       case 11:
397         mapindex = 1;
398         dwell =  400;
399         settle = 200;
400         minlyap = maxexp = ABS(-0.85);
401         minexp = -1.0 * minlyap;
402         break;
403
404       case 12:
405         ff = "abbb";
406         mapindex = 1;
407         dwell =  400;
408         settle = 200;
409         minlyap = maxexp = ABS(-0.85);
410         minexp = -1.0 * minlyap;
411         break;
412
413       case 13:
414         ff = "abbabaab";
415         mapindex = 1;
416         dwell =  400;
417         settle = 200;
418         minlyap = maxexp = ABS(-0.85);
419         minexp = -1.0 * minlyap;
420         break;
421
422       case 14:
423         ff = "abbabaab";
424         dwell =  800;
425         settle = 200;
426         minlyap = maxexp = ABS(-0.85);
427         minexp = -1.0 * minlyap;
428         /* ####  -x 0.05 */
429         min_a = 3.91; aflag++;
430         a_range =  0.0899999999; wflag++;
431         min_b =  3.28; bflag++;
432         b_range =  0.35; hflag++;
433         break;
434
435       case 15:
436         ff = "aaaaaabbbbbb";
437         dwell =  400;
438         settle = 200;
439         minlyap = maxexp = ABS(-0.85);
440         minexp = -1.0 * minlyap;
441         break;
442
443       case 16:
444         dwell =  400;
445         settle = 200;
446         minlyap = maxexp = ABS(-0.85);
447         minexp = -1.0 * minlyap;
448         break;
449
450       case 17:
451         ff = "abbb";
452         dwell =  400;
453         settle = 200;
454         minlyap = maxexp = ABS(-0.85);
455         minexp = -1.0 * minlyap;
456         break;
457
458       case 18:
459         ff = "abbabaab";
460         dwell =  400;
461         settle = 200;
462         minlyap = maxexp = ABS(-0.85);
463         minexp = -1.0 * minlyap;
464         break;
465
466       case 19:
467         mapindex = 2;
468         ff = "aaaaaabbbbbb";
469         dwell =  400;
470         settle = 200;
471         minlyap = maxexp = ABS(-0.85);
472         minexp = -1.0 * minlyap;
473         break;
474
475       case 20:
476         mapindex = 2;
477         dwell =  400;
478         settle = 200;
479         minlyap = maxexp = ABS(-0.85);
480         minexp = -1.0 * minlyap;
481         break;
482
483       case 21:
484         mapindex = 2;
485         ff = "abbb";
486         dwell =  400;
487         settle = 200;
488         minlyap = maxexp = ABS(-0.85);
489         minexp = -1.0 * minlyap;
490         break;
491
492       case 22:
493         mapindex = 2;
494         ff = "abbabaab";
495         dwell =  400;
496         settle = 200;
497         minlyap = maxexp = ABS(-0.85);
498         minexp = -1.0 * minlyap;
499         break;
500       }
501
502       if (ff) {
503         char *ch;
504         int bindex = 0;
505         maxindex = strlen(ff);
506         if (maxindex > MAXINDEX)
507           usage();
508         ch = ff;
509         force++;
510         while (bindex < maxindex) {
511           if (*ch == 'a')
512             forcing[bindex++] = 0;
513           else if (*ch == 'b')
514             forcing[bindex++] = 1;
515           else
516             usage();
517           ch++;
518         }
519       }
520     }
521
522   screen = DefaultScreen(dpy);
523   background = BlackPixel(dpy, screen);
524   setupmem();
525   init_data();
526   if (displayplanes > 1)
527     foreground = startcolor;
528   else
529     foreground = WhitePixel(dpy, screen);
530
531   /*
532   * Create the window to display the Lyapunov exponents
533   */
534   canvas = window;
535   init_canvas();
536
537   if (window != DefaultRootWindow(dpy))
538     XSelectInput(dpy,canvas,KeyPressMask|ButtonPressMask|ButtonMotionMask|
539                  ButtonReleaseMask|ExposureMask|StructureNotifyMask);
540   if (displayplanes > 1) {
541     init_color();
542   } else {
543     XQueryColors(dpy, DefaultColormap(dpy, DefaultScreen(dpy)),
544         Colors, numcolors);
545   }
546   pixmap = XCreatePixmap(dpy, DefaultRootWindow(dpy),
547                          width, height, DefaultDepth(dpy, screen));
548   rubber_data.band_cursor = XCreateFontCursor(dpy, XC_hand2);
549   CreateXorGC();
550   Clear();
551   for(;;)
552       main_event();
553 }
554
555 static void
556 main_event(void)
557 {
558   int n;
559   XEvent event;
560
561   if (complyap() == TRUE)
562       run=0;
563   n = XEventsQueued(dpy, QueuedAfterFlush);
564   while (n--) {
565           XNextEvent(dpy, &event);
566             switch(event.type)
567             {
568             case KeyPress:
569     Getkey(&event.xkey);
570     break;
571             case Expose:
572     redisplay(canvas, &event.xexpose);
573           break;
574             case ConfigureNotify:
575     resize();
576           break;
577             case ButtonPress:
578     StartRubberBand(canvas, &rubber_data, &event);
579           break;
580             case MotionNotify:
581     TrackRubberBand(canvas, &rubber_data, &event);
582           break;
583             case ButtonRelease:
584     EndRubberBand(canvas, &rubber_data, &event);
585           break;
586             }
587         }
588 }
589
590 /* complyap() is the guts of the program. This is where the Lyapunov exponent
591  * is calculated. For each iteration (past some large number of iterations)
592  * calculate the logarithm of the absolute value of the derivative at that
593  * point. Then average them over some large number of iterations. Some small
594  * speed up is achieved by utilizing the fact that log(a*b) = log(a) + log(b).
595  */
596 static int
597 complyap(void)
598 {
599   register i, bindex;
600   double total, prod, x, dx, r;
601
602   if (!run)
603     return TRUE;
604   a += a_inc;
605   if (a >= max_a)
606     if (sendpoint(lyapunov) == TRUE)
607       return FALSE;
608     else {
609       FlushBuffer();
610       if (savefile)
611         save_to_file();
612       return TRUE;
613     }
614   if (b >= max_b) {
615     FlushBuffer();
616     if (savefile)
617       save_to_file();
618     return TRUE;
619   }
620   prod = 1.0;
621   total = 0.0;
622   bindex = 0;
623   x = start_x;
624   r = (forcing[bindex]) ? b : a;
625 #ifdef MAPS
626   findex = 0;
627   map = Maps[Forcing[findex]];
628 #endif
629   for (i=0;i<settle;i++) {     /* Here's where we let the thing */
630     x = (*map)(x, r);    /* "settle down". There is usually */
631     if (++bindex >= maxindex) { /* some initial "noise" in the */
632       bindex = 0;    /* iterations. How can we optimize */
633       if (Rflag)      /* the value of settle ??? */
634           setforcing();
635     }
636     r = (forcing[bindex]) ? b : a;
637 #ifdef MAPS
638     if (++findex >= funcmaxindex)
639       findex = 0;
640     map = Maps[Forcing[findex]];
641 #endif
642   }
643 #ifdef MAPS
644   deriv = Derivs[Forcing[findex]];
645 #endif
646   if (useprod) {      /* using log(a*b) */
647     for (i=0;i<dwell;i++) {
648       x = (*map)(x, r);
649       dx = (*deriv)(x, r); /* ABS is a macro, so don't be fancy */
650       dx = ABS(dx);
651       if (dx == 0.0) /* log(0) is nasty so break out. */
652       {
653         i++;
654         break;
655       }
656       prod *= dx;
657       /* we need to prevent overflow and underflow */
658       if ((prod > 1.0e12) || (prod < 1.0e-12)) {
659         total += log(prod);
660         prod = 1.0;
661       }
662       if (++bindex >= maxindex) {
663         bindex = 0;
664         if (Rflag)
665           setforcing();
666       }
667       r = (forcing[bindex]) ? b : a;
668 #ifdef MAPS
669       if (++findex >= funcmaxindex)
670         findex = 0;
671       map = Maps[Forcing[findex]];
672       deriv = Derivs[Forcing[findex]];
673 #endif
674     }
675     total += log(prod);
676     lyapunov = (total * M_LOG2E) / (double)i;   
677   }
678   else {        /* use log(a) + log(b) */
679     for (i=0;i<dwell;i++) {
680       x = (*map)(x, r);
681       dx = (*deriv)(x, r); /* ABS is a macro, so don't be fancy */
682       dx = ABS(dx);
683       if (x == 0.0)  /* log(0) check */
684       {
685         i++;
686         break;
687       }
688       total += log(dx);
689       if (++bindex >= maxindex) {
690         bindex = 0;
691         if (Rflag)
692           setforcing();
693       }
694       r = (forcing[bindex]) ? b : a;
695 #ifdef MAPS
696       if (++findex >= funcmaxindex)
697         findex = 0;
698       map = Maps[Forcing[findex]];
699       deriv = Derivs[Forcing[findex]];
700 #endif
701     }
702     lyapunov = (total * M_LOG2E) / (double)i;
703   }
704
705   if (sendpoint(lyapunov) == TRUE)
706     return FALSE;
707   else {
708     FlushBuffer();
709     if (savefile)
710       save_to_file();
711     return TRUE;
712   }
713 }
714
715 static double
716 logistic(double x, double r)        /* the familiar logistic map */
717 {
718   return(r * x * (1.0 - x));
719 }
720
721 static double
722 dlogistic(double x, double r)       /* the derivative of logistic map */
723 {
724   return(r - (2.0 * r * x));
725 }
726
727 static double
728 circle(double x, double r)        /* sin() hump or sorta like the circle map */
729 {
730   return(r * sin(M_PI * x));
731 }
732
733 static double
734 dcircle(double x, double r)       /* derivative of the "sin() hump" */
735 {
736   return(r * M_PI * cos(M_PI * x));
737 }
738
739 static double
740 leftlog(double x, double r)       /* left skewed logistic */
741 {
742   double d;
743
744   d = 1.0 - x;
745   return(r * x * d * d);
746 }
747
748 static double
749 dleftlog(double x, double r)    /* derivative of the left skewed logistic */
750 {
751   return(r * (1.0 - (4.0 * x) + (3.0 * x * x)));
752 }
753
754 static double
755 rightlog(double x, double r)    /* right skewed logistic */
756 {
757   return(r * x * x * (1.0 - x));
758 }
759
760 static double
761 drightlog(double x, double r)    /* derivative of the right skewed logistic */
762 {
763   return(r * ((2.0 * x) - (3.0 * x * x)));
764 }
765
766 static double
767 doublelog(double x, double r)    /* double logistic */
768 {
769   double d;
770
771   d = 1.0 - x;
772   return(r * x * x * d * d);
773 }
774
775 static double
776 ddoublelog(double x, double r)   /* derivative of the double logistic */
777 {
778   double d;
779
780   d = x * x;
781   return(r * ((2.0 * x) - (6.0 * d) + (4.0 * x * d)));
782 }
783
784 static void
785 init_data(void)
786 {
787   numcolors = XDisplayCells(dpy, XDefaultScreen(dpy));
788   displayplanes = DisplayPlanes(dpy, XDefaultScreen(dpy));
789   if (numcolors > maxcolor)
790     numcolors = maxcolor;
791   numfreecols = numcolors - mincolindex;
792   lowrange = mincolindex - startcolor;
793   a_inc = a_range / (double)width;
794   b_inc = b_range / (double)height;
795   point.x = -1;
796   point.y = 0;
797   a = rubber_data.p_min = min_a;
798   b = rubber_data.q_min = min_b;
799   rubber_data.p_max = max_a;
800   rubber_data.q_max = max_b;
801   if (show)
802     show_defaults();
803   InitBuffer();
804 }
805
806 static void
807 init_canvas(void)
808 {
809   static int i;
810
811   /*
812   * create default, writable, graphics contexts for the canvas.
813   */
814         for (i=0; i<maxcolor; i++) {
815             Data_GC[i] = XCreateGC(dpy, DefaultRootWindow(dpy),
816                 (unsigned long) NULL, (XGCValues *) NULL);
817             /* set the background to black */
818             XSetBackground(dpy,Data_GC[i],BlackPixel(dpy,XDefaultScreen(dpy)));
819             /* set the foreground of the ith context to i */
820             XSetForeground(dpy, Data_GC[i], i);
821         }
822         if (displayplanes == 1) {
823             XSetForeground(dpy,Data_GC[0],BlackPixel(dpy,XDefaultScreen(dpy)));
824             XSetForeground(dpy,Data_GC[1],WhitePixel(dpy,XDefaultScreen(dpy)));
825         }
826 }
827
828 #if 0
829 static void
830 hls2rgb(int hue_light_sat[3],
831         int rgb[3])             /*      Each in range [0..65535]        */
832 {
833   unsigned short r, g, b;
834   hsv_to_rgb((int) (hue_light_sat[0] / 10),             /* 0-3600 -> 0-360 */
835              (int) ((hue_light_sat[2]/1000.0) * 64435), /* 0-1000 -> 0-65535 */
836              (int) ((hue_light_sat[1]/1000.0) * 64435), /* 0-1000 -> 0-65535 */
837              &r, &g, &b);
838   rgb[0] = r;
839   rgb[1] = g;
840   rgb[2] = b;
841 }
842 #endif /* 0 */
843
844
845 static void
846 init_color(void)
847 {
848 #if 1
849
850   int i;
851   XColor colors[256];
852   int ncolors = maxcolor;
853   Bool writable = False;
854   make_smooth_colormap(dpy, visual, cmap,
855                         colors, &ncolors, True, &writable, True);
856
857   for (i = 0; i < maxcolor; i++)
858     XSetForeground(dpy, Data_GC[i],
859                    colors[((int) ((i / ((float)maxcolor)) * ncolors))].pixel);
860
861 #else
862   static int i, j, colgap, leg, step;
863   static Visual *visual;
864   Colormap def_cmap;
865   int hls[3], rgb[3];
866
867   def_cmap = DefaultColormap(dpy, DefaultScreen(dpy));
868   for (i=0; i<numcolors; i++) {
869     Colors[i].pixel = i;
870     Colors[i].flags = DoRed|DoGreen|DoBlue;
871   }
872
873   /* Try to write into a new color map */
874   visual = DefaultVisual(dpy, DefaultScreen(dpy));
875   cmap = XCreateColormap(dpy, canvas, visual, AllocAll);
876   XQueryColors(dpy, def_cmap, Colors, numcolors);
877   if (mincolindex)
878     colgap = rgb_max / mincolindex;
879   else
880     colgap = rgb_max;
881   hls[0] = 50;  /* Hue in low range */
882   hls[2] = 1000;  /* Fully saturated */
883   for (i=startcolor; i<lowrange + startcolor; i++) {
884     hls[1] = 1000L * (i-startcolor) / lowrange;
885     hls2rgb(hls, rgb);
886     Colors[i].red = rgb[0];
887     Colors[i].green = rgb[1];
888     Colors[i].blue = rgb[2];
889   }
890   colgap = rgb_max / numcolors;
891   if (numwheels == 0)
892     XQueryColors(dpy, def_cmap, Colors, numcolors);
893   else if (numwheels == 1) {
894     colgap = 2*rgb_max/(numcolors - color_offset);
895     for (i=mincolindex; i<(numcolors/2); i++) {
896       Colors[i].blue = 0;
897       Colors[i].green=((i+color_offset)*colgap);
898       Colors[i].red=((i+color_offset)*colgap);
899     }
900     for (i=(numcolors/2); i<(numcolors); i++) {
901       Colors[i].blue = 0;
902       Colors[i].green=(((numcolors-i)+color_offset)*colgap);
903       Colors[i].red=(((numcolors-i)+color_offset)*colgap);
904     }
905   }
906   else if (numwheels == 2) {
907           hls[0] = 800; /* Hue in mid range */
908           hls[2] = 1000;  /* Fully saturated */
909           for (i=startcolor; i<lowrange + startcolor; i++) {
910       hls[1] = 1000L * (i-startcolor) / lowrange;
911       hls2rgb(hls, rgb);
912       Colors[i].red = rgb[0];
913       Colors[i].green = rgb[1];
914       Colors[i].blue = rgb[2];
915           }
916     for (i=mincolindex; i<(numcolors/2); i++) {
917       Colors[i].blue = rgb_max;
918       Colors[i].green = 0;
919       Colors[i].red=(i*2*rgb_max/numcolors);
920     }
921     for (i=(numcolors/2); i<numcolors; i++) {
922       Colors[i].blue = rgb_max;
923       Colors[i].green = 0;
924       Colors[i].red=((numcolors - i)*2*rgb_max/numcolors);
925     }
926   }
927   else if (numwheels == 3) {
928           hls[0] = 800; /* Hue in mid range */
929           hls[2] = 1000;  /* Fully saturated */
930           for (i=startcolor; i<lowrange + startcolor; i++) {
931       hls[1] = 1000L * (i-startcolor) / lowrange;
932       hls2rgb(hls, rgb);
933       Colors[i].red = rgb[0];
934       Colors[i].green = rgb[1];
935       Colors[i].blue = rgb[2];
936           }
937     colgap = 4*rgb_max/numcolors;
938     for (i=mincolindex; i<(numcolors/4); i++) {
939       Colors[i].blue = rgb_max;
940       Colors[i].green = 0;
941       Colors[i].red=(i*colgap);
942     }
943     for (i=(numcolors/4); i<(numcolors/2); i++) {
944       Colors[i].red = rgb_max;
945       Colors[i].green = 0;
946       Colors[i].blue=((numcolors/2) - i) * colgap;
947     }
948     for (i=(numcolors/2); i<(0.75*numcolors); i++) {
949       Colors[i].red = rgb_max;
950       Colors[i].blue=(i * colgap);
951       Colors[i].green = 0;
952     }
953     for (i=(0.75*numcolors); i<numcolors; i++) {
954       Colors[i].blue = rgb_max;
955       Colors[i].green = 0;
956       Colors[i].red=(numcolors-i)*colgap;
957     }
958   }
959   else if (numwheels == 4) {
960           hls[0] = 800; /* Hue in mid range */
961           hls[2] = 1000;  /* Fully saturated */
962           for (i=startcolor; i<lowrange + startcolor; i++) {
963       hls[1] = 1000L * (i-startcolor) / lowrange;
964       hls2rgb(hls, rgb);
965       Colors[i].red = rgb[0];
966       Colors[i].green = rgb[1];
967       Colors[i].blue = rgb[2];
968           }
969     colgap = numwheels * rgb_max / numcolors;
970     for (i=mincolindex; i<(numcolors/numwheels); i++) {
971       Colors[i].blue = rgb_max;
972       Colors[i].green = 0;
973       Colors[i].red=(i*colgap);
974     }
975     for (i=(numcolors/numwheels); i<(2*numcolors/numwheels); i++) {
976       Colors[i].red = rgb_max;
977       Colors[i].green = 0;
978       Colors[i].blue=((2*numcolors/numwheels) - i) * colgap;
979     }
980     for (i=(2*numcolors/numwheels); i<numcolors; i++) {
981       Colors[i].red = rgb_max;
982       Colors[i].green=(i - (2*numcolors/numwheels)) * colgap;
983       Colors[i].blue = 0;
984     }
985   }
986   else if (numwheels == 5) {
987     hls[1] = 700; /* Lightness in midrange */
988     hls[2] = 1000;  /* Fully saturated */
989     for (i=mincolindex; i<numcolors; i++) {
990       hls[0] = 3600L * i / numcolors;
991       hls2rgb(hls, rgb);
992       Colors[i].red = rgb[0];
993       Colors[i].green = rgb[1];
994       Colors[i].blue = rgb[2];
995     }
996     for (i=mincolindex; i<numcolors; i+=stripe_interval) {
997       hls[0] = 3600L * i / numcolors;
998       hls2rgb(hls, rgb);
999       Colors[i].red = rgb[0] / 2;
1000       Colors[i].green = rgb[1] / 2;
1001       Colors[i].blue = rgb[2] / 2;
1002     }
1003   }
1004   else if (numwheels == 6) {
1005       hls[0] = 800; /* Hue in mid range */
1006       hls[2] = 1000;  /* Fully saturated */
1007       for (i=startcolor; i<lowrange + startcolor; i++) {
1008     hls[1] = 1000L * (i-startcolor) / lowrange;
1009     hls2rgb(hls, rgb);
1010     Colors[i].red = rgb[0];
1011     Colors[i].green = rgb[1];
1012     Colors[i].blue = rgb[2];
1013       }
1014       step = numfreecols / 3;
1015       leg = step+mincolindex;
1016       for (i = mincolindex; i < leg; ++i)
1017       {
1018     Colors[i].pixel = i;
1019     Colors[i].red = fabs(65535 - (double)i / step * 65535.0);
1020     Colors[i].blue = (double)i / step * 65535.0;
1021     Colors[i].green = 0;
1022     Colors[i].flags = DoRed | DoGreen | DoBlue;
1023       }
1024       for (j = 0, i = leg, leg += step; i < leg; ++i, ++j)
1025       {
1026     Colors[i].pixel = i;
1027     Colors[i].red = (double)j / step * 65535.0;
1028     Colors[i].blue = 65535;
1029     Colors[i].green = Colors[i].red;
1030     Colors[i].flags = DoRed | DoGreen | DoBlue;
1031       }
1032       for (j = 0, i = leg, leg += step; i < leg; ++i, ++j)
1033       {
1034     Colors[i].pixel = i;
1035     Colors[i].red = 65535;
1036     Colors[i].blue = fabs(65535 - (double)j / step * 65535.0);
1037     Colors[i].green = Colors[i].blue;
1038     Colors[i].flags = DoRed | DoGreen | DoBlue;
1039       }
1040   }
1041   else if (numwheels == MAXWHEELS) {  /* rainbow palette */
1042     hls[1] = 500; /* Lightness in midrange */
1043     hls[2] = 1000;  /* Fully saturated */
1044     for (i=mincolindex; i<numcolors; i++) {
1045       hls[0] = 3600L * i / numcolors;
1046       hls2rgb(hls, rgb);
1047       Colors[i].red = rgb[0];
1048       Colors[i].green = rgb[1];
1049       Colors[i].blue = rgb[2];
1050     }
1051   }
1052   XStoreColors(dpy, cmap, Colors, numcolors);
1053
1054   XSetWindowColormap(dpy, canvas, cmap);
1055 #endif
1056 }
1057
1058 static void
1059 parseargs()
1060 {
1061   static int i;
1062   int bindex=0, findex;
1063   char *s, *ch;
1064
1065   map = Maps[0];
1066   deriv = Derivs[0];
1067   maxexp=minlyap; minexp= -1.0 * minlyap;
1068
1069   mincolindex = get_integer_resource("minColor", "Integer");
1070   dwell = get_integer_resource("dwell", "Integer");
1071 #ifdef MAPS
1072   {
1073     char *optarg = get_string_resource("function", "String");
1074     funcmaxindex = strlen(optarg);
1075     if (funcmaxindex > FUNCMAXINDEX)
1076       usage();
1077     ch = optarg;
1078     Force++;
1079     for (findex=0;findex<funcmaxindex;findex++) {
1080       Forcing[findex] = (int)(*ch++ - '0');;
1081       if (Forcing[findex] >= NUMMAPS)
1082         usage();
1083     }
1084   }
1085 #endif
1086   if (get_boolean_resource("useLog", "Boolean"))
1087     useprod=0;
1088
1089   minlyap=ABS(get_float_resource("colorExponent", "Float"));
1090   maxexp=minlyap;
1091   minexp= -1.0 * minlyap;
1092
1093   color_offset = get_integer_resource("colorOffset", "Integer");
1094
1095   maxcolor=ABS(get_integer_resource("maxColor", "Integer"));
1096   if ((maxcolor - startcolor) <= 0)
1097     startcolor = 0;
1098   if ((maxcolor - mincolindex) <= 0) {
1099     mincolindex = 1;
1100     color_offset = 0;
1101   }
1102
1103   s = get_string_resource("randomForce", "Float");
1104   if (s && *s) {
1105     prob=atof(s); Rflag++; setforcing();
1106   }
1107
1108   settle = get_integer_resource("settle", "Integer");
1109
1110   s = get_string_resource("minA", "Float");
1111   if (s && *s) {
1112     min_a = atof(s);
1113     aflag++;
1114   }
1115   
1116   s = get_string_resource("minB", "Float");
1117   if (s && *s) {
1118     min_b=atof(s); bflag++;
1119   }
1120   
1121   numwheels = get_integer_resource("wheels", "Integer");
1122
1123   s = get_string_resource("forcingFunction", "String");
1124   if (s && *s) {
1125     maxindex = strlen(s);
1126     if (maxindex > MAXINDEX)
1127       usage();
1128     ch = s;
1129     force++;
1130     while (bindex < maxindex) {
1131       if (*ch == 'a')
1132         forcing[bindex++] = 0;
1133       else if (*ch == 'b')
1134         forcing[bindex++] = 1;
1135       else
1136         usage();
1137       ch++;
1138     }
1139   }
1140
1141   s = get_string_resource("bRange", "Float");
1142   if (s && *s) {
1143     b_range = atof(s);
1144     hflag++;
1145   }
1146
1147   start_x = get_float_resource("startX", "Float");
1148
1149   s = get_string_resource("mapIndex", "Integer");
1150   if (s && *s) {
1151     mapindex=atoi(s);
1152     if ((mapindex >= NUMMAPS) || (mapindex < 0))
1153       usage();
1154     map = Maps[mapindex];
1155     deriv = Derivs[mapindex];
1156     if (!aflag)
1157       min_a = amins[mapindex];
1158     if (!wflag)
1159       a_range = aranges[mapindex];
1160     if (!bflag)
1161       min_b = bmins[mapindex];
1162     if (!hflag)
1163       b_range = branges[mapindex];
1164     if (!Force)
1165       for (i=0;i<FUNCMAXINDEX;i++)
1166         Forcing[i] = mapindex;
1167   }
1168
1169   outname = get_string_resource("outputFile", "Integer");
1170
1171   if (get_boolean_resource("beNegative", "Boolean"))
1172     negative--;
1173
1174   rgb_max = get_integer_resource("rgbMax", "Integer");
1175   spinlength = get_integer_resource("spinLength", "Integer");
1176   show = get_boolean_resource("show", "Boolean");
1177
1178   s = get_string_resource("aRange", "Float");
1179   if (s && *s) {
1180     a_range = atof(s); wflag++;
1181   }
1182
1183   max_a = min_a + a_range;
1184   max_b = min_b + b_range;
1185
1186   a_minimums[0] = min_a; b_minimums[0] = min_b;
1187   a_maximums[0] = max_a; b_maximums[0] = max_b;
1188
1189   if (Force)
1190     if (maxindex == funcmaxindex)
1191       for (findex=0;findex<funcmaxindex;findex++)
1192         check_params(Forcing[findex],forcing[findex]);
1193     else
1194       fprintf(stderr, "Warning! Unable to check parameters\n");
1195   else
1196     check_params(mapindex,2);
1197 }
1198
1199 static void
1200 check_params(int mapnum, int parnum)
1201 {
1202
1203   if (parnum != 1) {
1204       if ((max_a > pmaxs[mapnum]) || (min_a < pmins[mapnum])) {
1205     fprintf(stderr, "Warning! Parameter 'a' out of range.\n");
1206     fprintf(stderr, "You have requested a range of (%f,%f).\n",
1207       min_a,max_a);
1208     fprintf(stderr, "Valid range is (%f,%f).\n",
1209       pmins[mapnum],pmaxs[mapnum]);
1210       }
1211   }
1212   if (parnum != 0) {
1213       if ((max_b > pmaxs[mapnum]) || (min_b < pmins[mapnum])) {
1214     fprintf(stderr, "Warning! Parameter 'b' out of range.\n");
1215     fprintf(stderr, "You have requested a range of (%f,%f).\n",
1216       min_b,max_b);
1217     fprintf(stderr, "Valid range is (%f,%f).\n",
1218       pmins[mapnum],pmaxs[mapnum]);
1219       }
1220   }
1221 }
1222
1223 static void
1224 usage(void)
1225 {
1226     fprintf(stderr,"lyap [-BLs][-W#][-H#][-a#][-b#][-w#][-h#][-x xstart]\n");
1227     fprintf(stderr,"\t[-M#][-S#][-D#][-f string][-r#][-O#][-C#][-c#][-m#]\n");
1228 #ifdef MAPS
1229     fprintf(stderr,"\t[-F string]\n");
1230 #endif
1231     fprintf(stderr,"\tWhere: -C# specifies the minimum color index\n");
1232     fprintf(stderr,"\t       -r# specifies the maxzimum rgb value\n");
1233     fprintf(stderr,"\t       -u displays this message\n");
1234     fprintf(stderr,"\t       -a# specifies the minimum horizontal parameter\n");
1235     fprintf(stderr,"\t       -b# specifies the minimum vertical parameter\n");
1236     fprintf(stderr,"\t       -w# specifies the horizontal parameter range\n");
1237     fprintf(stderr,"\t       -h# specifies the vertical parameter range\n");
1238     fprintf(stderr,"\t       -D# specifies the dwell\n");
1239     fprintf(stderr,"\t       -S# specifies the settle\n");
1240     fprintf(stderr,"\t       -H# specifies the initial window height\n");
1241     fprintf(stderr,"\t       -W# specifies the initial window width\n");
1242     fprintf(stderr,"\t       -O# specifies the color offset\n");
1243     fprintf(stderr,"\t       -c# specifies the desired color wheel\n");
1244     fprintf(stderr,"\t       -m# specifies the desired map (0-4)\n");
1245     fprintf(stderr,"\t       -f aabbb specifies a forcing function of 00111\n");
1246 #ifdef MAPS
1247     fprintf(stderr,"\t       -F 00111 specifies the function forcing function\n");
1248 #endif
1249     fprintf(stderr,"\t       -L indicates use log(x)+log(y) rather than log(xy)\n");
1250     fprintf(stderr,"\tDuring display :\n");
1251     fprintf(stderr,"\t     Use the mouse to zoom in on an area\n");
1252     fprintf(stderr,"\t     e or E recalculates color indices\n");
1253     fprintf(stderr,"\t     f or F saves exponents to a file\n");
1254     fprintf(stderr,"\t     KJmn increase/decrease minimum negative exponent\n");
1255     fprintf(stderr,"\t     r or R redraws\n");
1256     fprintf(stderr,"\t     s or S spins the colorwheel\n");
1257     fprintf(stderr,"\t     w or W changes the color wheel\n");
1258     fprintf(stderr,"\t     x or X clears the window\n");
1259     fprintf(stderr,"\t     q or Q exits\n");
1260     exit(1);
1261 }
1262
1263 static void
1264 Cycle_frames(void)
1265 {
1266   static int i;
1267   for (i=0;i<=maxframe;i++)
1268     redraw(exponents[i], expind[i], 1);
1269 }
1270
1271 static void
1272 Spin(Window w)
1273 {
1274   static int i, j;
1275   long tmpxcolor;
1276
1277   if (displayplanes > 1) {
1278     for (j=0;j<spinlength;j++) {
1279       tmpxcolor = Colors[mincolindex].pixel;
1280       for (i=mincolindex;i<numcolors-1;i++)
1281         Colors[i].pixel = Colors[i+1].pixel;
1282       Colors[numcolors-1].pixel = tmpxcolor;
1283       XStoreColors(dpy, cmap, Colors, numcolors);
1284     }
1285     for (j=0;j<spinlength;j++) {
1286       tmpxcolor = Colors[numcolors-1].pixel;
1287       for (i=numcolors-1;i>mincolindex;i--)
1288         Colors[i].pixel = Colors[i-1].pixel;
1289       Colors[mincolindex].pixel = tmpxcolor;
1290       XStoreColors(dpy, cmap, Colors, numcolors);
1291     }
1292   }
1293 }
1294
1295 static void
1296 Getkey(XKeyEvent *event)
1297 {
1298   unsigned char key;
1299   static int i;
1300   if (XLookupString(event, (char *)&key, sizeof(key), (KeySym *)0,
1301             (XComposeStatus *) 0) > 0)
1302     switch (key) {
1303   case '<': dwell /= 2; if (dwell < 1) dwell = 1; break;
1304   case '>': dwell *= 2; break;
1305   case '[': settle /= 2; if (settle < 1) settle = 1; break;
1306   case ']': settle *= 2; break;
1307   case 'd': go_down(); break;
1308   case 'D': FlushBuffer(); break;
1309   case 'e':
1310   case 'E': FlushBuffer();
1311       dorecalc = (!dorecalc);
1312       if (dorecalc)
1313       recalc();
1314       else {
1315       maxexp = minlyap; minexp = -1.0 * minlyap;
1316       }
1317       redraw(exponents[frame], expind[frame], 1);
1318       break;
1319   case 'f':
1320   case 'F': save_to_file(); break;
1321   case 'i': if (stripe_interval > 0) {
1322       stripe_interval--;
1323         if (displayplanes > 1) {
1324             init_color();
1325         }
1326       }
1327       break;
1328   case 'I': stripe_interval++;
1329       if (displayplanes > 1) {
1330         init_color();
1331       }
1332       break;
1333   case 'K': if (minlyap > 0.05)
1334       minlyap -= 0.05;
1335        break;
1336   case 'J': minlyap += 0.05;
1337        break;
1338   case 'm': mapindex++;
1339                   if (mapindex >= NUMMAPS)
1340                         mapindex=0;
1341                   map = Maps[mapindex];
1342                   deriv = Derivs[mapindex];
1343       if (!aflag)
1344                         min_a = amins[mapindex];
1345                   if (!wflag)
1346                         a_range = aranges[mapindex];
1347                   if (!bflag)
1348                         min_b = bmins[mapindex];
1349                   if (!hflag)
1350                         b_range = branges[mapindex];
1351                   if (!Force)
1352                         for (i=0;i<FUNCMAXINDEX;i++)
1353                              Forcing[i] = mapindex;
1354             max_a = min_a + a_range;
1355             max_b = min_b + b_range;
1356             a_minimums[0] = min_a; b_minimums[0] = min_b;
1357             a_maximums[0] = max_a; b_maximums[0] = max_b;
1358             a_inc = a_range / (double)width;
1359             b_inc = b_range / (double)height;
1360             point.x = -1;
1361             point.y = 0;
1362             a = rubber_data.p_min = min_a;
1363             b = rubber_data.q_min = min_b;
1364             rubber_data.p_max = max_a;
1365             rubber_data.q_max = max_b;
1366                   Clear();
1367                   break;
1368   case 'M': if (minlyap > 0.005)
1369       minlyap -= 0.005;
1370        break;
1371   case 'N': minlyap += 0.005;
1372        break;
1373   case 'p':
1374   case 'P': negative = (!negative);
1375       FlushBuffer(); redraw(exponents[frame], expind[frame], 1);
1376       break;
1377   case 'r': FlushBuffer(); redraw(exponents[frame], expind[frame], 1);
1378       break;
1379   case 'R': FlushBuffer(); Redraw(); break;
1380   case 's':
1381        spinlength=spinlength/2;
1382   case 'S': if (displayplanes > 1)
1383       Spin(canvas);
1384        spinlength=spinlength*2; break;
1385   case 'u': go_back(); break;
1386   case 'U': go_init(); break;
1387   case 'v':
1388   case 'V': print_values(); break;
1389   case 'W': if (numwheels < MAXWHEELS)
1390       numwheels++;
1391        else
1392       numwheels = 0;
1393        if (displayplanes > 1) {
1394         init_color();
1395        }
1396        break;
1397   case 'w': if (numwheels > 0)
1398       numwheels--;
1399        else
1400       numwheels = MAXWHEELS;
1401        if (displayplanes > 1) {
1402         init_color();
1403        }
1404        break;
1405   case 'x': Clear(); break;
1406   case 'X': Destroy_frame(); break;
1407   case 'z': Cycle_frames(); redraw(exponents[frame], expind[frame], 1);
1408       break;
1409   case 'Z': while (!XPending(dpy)) Cycle_frames();
1410       redraw(exponents[frame], expind[frame], 1); break;
1411   case 'q':
1412   case 'Q': exit(0); break;
1413   case '?':
1414   case 'h':
1415   case 'H': print_help(); break;
1416   default:  break;
1417   }
1418 }
1419
1420 /* Here's where we index into a color map. After the Lyapunov exponent is
1421  * calculated, it is used to determine what color to use for that point.
1422  * I suppose there are a lot of ways to do this. I used the following :
1423  * if it's non-negative then there's a reserved area at the lower range
1424  * of the color map that i index into. The ratio of some "minimum exponent
1425  * value" and the calculated value is used as a ratio of how high to index
1426  * into this reserved range. Usually these colors are dark red (see init_color).
1427  * If the exponent is negative, the same ratio (expo/minlyap) is used to index
1428  * into the remaining portion of the colormap (which is usually some light
1429  * shades of color or a rainbow wheel). The coloring scheme can actually make
1430  * a great deal of difference in the quality of the picture. Different colormaps
1431  * bring out different details of the dynamics while different indexing
1432  * algorithms also greatly effect what details are seen. Play around with this.
1433  */
1434 static int
1435 sendpoint(double expo)
1436 {
1437   static int index;
1438   static double tmpexpo;
1439
1440 #if 0
1441 /* The relationship minexp <= expo <= maxexp should always be true. This test
1442    enforces that. But maybe not enforcing it makes better pictures. */
1443   if (expo < minexp)
1444     expo = minexp;
1445   else if (expo > maxexp)
1446     expo = maxexp;
1447 #endif
1448
1449   point.x++;
1450   tmpexpo = (negative) ? expo : -1.0 * expo;
1451   if (tmpexpo > 0) {
1452     if (displayplanes >1) {
1453         index = (int)(tmpexpo*lowrange/maxexp);
1454         index = (index % lowrange) + startcolor;
1455     }
1456     else
1457         index = 0;
1458   }
1459   else {
1460     if (displayplanes >1) {
1461         index = (int)(tmpexpo*numfreecols/minexp);
1462         index = (index % numfreecols) + mincolindex;
1463     }
1464     else
1465         index = 1;
1466   }
1467     BufferPoint(dpy, canvas, index, point.x, point.y);
1468   if (save)
1469     exponents[frame][expind[frame]++] = expo;
1470   if (point.x >= width) {
1471     point.y++;
1472     point.x = 0;
1473     if (save) {
1474       b += b_inc;
1475       a = min_a;
1476     }
1477     if (point.y >= height)
1478       return FALSE;
1479     else
1480       return TRUE;
1481   }
1482   return TRUE;
1483 }
1484
1485 static void
1486 redisplay (Window w, XExposeEvent *event)
1487 {
1488   /*
1489   * Extract the exposed area from the event and copy
1490   * from the saved pixmap to the window.
1491   */
1492   XCopyArea(dpy, pixmap, canvas, Data_GC[0],
1493            event->x, event->y, event->width, event->height,
1494            event->x, event->y);
1495 }
1496
1497 static void
1498 resize(void)
1499 {
1500   Window r;
1501   int n, x, y;
1502   unsigned int bw, d, new_w, new_h;
1503
1504   XGetGeometry(dpy,canvas,&r,&x,&y,&new_w,&new_h,&bw,&d);
1505   if ((new_w == width) && (new_h == height))
1506     return;
1507   width = new_w; height = new_h;
1508   XClearWindow(dpy, canvas);
1509   if (pixmap)
1510     XFreePixmap(dpy, pixmap);
1511   pixmap = XCreatePixmap(dpy, DefaultRootWindow(dpy),
1512       width, height, DefaultDepth(dpy, screen));
1513   a_inc = a_range / (double)width;
1514   b_inc = b_range / (double)height;
1515   point.x = -1;
1516   point.y = 0;
1517   run = 1;
1518   a = rubber_data.p_min = min_a;
1519   b = rubber_data.q_min = min_b;
1520   rubber_data.p_max = max_a;
1521   rubber_data.q_max = max_b;
1522   freemem();
1523   setupmem();
1524         for (n=0;n<MAXFRAMES;n++)
1525     if ((n <= maxframe) && (n != frame))
1526         resized[n] = 1;
1527   InitBuffer();
1528   Clear();
1529   Redraw();
1530 }
1531
1532 static void
1533 redraw(double *exparray, int index, int cont)
1534 {
1535   static int i;
1536   static int x_sav, y_sav;
1537
1538   x_sav = point.x;
1539   y_sav = point.y;
1540
1541   point.x = -1;
1542   point.y = 0;
1543
1544   save=0;
1545   for (i=0;i<index;i++)
1546     sendpoint(exparray[i]);
1547   save=1;
1548
1549   if (cont) {
1550     point.x = x_sav;
1551     point.y = y_sav;
1552   }
1553   else {
1554     a = point.x * a_inc + min_a;
1555     b = point.y * b_inc + min_b;
1556   }
1557   FlushBuffer();
1558 }
1559
1560 static void
1561 Redraw(void)
1562 {
1563   FlushBuffer();
1564         point.x = -1;
1565         point.y = 0;
1566   run = 1;
1567         a = min_a;
1568         b = min_b;
1569   expind[frame] = 0;
1570   resized[frame] = 0;
1571 }
1572
1573 /* Store color pics in PPM format and monochrome in PGM */
1574 static void
1575 save_to_file(void)
1576 {
1577   FILE *outfile;
1578   unsigned char c;
1579   XImage *ximage;
1580   static int i,j;
1581   struct Colormap {
1582     unsigned char red;
1583     unsigned char green;
1584     unsigned char blue;
1585   };
1586   struct Colormap *colormap=NULL;
1587
1588   if (colormap)
1589     free(colormap);
1590   if ((colormap=
1591     (struct Colormap *)malloc(sizeof(struct Colormap)*maxcolor))
1592       == NULL) {
1593     fprintf(stderr,"Error malloc'ing colormap array\n");
1594     exit(-1);
1595   }
1596   outfile = fopen(outname,"w");
1597   if(!outfile) {
1598     perror(outname);
1599     exit(-1);
1600   }
1601
1602   ximage=XGetImage(dpy, pixmap, 0, 0, width, height, AllPlanes, XYPixmap);
1603
1604   if (displayplanes > 1) {
1605     for (i=0;i<maxcolor;i++) {
1606       colormap[i].red=(unsigned char)(Colors[i].red >> 8);
1607       colormap[i].green=(unsigned char)(Colors[i].green >> 8);
1608       colormap[i].blue =(unsigned char)(Colors[i].blue >> 8);
1609     }
1610     fprintf(outfile,"P%d %d %d\n",6,width,height);
1611   }
1612   else
1613     fprintf(outfile,"P%d %d %d\n",5,width,height);
1614   fprintf(outfile,"# settle=%d  dwell=%d start_x=%f\n",settle,dwell,
1615         start_x);
1616   fprintf(outfile,"# min_a=%f  a_rng=%f  max_a=%f\n",min_a,a_range,max_a);
1617   fprintf(outfile,"# min_b=%f  b_rng=%f  max_b=%f\n",min_b,b_range,max_b);
1618   if (Rflag)
1619     fprintf(outfile,"# pseudo-random forcing\n");
1620   else if (force) {
1621     fprintf(outfile,"# periodic forcing=");
1622     for (i=0;i<maxindex;i++) {
1623       fprintf(outfile,"%d",forcing[i]);
1624     }
1625     fprintf(outfile,"\n");
1626   }
1627   else
1628     fprintf(outfile,"# periodic forcing=01\n");
1629   if (Force) {
1630     fprintf(outfile,"# function forcing=");
1631     for (i=0;i<funcmaxindex;i++) {
1632       fprintf(outfile,"%d",Forcing[i]);
1633     }
1634     fprintf(outfile,"\n");
1635   }
1636   fprintf(outfile,"%d\n",numcolors-1);
1637
1638   for (j=0;j<height;j++)
1639       for (i=0;i<width;i++) {
1640     c = (unsigned char)XGetPixel(ximage,i,j);
1641     if (displayplanes > 1)
1642         fwrite((char *)&colormap[c],sizeof colormap[0],1,outfile);
1643     else
1644         fwrite((char *)&c,sizeof c,1,outfile);
1645       }
1646   fclose(outfile);
1647 }
1648
1649 static void
1650 recalc(void)
1651 {
1652   static int i, x, y;
1653
1654   minexp = maxexp = 0.0;
1655   x = y = 0;
1656   for (i=0;i<expind[frame];i++) {
1657     if (exponents[frame][i] < minexp)
1658       minexp = exponents[frame][i];
1659     if (exponents[frame][i] > maxexp)
1660       maxexp = exponents[frame][i];
1661   }
1662 }
1663
1664 static void
1665 Clear(void)
1666 {
1667       XClearWindow(dpy, canvas);
1668   XCopyArea(dpy, canvas, pixmap, Data_GC[0],
1669             0, 0, width, height, 0, 0);
1670   InitBuffer();
1671 }
1672
1673 static void
1674 show_defaults(void)
1675 {
1676
1677   printf("Width=%d  Height=%d  numcolors=%d  settle=%d  dwell=%d\n",
1678     width,height,numcolors,settle,dwell);
1679   printf("min_a=%f  a_range=%f  max_a=%f\n", min_a,a_range,max_a);
1680   printf("min_b=%f  b_range=%f  max_b=%f\n", min_b,b_range,max_b);
1681   printf("minlyap=%f  minexp=%f  maxexp=%f\n", minlyap,minexp,maxexp);
1682   exit(0);
1683 }
1684
1685 static void
1686 CreateXorGC(void)
1687 {
1688   XGCValues values;
1689
1690   values.foreground = foreground;
1691   values.line_style = LineSolid;
1692   values.function = GXxor;
1693   RubberGC = XCreateGC(dpy, DefaultRootWindow(dpy),
1694         GCForeground | GCBackground | GCFunction | GCLineStyle, &values);
1695 }
1696
1697 static void
1698 StartRubberBand(Window w, image_data_t *data, XEvent *event)
1699 {
1700   XPoint corners[5];
1701
1702   nostart = 0;
1703   data->rubber_band.last_x = data->rubber_band.start_x = event->xbutton.x;
1704   data->rubber_band.last_y = data->rubber_band.start_y = event->xbutton.y;
1705   SetupCorners(corners, data);
1706   XDrawLines(dpy, canvas, RubberGC,
1707       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1708 }
1709
1710 static void
1711 SetupCorners(XPoint *corners, image_data_t *data)
1712 {
1713   corners[0].x = data->rubber_band.start_x;
1714   corners[0].y = data->rubber_band.start_y;
1715   corners[1].x = data->rubber_band.start_x;
1716   corners[1].y = data->rubber_band.last_y;
1717   corners[2].x = data->rubber_band.last_x;
1718   corners[2].y = data->rubber_band.last_y;
1719   corners[3].x = data->rubber_band.last_x;
1720   corners[3].y = data->rubber_band.start_y;
1721   corners[4] = corners[0];
1722 }
1723
1724 static void
1725 TrackRubberBand(Window w, image_data_t *data, XEvent *event)
1726 {
1727   XPoint corners[5];
1728   int xdiff, ydiff;
1729
1730   if (nostart)
1731     return;
1732   SetupCorners(corners, data);
1733   XDrawLines(dpy, canvas, RubberGC,
1734       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1735   ydiff = event->xbutton.y - data->rubber_band.start_y;
1736   xdiff = event->xbutton.x - data->rubber_band.start_x;
1737   data->rubber_band.last_x = data->rubber_band.start_x + xdiff;
1738   data->rubber_band.last_y = data->rubber_band.start_y + ydiff;
1739   if (data->rubber_band.last_y < data->rubber_band.start_y ||
1740       data->rubber_band.last_x < data->rubber_band.start_x)
1741   {
1742     data->rubber_band.last_y = data->rubber_band.start_y;
1743     data->rubber_band.last_x = data->rubber_band.start_x;
1744   }
1745   SetupCorners(corners, data);
1746   XDrawLines(dpy, canvas, RubberGC,
1747       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1748 }
1749
1750 static void
1751 EndRubberBand(Window w, image_data_t *data, XEvent *event)
1752 {
1753   XPoint corners[5];
1754   XPoint top, bot;
1755   double delta, diff;
1756
1757   nostart = 1;
1758   SetupCorners(corners, data);
1759   XDrawLines(dpy, canvas, RubberGC,
1760       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1761   if (data->rubber_band.start_x >= data->rubber_band.last_x ||
1762       data->rubber_band.start_y >= data->rubber_band.last_y)
1763     return;
1764   top.x = data->rubber_band.start_x;
1765   bot.x = data->rubber_band.last_x;
1766   top.y = data->rubber_band.start_y;
1767   bot.y = data->rubber_band.last_y;
1768   diff = data->q_max - data->q_min;
1769   delta = (double)top.y / (double)height;
1770   data->q_min += diff * delta;
1771   delta = (double)(height - bot.y) / (double)height;
1772   data->q_max -= diff * delta;
1773   diff = data->p_max - data->p_min;
1774   delta = (double)top.x / (double)width;
1775   data->p_min += diff * delta;
1776   delta = (double)(width - bot.x) / (double)width;
1777   data->p_max -= diff * delta;
1778   fflush(stdout);
1779   set_new_params(w, data);
1780 }
1781
1782 static void
1783 set_new_params(Window w, image_data_t *data)
1784 {
1785   frame = (maxframe + 1) % MAXFRAMES;
1786   if (frame > maxframe)
1787     maxframe = frame;
1788   a_range = data->p_max - data->p_min;
1789   b_range = data->q_max - data->q_min;
1790         a_minimums[frame] = min_a = data->p_min;
1791         b_minimums[frame] = min_b = data->q_min;
1792         a_inc = a_range / (double)width;
1793         b_inc = b_range / (double)height;
1794         point.x = -1;
1795         point.y = 0;
1796   run = 1;
1797         a = min_a;
1798         b = min_b;
1799         a_maximums[frame] = max_a = data->p_max;
1800         b_maximums[frame] = max_b = data->q_max;
1801   expind[frame] = 0;;
1802   Clear();
1803 }
1804
1805 static void
1806 go_down(void)
1807 {
1808   frame++;
1809   if (frame > maxframe)
1810     frame = 0;
1811   jumpwin();
1812 }
1813
1814 static void
1815 go_back(void)
1816 {
1817   frame--;
1818   if (frame < 0)
1819     frame = maxframe;
1820   jumpwin();
1821 }
1822
1823 static void
1824 jumpwin(void)
1825 {
1826   rubber_data.p_min = min_a = a_minimums[frame];
1827   rubber_data.q_min = min_b = b_minimums[frame];
1828   rubber_data.p_max = max_a = a_maximums[frame];
1829   rubber_data.q_max = max_b = b_maximums[frame];
1830   a_range = max_a - min_a;
1831   b_range = max_b - min_b;
1832         a_inc = a_range / (double)width;
1833         b_inc = b_range / (double)height;
1834         point.x = -1;
1835         point.y = 0;
1836         a = min_a;
1837         b = min_b;
1838   Clear();
1839   if (resized[frame])
1840     Redraw();
1841   else
1842     redraw(exponents[frame], expind[frame], 0);
1843 }
1844
1845 static void
1846 go_init(void)
1847 {
1848   frame = 0;
1849   jumpwin();
1850 }
1851
1852 static void
1853 Destroy_frame(void)
1854 {
1855   static int i;
1856
1857   for (i=frame; i<maxframe; i++) {
1858     exponents[frame] = exponents[frame+1];
1859     expind[frame] = expind[frame+1];
1860     a_minimums[frame] = a_minimums[frame+1];
1861     b_minimums[frame] = b_minimums[frame+1];
1862     a_maximums[frame] = a_maximums[frame+1];
1863     b_maximums[frame] = b_maximums[frame+1];
1864   }
1865   maxframe--;
1866   go_back();
1867 }
1868
1869 static void
1870 InitBuffer(void)
1871 {
1872   int i;
1873
1874   for (i = 0 ; i < maxcolor; ++i)
1875     Points.npoints[i] = 0;
1876 }
1877
1878 static void
1879 BufferPoint(Display *display, Window window, int color, int x, int y)
1880 {
1881
1882 /* Guard against bogus color values. Shouldn't be necessary but paranoia
1883    is good. */
1884   if (color < 0)
1885     color = 0;
1886   else if (color >= maxcolor)
1887     color = maxcolor - 1;
1888
1889   if (Points.npoints[color] == MAXPOINTS)
1890   {
1891     XDrawPoints(display, window, Data_GC[color],
1892         Points.data[color], Points.npoints[color], CoordModeOrigin);
1893     XDrawPoints(display, pixmap, Data_GC[color],
1894         Points.data[color], Points.npoints[color], CoordModeOrigin);
1895     Points.npoints[color] = 0;
1896   }
1897   Points.data[color][Points.npoints[color]].x = x;
1898   Points.data[color][Points.npoints[color]].y = y;
1899   ++Points.npoints[color];
1900 }
1901
1902 static void
1903 FlushBuffer(void)
1904 {
1905   int color;
1906
1907   for (color = 0; color < maxcolor; ++color)
1908     if (Points.npoints[color])
1909     {
1910         XDrawPoints(dpy, canvas, Data_GC[color],
1911           Points.data[color], Points.npoints[color],
1912           CoordModeOrigin);
1913         XDrawPoints(dpy, pixmap, Data_GC[color],
1914           Points.data[color], Points.npoints[color],
1915           CoordModeOrigin);
1916         Points.npoints[color] = 0;
1917     }
1918 }
1919
1920 static void
1921 print_help(void)
1922 {
1923     printf("During run-time, interactive control can be exerted via : \n");
1924     printf("Mouse buttons allow rubber-banding of a zoom box\n");
1925     printf("< halves the 'dwell', > doubles the 'dwell'\n");
1926     printf("[ halves the 'settle', ] doubles the 'settle'\n");
1927     printf("D flushes the drawing buffer\n");
1928     printf("e or E recalculates color indices\n");
1929     printf("f or F saves exponents to a file\n");
1930     printf("h or H or ? displays this message\n");
1931     printf("i decrements, I increments the stripe interval\n");
1932     printf("KJMN increase/decrease minimum negative exponent\n");
1933     printf("m increments the map index, changing maps\n");
1934     printf("p or P reverses the colormap for negative/positive exponents\n");
1935     printf("r redraws without recalculating\n");
1936     printf("R redraws, recalculating with new dwell and settle values\n");
1937     printf("s or S spins the colorwheel\n");
1938     printf("u pops back up to the last zoom\n");
1939     printf("U pops back up to the first picture\n");
1940     printf("v or V displays the values of various settings\n");
1941     printf("w decrements, W increments the color wheel index\n");
1942     printf("x or X clears the window\n");
1943     printf("q or Q exits\n");
1944 }
1945
1946 static void
1947 print_values(void)
1948 {
1949     static int i;
1950
1951     printf("\nminlyap=%f minexp=%f maxexp=%f\n",minlyap,minexp,maxexp);
1952     printf("width=%d height=%d\n",width,height);
1953     printf("settle=%d  dwell=%d start_x=%f\n",settle,dwell, start_x);
1954     printf("min_a=%f  a_rng=%f  max_a=%f\n",min_a,a_range,max_a);
1955     printf("min_b=%f  b_rng=%f  max_b=%f\n",min_b,b_range,max_b);
1956     if (Rflag)
1957   printf("pseudo-random forcing\n");
1958     else if (force) {
1959   printf("periodic forcing=");
1960   for (i=0;i<maxindex;i++)
1961     printf("%d",forcing[i]);
1962   printf("\n");
1963     }
1964     else
1965   printf("periodic forcing=01\n");
1966     if (Force) {
1967   printf("function forcing=");
1968   for (i=0;i<funcmaxindex;i++) {
1969     printf("%d",Forcing[i]);
1970   }
1971   printf("\n");
1972     }
1973     printf("numcolors=%d\n",numcolors-1);
1974 }
1975
1976 static void
1977 freemem(void)
1978 {
1979   static int i;
1980
1981         for (i=0;i<MAXFRAMES;i++)
1982                 free(exponents[i]);
1983 }
1984
1985 static void
1986 setupmem(void)
1987 {
1988   static int i;
1989
1990         for (i=0;i<MAXFRAMES;i++) {
1991                 if((exponents[i]=
1992                     (double *)malloc(sizeof(double)*width*height))==NULL){
1993                     fprintf(stderr,"Error malloc'ing exponent array.\n");
1994                     exit(-1);
1995                 }
1996         }
1997 }
1998
1999 static void
2000 setforcing(void)
2001 {
2002   static int i;
2003   for (i=0;i<MAXINDEX;i++)
2004     forcing[i] = (random() > prob) ? 0 : 1;
2005 }