Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Drawing/Collections/ILTickCollection.cs @ 11826

Last change on this file since 11826 was 9102, checked in by gkronber, 12 years ago

#1967: ILNumerics source for experimentation

File size: 36.5 KB
Line 
1///
2///    This file is part of ILNumerics Community Edition.
3///
4///    ILNumerics Community Edition - high performance computing for applications.
5///    Copyright (C) 2006 - 2012 Haymo Kutschbach, http://ilnumerics.net
6///
7///    ILNumerics Community Edition is free software: you can redistribute it and/or modify
8///    it under the terms of the GNU General Public License version 3 as published by
9///    the Free Software Foundation.
10///
11///    ILNumerics Community Edition is distributed in the hope that it will be useful,
12///    but WITHOUT ANY WARRANTY; without even the implied warranty of
13///    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14///    GNU General Public License for more details.
15///
16///    You should have received a copy of the GNU General Public License
17///    along with ILNumerics Community Edition. See the file License.txt in the root
18///    of your distribution package. If not, see <http://www.gnu.org/licenses/>.
19///
20///    In addition this software uses the following components and/or licenses:
21///
22///    =================================================================================
23///    The Open Toolkit Library License
24///   
25///    Copyright (c) 2006 - 2009 the Open Toolkit library.
26///   
27///    Permission is hereby granted, free of charge, to any person obtaining a copy
28///    of this software and associated documentation files (the "Software"), to deal
29///    in the Software without restriction, including without limitation the rights to
30///    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
31///    the Software, and to permit persons to whom the Software is furnished to do
32///    so, subject to the following conditions:
33///
34///    The above copyright notice and this permission notice shall be included in all
35///    copies or substantial portions of the Software.
36///
37///    =================================================================================
38///   
39
40using System;
41using System.Collections.Generic;
42using System.Drawing;
43using ILNumerics.Drawing.Labeling;
44using System.Collections;
45
46namespace ILNumerics.Drawing.Collections {
47    /// <summary>
48    /// List of labeled ticks for an axis
49    /// </summary>
50    public class ILTickCollection : ILLabelingElement,
51                                    IDisposable,
52                                    IEnumerable<LabeledTick> {
53
54        #region events
55        /// <summary>
56        /// Fires, when the collection of ticks has changed
57        /// </summary>
58        public new event AxisChangedEventHandler Changed;
59        /// <summary>
60        /// fires, if a new labeled tick is about to be added to the collection
61        /// </summary>
62        public event LabeledTickAddingHandler LabeledTickAdding;
63        #endregion
64
65        #region event handler
66        /// <summary>
67        /// fires the change event
68        /// </summary>
69        protected void OnChange() {
70            if (Changed != null)
71                Changed(this,new ILAxisChangedEventArgs(m_axisName));
72        }
73        /// <summary>
74        /// fires LabeledTickAdding event
75        /// </summary>
76        /// <param name="value">existing value</param>
77        /// <param name="label">existing label</param>
78        /// <param name="index">index of new tick in collection</param>
79        /// <returns>true: a registrar requested to cancel the adding, false otherwise</returns>
80        protected bool OnLabeledTickAdding(ref float value, ref string label, int index) {
81            if (LabeledTickAdding != null) {
82                ILLabeledTickAddingArgs args = new ILLabeledTickAddingArgs(value,label,index);
83                LabeledTickAdding(this,args);
84                label = args.Expression;
85                value = args.Value;
86                return args.Cancel;
87            }
88            return false;
89        }
90        #endregion
91
92        #region attributes
93        private int m_ticksAllowOverlap = 10;
94        private List<LabeledTick> m_ticks;
95        private TickDisplay m_tickDisplay;
96        private AxisNames m_axisName;
97        private TickDirection m_tickDirection;
98        private byte m_precision;
99        private int m_padding;
100        private Color m_tickColorNear;
101        private Color m_tickColorFar;
102        private TickMode m_tickMode;
103        private float m_tickFraction;
104        //internal properties
105        internal Point m_lineStart;
106        internal Point m_lineEnd;
107        private TickLabelRenderingHint m_renderingHint;
108        private ILPanel m_panel;
109        #endregion
110
111        #region properties
112        /// <summary>
113        /// determine the max number of pixels allowing a tic labels to be rendered inside the padding area of the next label
114        /// </summary>
115        public int TicksAllowOverlap {
116            get { return m_ticksAllowOverlap; }
117            set { m_ticksAllowOverlap = value; }
118        }
119
120        /// <summary>
121        /// Get the prefered placement for tick labels or sets it
122        /// </summary>
123        /// <remarks>Tick labels will not stricly rely on this setting, but rather
124        /// try to find the optimal tick positions depending on the current
125        /// rendering situation, taking the hint into account.</remarks>
126        public TickLabelRenderingHint RenderingHint {
127            get {
128                return m_renderingHint;
129            }
130            set {
131                m_renderingHint = value;
132                OnChange();
133            }
134        }
135       
136        /// <summary>
137        /// Positioning mode for ticks ([Auto],Manual)
138        /// </summary>
139        public TickMode Mode {
140            get {
141                return m_tickMode;
142            }
143            set {
144                m_tickMode = value;
145                OnChange();
146            }
147        }
148
149        /// <summary>
150        /// get / set the color for near ticks (label side)
151        /// </summary>
152        public Color NearColor {
153            get {
154                return m_tickColorNear;
155            }
156            set {
157                m_tickColorNear = value;
158                OnChange();
159            }
160        }
161
162        /// <summary>
163        /// get / set the color for backside ticks
164        /// </summary>
165        public Color FarColor {
166            get {
167                return m_tickColorFar;
168            }
169            set {
170                m_tickColorFar = value;
171                OnChange();
172            }
173        }
174
175        /// <summary>
176        ///  Get/ set the default color for tick labels
177        /// </summary>
178        /// <remarks>The color may be overwritten for individual labels</remarks>
179        public Color LabelColor {
180            get {
181                return m_color;
182            }
183            set {
184                m_color = value;
185                OnChange();
186            }
187        }
188
189        /// <summary>
190        /// padding between ticks
191        /// </summary>
192        public int Padding {
193            get {
194                return m_padding;
195            }
196            set {
197                m_padding = value;
198                OnChange();
199            }
200        }
201
202        /// <summary>
203        /// number of digits to be displayed in axis ticks
204        /// </summary>
205        public byte Precision {
206            get {
207                return m_precision;
208            }
209            set {
210                if (value < 16 && value > 0)
211                    m_precision = value;
212                else
213                    throw new ILNumerics.Exceptions.ILArgumentException("precision must be in range 1..15!");
214                // caching: since tick labels will be redrawn every
215                // render frame, we do not invalidate the label's queues here
216                OnChange();
217            }
218        }
219
220        /// <summary>
221        /// Get/ set which sides ticks for axis will be displayed on
222        /// </summary>
223        public TickDisplay Display {
224            get {
225                return m_tickDisplay;
226            }
227            set {
228                m_tickDisplay = value;
229                OnChange();
230            }
231        }
232
233        /// <summary>
234        /// How ticks are displayed (inside/outside)
235        /// </summary>
236        public TickDirection Direction {
237            get {
238                return m_tickDirection;
239            }
240            set {
241                m_tickDirection = value;
242                OnChange();
243            }
244        }
245
246        /// <summary>
247        /// length for ticks, fraction of the overall axis length. Default: 0.02
248        /// </summary>
249        public float TickFraction {
250            get {
251                return m_tickFraction;
252            }
253            set {
254                m_tickFraction = value;
255                OnChange();
256            }
257        }
258       
259        /// <summary>
260        /// Number of ticks currently stored into the collection
261        /// </summary>
262        public int Count {
263            get {
264                return m_ticks.Count;
265            }
266        }
267
268        /// <summary>
269        /// The axis this tick collection is assigned to
270        /// </summary>
271        public ILAxis Axis {
272            get {
273                return m_panel.Axes[m_axisName]; }
274        }
275        #endregion
276
277        #region constructor
278        /// <summary>
279        /// creates new ILTickCollection
280        /// </summary>
281        /// <param name="axisName"></param>
282        public ILTickCollection (ILPanel panel, AxisNames axisName)
283            : base(panel,new Font(FontFamily.GenericMonospace, 10.0f),Color.Black) {
284            m_panel = panel;
285            m_ticks = new List<LabeledTick>();
286            m_axisName = axisName;
287            m_precision = 4;
288            m_padding = 5;
289            m_tickColorFar = Color.Black;
290            m_tickColorNear = Color.Black;
291            m_tickDisplay = TickDisplay.LabelSide;
292            m_tickMode = TickMode.Auto;
293            m_tickFraction = 0.015f;
294            m_renderingHint = TickLabelRenderingHint.Auto;
295        }
296        #endregion
297
298        #region public methods
299        /// <summary>
300        /// Clear the collection of labeled ticks
301        /// </summary>
302        public void Clear() {
303            m_ticks.Clear();
304            m_size = Size.Empty;
305        }
306
307        /// <summary>
308        /// replace current collection of labeled ticks with a new one
309        /// </summary>
310        /// <param name="ticks"></param>
311        /// <remarks>This will fire a Change event.</remarks>
312        [Obsolete]
313        public void Replace(List<float> ticks) {
314            Set(ticks);
315        }
316
317        /// <summary>
318        /// replace current collection of labeled ticks with a new one
319        /// </summary>
320        /// <param name="ticks">label position for every tick</param>
321        /// <param name="labels">label texts for every tick corresponding to <paramref name="ticks"/></param>
322        /// <remarks><para>
323        /// This will set the <paramref name="Mode"/> property to 'TickMode.Manual', hence preventing from
324        /// automatic label creation on mouse perspective changes.</para>
325        /// <para>Set creates a change event.</para>
326        /// </remarks>
327        public void Set(IEnumerable<float> ticks, IEnumerable labels) {
328            Clear();
329            IEnumerator<float> tickCurs = ticks.GetEnumerator();     
330            foreach (var lab in labels) {
331                if (tickCurs.MoveNext()) {
332                    if (lab != null)
333                        Add(tickCurs.Current, lab.ToString());
334                    else
335                        Add(tickCurs.Current);
336                } else {
337                    throw new Exceptions.ILArgumentException("The number of 'labels' must match the number of tick locations.");
338                }
339            }
340            this.Mode = TickMode.Manual;
341            OnChange();
342        }
343        /// <summary>
344        /// replace current collection of labeled ticks with a new one
345        /// </summary>
346        /// <param name="ticks">label position for every tick</param>
347        /// <remarks><para>
348        /// This will set the <paramref name="Mode"/> property to 'TickMode.Manual', hence preventing from
349        /// automatic label creation on mouse perspective changes.</para>
350        /// <para>The <para>Precision</para> member is used to create tick label texts for all tick positions.</para>
351        /// <para>Set creates a change event.</para>
352        /// </remarks>
353        public void Set(IEnumerable<float> ticks) {
354            Clear();
355            foreach (float tick in ticks) {
356                Add(tick);
357            }
358            OnChange();
359        }
360        /// <summary>
361        /// Add a labeled tick to the ticks collection.
362        /// </summary>
363        /// <param name="value">current position</param>
364        /// <param name="label">current value</param>
365        /// <remarks>This function will fire the LabeledTickAdding event. This
366        /// gives users the chance to modify the tick and/or the label before
367        /// it gets added. She can also cancel the adding for the tick at all. <br/>
368        /// No Change event for the axis will be fired from this method.</remarks>
369        public void Add(float value, string label) {
370            if (OnLabeledTickAdding(ref value, ref label, m_ticks.Count)) {
371                return;
372            }
373            ILRenderQueue queue = m_interpreter.Transform(label,
374                                  m_font,m_color,m_renderer);
375            m_ticks.Add(new LabeledTick(value,queue));
376            if (m_size.Height < queue.Size.Height)
377                m_size.Height = queue.Size.Height;
378            if (m_size.Width < queue.Size.Width)
379                m_size.Width = queue.Size.Width;
380            //m_tickMode = TickMode.Manual;
381        }
382        /// <summary>
383        /// Add a labeled tick to the ticks collection
384        /// </summary>
385        /// <param name="value">position for tick</param>
386        /// <remarks>No Change event will be fired</remarks>
387        public void Add(float value) {
388            this.Add(value,value.ToString("g"+m_precision));
389        }
390        /// <summary>
391        /// Get maximum size of
392        /// all tick labels in pixels on screen
393        /// </summary>
394        /// <remarks>This property does not take the orientation into account. The size
395        /// of the content will be returned as if the orientation was straight horizontally.</remarks>
396        public override Size Size {
397            get {
398               // if (m_tickMode == TickMode.Auto && m_ticks.Count == 0) {
399               //     // first time: no labels have been added? -> assume maximum
400               //     // size determined by precision
401               //     Graphics g = Graphics.FromImage(new Bitmap(1,1));
402               //     string measString = String.Format(".-e08" + new String('0',m_precision));
403               //     m_size = g.MeasureString(measString,m_font).ToSize();
404               //}
405               return m_size;
406            }
407        }
408        ///// <summary>
409        ///// (Re-)measures the maximum size for all labels contained in the collection
410        ///// </summary>
411        ///// <param name="gr">graphics object, _may_ be used to measure texts (on some platforms)</param>
412        ///// <returns>maximum size</returns>
413        ///// <remarks>This function recomputes the true size for all labels and updates the internal cache. The cached value can
414        ///// than queried by the property 'ScreenSize'.
415        ///// <para>Note: if no tick labels have been stored into the collection yet, the
416        ///// maximum size possible for a label is returned. Therefore, the Precision member is
417        ///// taken into account.</para></remarks>
418        //public Size MeasureMaxScreenSize(Graphics gr) {
419        //    if (m_ticks.Count == 0) {
420        //        SizeF sf = gr.MeasureString (
421        //            "-e.08" + new String('0', m_precision),m_font);
422        //        m_screenSize = new Size((int)sf.Width,(int)sf.Height);
423        //    } else {
424        //        m_screenSize = new Size();
425        //        Size tmp;
426        //        foreach (LabeledTick tick in this) {
427        //            tmp = tick.Queue.Size;
428        //            if (tmp.Height > m_screenSize.Height)
429        //                m_screenSize.Height = tmp.Height;
430        //            if (tmp.Width > m_screenSize.Width)
431        //                m_screenSize.Width = tmp.Width;
432        //        }
433        //    }
434        //    return m_screenSize;
435        //}
436        /// <summary>
437        /// fill (replace) labels with nice labels for range 
438        /// </summary>
439        /// <param name="min">lower limit</param>
440        /// <param name="max">upper limit</param>
441        /// <param name="tickCount">maximum number of ticks</param>
442        public void CreateAuto(float min, float max, int tickCount) {
443            float dist = max - min;
444            tickCount = 50;
445            string format = String.Format("g{0}",m_precision);
446            // find the range for values we are dealing with.
447            // how many ticks will (really) fit on the label line?
448            if (tickCount > 1) {
449                Replace(NiceLabels(min,max,tickCount,m_renderingHint));
450                if (Count > 0)
451                    return;
452                // else: no ticks could be found at all -> fallback: show only center
453                tickCount = 1;
454            }
455            Clear();
456            float relevExp = (float)Math.Round(Math.Log10((max - min)));
457            if (!float.IsNaN(relevExp) && !float.IsInfinity(relevExp)) {
458                float multRound;
459                if (relevExp < 1) {
460                    multRound = (float) (1 / Math.Pow(10,relevExp-1));
461                } else {
462                    multRound = (float) Math.Pow(10,relevExp-1);
463                }
464                if (tickCount <= 1) {
465                    // If tickCount is 1, only the middle of Axis will be drawn.
466                    float ls = (float)(Math.Ceiling((max + min) / 2 / multRound) * multRound);
467                    if (ls != 0)
468                        Add(ls,ls.ToString(format));
469                    else
470                        Add(min,min.ToString(format));
471                } else if (tickCount == 3) {
472                    // draw max, min and the approx. center of range
473                    Add(min,min.ToString(format));
474                    Add(max,max.ToString(format));
475                    float ls = (float)(Math.Round((max + min) / 2 / multRound) * multRound); 
476                    Add(ls,ls.ToString(format));
477                } else { //if (tickCount == 2) {
478                    // If tickCount is less than 3 - only the max and the min will be drawn.
479                    Add(min,min.ToString(format));
480                    Add(max,max.ToString(format));
481                }
482            } else {
483                Add(max,max.ToString(format));
484            }
485        }
486
487        /// <summary>
488        /// Determine nice looking label positions for range specified
489        /// </summary>
490        /// <param name="min">lower limit</param>
491        /// <param name="max">upper limit</param>
492        /// <param name="numMaxLabels">maximum number of labels </param>
493        /// <param name="format">format string used to convert numbers to strings</param>
494        /// <param name="hint">rendering hint, specifies preferred method</param>
495        /// <returns>list of tick labels</returns>
496        public static List<float> NiceLabels(float min, float max, int numMaxLabels, TickLabelRenderingHint hint) {
497            List<float> ret;
498            switch (hint) {
499                case TickLabelRenderingHint.Filled:
500                    ret = NiceLabelsFill(min,max,numMaxLabels);
501                    break;
502                case TickLabelRenderingHint.Multiple1:
503                    ret = NiceLabelsEven(min,max,numMaxLabels,1.0f);
504                    break;
505                case TickLabelRenderingHint.Multiple2:
506                    ret = NiceLabelsEven(min,max,numMaxLabels,2.0f);
507                    break;
508                case TickLabelRenderingHint.Multiple5:
509                    ret = NiceLabelsEven(min,max,numMaxLabels,5.0f);
510                    break;
511                default:
512                    //ret = NiceLabelsAuto(min,max,numMaxLabels,format);
513                    ret = loose_label(min,max,numMaxLabels);
514                    break;
515            }
516            return ret;
517        }
518
519        public void Draw(ILRenderProperties p, float min, float max) {
520            m_renderer.Begin(p);
521            float clipRange = max - min;
522           
523            ILPoint3Df mult = new ILPoint3Df(
524                        ((float)(m_lineEnd.X - m_lineStart.X) / clipRange),
525                        ((float)(m_lineEnd.Y - m_lineStart.Y) / clipRange),
526                        0);
527            float tmp;
528            Point point = new Point(0,0);
529            Point oldMidPoint = new Point(int.MinValue,int.MinValue);
530            Point newMidPoint = new Point(int.MinValue,int.MinValue);
531            Point oldHSize = new Point(), newHSize = new Point();
532            foreach (LabeledTick lt in m_ticks) {
533                if (lt.Queue.Count > 0
534                    && lt.Position >= min
535                    && lt.Position <= max) {
536                    tmp = lt.Position-min;
537                    point.X = (int)(m_lineStart.X + mult.X * tmp);
538                    point.Y = (int)(m_lineStart.Y + mult.Y * tmp);
539                    offsetAlignment(lt.Queue.Size, ref point);
540                    newHSize.X = (int)(lt.Queue.Size.Width / 2.0f);
541                    newHSize.Y = (int)(lt.Queue.Size.Height / 2.0f);
542                    newMidPoint.X = point.X + newHSize.X;
543                    newMidPoint.Y = point.Y + newHSize.Y;
544                    // check distance to last drawn label for tickmode auto (padding)
545                    if (m_tickMode == TickMode.Auto) {
546                        if (oldMidPoint.X != int.MinValue
547                            && oldMidPoint.Y != int.MinValue) {
548
549                            float distX = Math.Abs(newMidPoint.X - oldMidPoint.X);
550                            float distY = Math.Abs(newMidPoint.Y - oldMidPoint.Y);
551                            if (distX < (m_padding + oldHSize.X + newHSize.X) - m_ticksAllowOverlap &&
552                                distY < (m_padding + oldHSize.Y + newHSize.Y) - m_ticksAllowOverlap) {
553                                //m_ticks.Remove(lt);
554                                continue;
555                            }
556                        }
557                        // bookmark outer rendering limits
558                        if (newMidPoint.X - newHSize.X < p.MinX)
559                            p.MinX = newMidPoint.X - newHSize.X;
560                        if (newMidPoint.Y - newHSize.Y < p.MinY)
561                            p.MinY = newMidPoint.Y - newHSize.Y;
562                        if (newMidPoint.X + newHSize.X > p.MaxX)
563                            p.MaxX = newMidPoint.X + newHSize.X;
564                        if (newMidPoint.Y + newHSize.Y > p.MaxY)
565                            p.MaxY = newMidPoint.Y + newHSize.Y;
566                    }
567                    m_renderer.Draw(lt.Queue, point, m_orientation, m_color);
568                    oldMidPoint = newMidPoint;
569                    oldHSize = newHSize;
570                }
571            }
572            m_renderer.End(p);
573        }
574        #endregion
575
576        #region IDisposable Member
577        public new void Dispose() {
578            if (m_renderer != null) {
579                // ???
580            }
581        }
582        #endregion
583
584        #region private helper
585
586        /// <summary>
587        /// Create nice labels, prefere even numbers over best optimal tick count
588        /// </summary>
589        /// <param name="min">min</param>
590        /// <param name="max">max</param>
591        /// <param name="numMaxLabels">max labels count</param>
592        /// <param name="format">format string used to convert numbers to strings</param>
593        /// <returns>nice label list</returns>
594        private static List<float> NiceLabelsAuto(float min, float max, int numMaxLabels, string format) {
595            float[] divisors = new float[3] {5.0f, 2.0f, 1.0f};
596            List<float>[] ticks = new List<float>[divisors.Length];
597            int count = 0, bestMatch = int.MaxValue, tmp = 0, bestMatchIdx = -1;
598            foreach (float div in divisors) {
599                ticks[count] = NiceLabelsEven(min,max,numMaxLabels,div); 
600                if (ticks[count].Count == numMaxLabels) {
601                    return ticks[count];
602                }
603                tmp = (int)Math.Abs(Math.Min(numMaxLabels,10) - ticks[count].Count);
604                if (tmp < bestMatch) {
605                    bestMatch = tmp;
606                    bestMatchIdx = count;
607                }
608                count ++;
609            }
610            // its possible for limits to exceed the resolution for float
611            // no ticks are returned in this case
612            return ticks[bestMatchIdx];
613        }
614        /// <summary>
615        /// find tick labels by distinct divisors (10,5,2). Chooses the divisor which best produces the best number according to numberTicks
616        /// </summary>
617        /// <param name="min">minimum</param>
618        /// <param name="max">maximum</param>
619        /// <param name="numberTicks">maximum number of ticks</param>
620        /// <param name="format">format string for string conversion</param>
621        /// <returns>list of tick labels</returns>
622        private static List<float> NiceLabelsFill(float min, float max, int numberTicks) {
623            // spacing may happen by divisors of 5,2,1. We test every case and choose the
624            // one producing the best match on the number of ticks requested than.
625            float[] divisors = new float[3] {5.0f, 2.0f, 1.0f};
626            List<float>[] ticks = new List<float>[divisors.Length];
627            int count = 0, bestMatch = int.MaxValue, tmp = 0, bestMatchIdx = -1;
628            foreach (float div in divisors) {
629                ticks[count] = NiceLabelsEven(min,max,numberTicks,div); 
630                tmp = (int)Math.Abs(Math.Min(numberTicks,10) - ticks[count].Count);
631                if (ticks[count].Count == numberTicks) {
632                    return ticks[count];
633                } else if (tmp <= bestMatch) {
634                    bestMatch = tmp;
635                    bestMatchIdx = count;
636                }
637                count ++;
638            }
639            System.Diagnostics.Debug.Assert(bestMatchIdx >= 0,"No best divisor has been found. Tick creation failed.");
640            if (bestMatchIdx >= 0)
641                return ticks[bestMatchIdx];
642            else
643                return ticks[0];  // rescue plan
644        }
645        private static List<float> NiceLabelsEven(float min, float max, int numberTicks, float divisor) {
646            //minimal distance required for ticks
647            float minDist = (max - min) / (numberTicks + 1);
648            // determine prominent range for optimal spacing
649            if (Math.Abs(minDist) < 1e-10) return new List<float>();
650            float relevExp = (float)Math.Log10((max - min));
651            if (float.IsNaN(relevExp)) {
652                return new List<float>();   
653            }
654            float multRound;
655            if (relevExp >= 1) {
656                return NiceLabelsEvenGE10(min,max,numberTicks,divisor);
657            }
658            List<float> ticks = new List<float>();
659            relevExp = (float)Math.Round(relevExp);
660            multRound = (float) (1 / Math.Pow(10,relevExp-1));
661            //float step = divisor / multRound, cur = min, origStep = step;
662            float step = multRound/ divisor, cur = min, origStep = step;
663            // TODO: check for step beeing too small for resonable min..max distance!
664            // OR: prevent for infinite loop!
665            while (step < minDist) {
666                step += origStep;
667            }
668            // find the first auto tick value, matching the divisor
669            cur = (float)(Math.Round((min + minDist) * multRound / divisor) / multRound * divisor);
670            ticks.Add(cur);
671            cur += step;
672            // add all ticks in _between_, keep margin to axis limits!
673            while (cur < max) {
674                cur = (float)(Math.Round(cur * multRound) / multRound);
675                ticks.Add(cur);
676                cur += step;
677                if (ticks.Count > numberTicks) {
678                    // emergency break - float cannot handle this distance!
679                    ticks.Clear();
680                    break;
681                }
682            }
683            return ticks;
684        }
685        private static List<float> NiceLabelsEvenGE10(float min, float max, int numberTicks, float divisor) {
686            //minimal distance required for ticks
687            float minDist = (max - min) / (numberTicks + 1);
688            // determine prominent range for optimal spacing
689            List<float> ticks = new List<float>();
690            // has been checked, if comming from NiceLabelsEven:
691            //if (Math.Abs(minDist) < 1e-10) return ticks;
692            float relevExp = (float)Math.Log10((max - min));
693            if (float.IsNaN(relevExp)) {
694                return ticks;   
695            }
696            float multRound;
697            relevExp = (float) (Math.Sign(relevExp) * Math.Floor(Math.Abs(relevExp)));
698            multRound = (float) Math.Pow(10,relevExp-1);
699            //float step = divisor / multRound, cur = min, origStep = step;
700            float step = multRound/ divisor, cur = min, origStep = step;
701            // TODO: check for step beeing too small for resonable min..max distance!
702            // OR: prevent for infinite loop!
703            while (step < minDist) {
704                // increase the multRRound by factor 10
705                relevExp ++;
706                multRound = (float) (Math.Pow(10,relevExp-1));
707                step = multRound/ divisor;
708            }
709            // find the first auto tick value, matching the divisor
710            cur = (float)niceNumber(min,false);
711            ticks.Add(cur);
712            // add all ticks in _between_, keep margin to axis limits!
713            while (cur < max) {
714                cur = (float)niceNumber(cur + step,false);
715                ticks.Add(cur);
716                if (ticks.Count > numberTicks) {
717                    // emergency break - float cannot handle this distance!
718                    ticks.Clear();
719                    break;
720                }
721            }
722            return ticks;
723        }
724
725        /// <summary>
726        /// create "nice" number in fractions of 2 or 5
727        /// </summary>
728        /// <param name="value">value</param>
729        /// <remarks>This code was adopted from Paul Heckbert
730        /// from "Graphics Gems", Academic Press, 1990. </remarks>
731        private static double niceNumber(double val, bool round) {
732            int expv;
733            double f;                                /* fractional part of x */
734            double nf;                               /* nice, rounded fraction */
735            double aval = Math.Abs(val);
736            double sign = Math.Sign(val);
737
738            expv = (int)Math.Floor(Math.Log10(aval));
739            f = aval/Math.Pow(10, expv);                /* between 1 and 10 */
740            if (round) {
741                if (f<1.5) nf = 1;
742                else if (f<3) nf = 2;
743                else if (f<7) nf = 5;
744                else nf = 10;
745            } else {
746                if (f<=1) nf = 1;
747                else if (f<=2) nf = 2;
748                else if (f<=5) nf = 5;
749                else nf = 10;
750            }
751            return (nf * Math.Pow(10, expv) * sign);
752        }
753        private static List<float> loose_label(float min,float max, int numberTicks) {
754            double d;                                /* tick mark spacing */
755            double graphmin;                /* graph range min and max */
756            double range, x;
757
758            /* we expect min!=max */
759            range = niceNumber(max-min, false);
760            d = niceNumber(range/(Math.Min(numberTicks,10)-1), true);
761            double exp = Math.Pow(10,Math.Floor(Math.Log10(max - min)));
762            graphmin = Math.Floor(min / exp) * exp; 
763
764                // Math.Min(niceNumber(min - d,true),niceNumber(min - d,false));
765            //graphmax = Math.Min(niceNumber(max - d, true), niceNumber(max + d, false));
766            List<float> ticks = new List<float>(); 
767            //ticks.Add(nfrac);
768            for (x = graphmin; x <= max; x = (float)(Math.Round((x + d) / d) * d)) {
769                //x = (float)(Math.Round(x/d)*d);
770                ticks.Add((float)x);
771                if (ticks.Count > 20) break; //emergency exit if range is in floating point range
772            }
773            return ticks;
774        }
775
776        #region Oli's labels implementaion (incomplete)
777        private static List<float> niceLabels (float start, float end, int maxNumbers,string format) {
778            float[] labelPositions = berechneLabel(start,end,maxNumbers);
779            List<float> ret = new List<float>();
780            foreach (float pos in labelPositions) {
781                ret.Add(pos);     
782            }
783            return ret;
784        }
785        private static float[] berechneLabel(float start, float end, int maxNumbers)
786        {
787            if (end <= start)
788                return null;
789            float strecke = Math.Abs(end - start);
790            maxNumbers++;//ï¿œberprï¿œfen!
791            int n = 0;
792            while (strecke < maxNumbers)
793            {
794                strecke *= 10;
795                n++;               
796            }
797            while (strecke > 100)
798            {
799                strecke /= 10;
800                n--;
801            }
802            start *= (float)Math.Pow(10, n);
803            int streckeIntValue = getStreckeAsNiceInt(strecke, maxNumbers);
804            /*
805            if (isPrimzahl(streckeIntValue) && streckeIntValue != maxNumbers)
806            {         
807                streckeIntValue++; //Kann zu Problemen fï¿œhren! -- ist aber auch Mist.
808            }
809            */
810
811            float step = 0;
812            int stepCount;
813            for (stepCount = maxNumbers; stepCount > 0; stepCount--)
814            {
815                step = streckeIntValue / stepCount;
816                int rest = streckeIntValue % stepCount;
817                if(rest < step && (step == 1 || step == 2 || step == 5 || step == 10 || step == 25 || step == 50 ))
818                        break;
819            }         
820            int startInt = (int)Math.Round(start, 0);
821            startInt = startInt - (startInt % (int)step);
822            if (n != 0)
823            {
824                step /= (float)(Math.Pow(10, n));
825                start = (float)startInt / (float)Math.Pow(10, n);
826            }
827            else
828                start = startInt;
829            if (!(start + stepCount * step < end))
830                stepCount--;
831            float[] ret = new float[stepCount];
832            for (int i = 1; i <= stepCount; i++)
833            {
834                ret[i - 1] = start + i * step;
835            }
836            return ret;
837        }
838        private static int getStreckeAsNiceInt(float strecke, int maxNumbers)
839        {
840            int streckeIntValue = (int)Math.Round(strecke, 0);
841            if (streckeIntValue <= 10)
842                return streckeIntValue;
843            if (streckeIntValue / 2 <= maxNumbers)
844                return streckeIntValue;
845
846            streckeIntValue = streckeIntValue - streckeIntValue % 5;
847            return streckeIntValue;
848        }
849        #endregion
850
851        #endregion
852
853        #region IEnumerable<LabeledTick> Member
854        /// <summary>
855        /// Get Enumerator, enumerating over all labeled ticks
856        /// </summary>
857        /// <returns>Enumerator</returns>
858        public IEnumerator<LabeledTick> GetEnumerator() {
859            return m_ticks.GetEnumerator();
860        }
861
862        #endregion
863
864        #region IEnumerable Member
865
866        /// <summary>
867        /// Get enumerator enumerating over labeled ticks
868        /// </summary>
869        /// <returns>enumerator</returns>
870        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
871            foreach (LabeledTick lt in m_ticks)
872                yield return lt;
873        }
874
875        #endregion
876
877    }
878}
Note: See TracBrowser for help on using the repository browser.