Questions about TFuncSeries lazarus / 55-TAChart ---------------------------------------------------------------------- hedgehog · 2026-03-09 07:19 Hi! I want to improve the accuracy of the results of plotting a function containing sharp peaks. For example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Chart1FuncSeries1Calculate(const AX: Double; out AY: Double);begin  AY:= 1/(abs(AX)+0.001);end; Obviously, the peak height at 0 should be 1000. However, in the attached screenshot, you can see that the peak height is less than 500 (with step=1). To do this, I need to change the code of the procedure TDrawFuncHelper.ForEachPoint Question: What's the best way to do this without modifying the TAChart package? Create your own series? (TMyFuncSeries) ---------------------------------------------------------------------- Thaddy · 2026-03-09 11:38 It is not that the peak isn't ~1000, it is because the scaling is such that it won't draw it because not enough samples are in the display range on X axis. You have to adapt the drawing such, that given the scaling and the screen resolution, a peak is drawn at ~1000 regardless: For the purpose of display, e.g anything above ~500 - ~800 (dpe3nds on steepness) should be scaled to a higher value or simply to the peak straight away. That way a peak value is always displayed. You can also use an envelope follower to smooth out the display range vs the real sample range. (Very easy to implement: a running queue (over X-axis) with a running average of samplerate/displayX elements + a bias > 1. ---------------------------------------------------------------------- wp · 2026-03-09 11:41 In this special case, you could check whether AX is close enough to zero. "Close enough" means: The value 0 is in the interval which is spanned on the x axis by one TFuncSeries.Step. You must calculate the size of Step on the x axis and then check the agreement by means of the functions IsZero or SameValue from the Math unit where this step size can be used as tolerance variable. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i // Calculate the size of Step in Graph units// Assuming here that graph units are the same as axis units, i.e. there is// no transformation involved.function TForm1.StepToGraph(X: Double; AStep: Integer): Double;var  imgX: Integer;  nextX: Double;begin  imgX := Chart1.XGraphToImage(X);  nextX := Chart1.XImageToGraph(imgX + AStep);    // the value after a "step"  Result := nextX - X;end; // Save the result of StepToGraph in some variable, e. g., FGraphStepprocedure TForm1.Chart1FuncSeries1Calculate(const AX: Double; out AY: Double);begin  if IsNaN(FGraphStep) then    FGraphStep := StepToGraph(0.0, Chart1FuncSeries1.Step);  if IsZero(AX, FGraphStep) then    AY := 1/0.001  else    AY:= 1/(abs(AX)+0.001);end; // Enforce recalculation of FGraphStep when the chart is resized.procedure TForm1.Chart1Resize(Sender: TObject);begin  FGraphStep := Nan;end; // Enforce recalculation of FGraphStep when the chart is zoomed.procedure TForm1.Chart1ExtentChanging(ASender: TChart);begin  FGraphStep := NaN;end; procedure TForm1.FormCreate(Sender: TObject);begin  FGraphStep := NaN;end;        [/quote]This code calculates the size of one "step" in the x axis "graph" units and stores the result in variable FGraphStep. It triggers recalculation of FGraphStep when the scaling of the plot changes, i.e. upon resizing and zooming. ---------------------------------------------------------------------- Thaddy · 2026-03-09 11:48 Ignore my answer: as per wp's demo there is already code to do similar. ---------------------------------------------------------------------- hedgehog · 2026-03-09 12:42 Hi. WP: Your answer is good, but it only works in this specific case! For any other function, we won't get the correct graph. Actually, I was trying to implement a polyline simplification algorithm for TChart/TFuncSeries. But after two hours of studying TChart's internal mechanisms, I realized it was quite complicated. ---------------------------------------------------------------------- wp · 2026-03-09 13:02 Quote from: hedgehog on March 09, 2026, 01:42:41 pmI realized it was quite complicated. Yes, it is... Quote from: hedgehog on March 09, 2026, 01:42:41 pmYour answer is good, but it only works in this specific case! For any other function, we won't get the correct graph. I'd say there's a infinite number of math functions, it is impossible to take care of all difficulties in a general solution. Can you explain what is common to the functions that you are trying to plot? Quote from: hedgehog on March 09, 2026, 01:42:41 pma polyline simplification algorithm You mean you want to create an array of points to be drawn by Canvas.PolyLine? This would have the advantage that, after creation of the array, you can insert the missing data points at the exact location of the "pseudo singularities". The disadvantage is that you must recalculate the array explicitely whenever the chart is zoomed or enlarged. You could even use a plain old TLineSeries for this... ---------------------------------------------------------------------- hedgehog · 2026-03-09 14:50 QuoteI'd say there's a infinite number of math functions, it is impossible to take care of all difficulties in a general solution. Can you explain what is common to the functions that you are trying to plot? What all these functions have in common is that they may have sharp peaks. Or they may not. QuoteYou mean you want to create an array of points to be drawn by Canvas.PolyLine? Yes. In the attached project, I attempted to create a universal procedure for plotting a function graph. This should always work (at least, I think so). ---------------------------------------------------------------------- wp · 2026-03-09 18:11 Interesting. I must confess that I do not understand this algorithm, without having looked into it too deeply... Can you give a verbal description? Certainly, a patch for integration into TFuncSeries would be welcome. But maybe this method should be available as a separate option because after adding a counter into your calc function I see that there are almost 63,000 function calls to draw the curve in your demo - which may be critical when calculation of the curve to be plotted is complicated. Two mutually exclusive features: current TFuncSeries: many data points, a "few" function calls, vs. your method: very few data points, but very many function calls. A requirement for adding to TFuncSeries would be also that it must be compatible with the DomainExclusion feature of TFuncSeries, i.e. it must respect the regions in which the function is not defined (e.g. sqrt(x) with domain exclusion for x < 0). ---------------------------------------------------------------------- hedgehog · 2026-03-09 19:29 Oh, yes, my apologies. The "swing door trend" algorithm is used here. It's a very simple and undemanding algorithm for simplifying polylines. Surprisingly, despite its widespread use, it doesn't have a Wikipedia entry. Here is a very simple description of the algorithm: https://softwaredocs.weatherford.com/cygnet/94/Content/Topics/History/ CygNet%20Swinging%20Door%20Compression.htm Quote But maybe this method should be available as a separate option because after adding a counter into your calc function I see that there are almost 63,000 function calls to draw the curve in your demo - which may be critical when calculation of the curve to be plotted is complicated. The algorithm is very simple. Each step performs several multiplications of real numbers and several comparisons. For any modern processor this is not a problem. QuoteA requirement for adding to TFuncSeries would be also that it must be compatible with the DomainExclusion feature of TFuncSeries, i.e. it must respect the regions in which the function is not defined (e.g. sqrt(x) with domain exclusion for x < 0).Oh, well, this one is simple. You need to plot the function graph in chunks, not the entire thing. ---------------------------------------------------------------------- wp · 2026-03-09 21:52 Quote from: hedgehog on March 09, 2026, 08:29:52 pmThe "swing door trend" algorithm is used here. It's a very simple and undemanding algorithm for simplifying polylines. Surprisingly, despite its widespread use, it doesn't have a Wikipedia entry. Here is a very simple description of the algorithm: https://softwaredocs.weatherford.com/cygnet/94/Content/Topics/History/ CygNet%20Swinging%20Door%20Compression.htm I'll take a closer look. QuoteQuote But maybe this method should be available as a separate option because after adding a counter into your calc function I see that there are almost 63,000 function calls to draw the curve in your demo - which may be critical when calculation of the curve to be plotted is complicated. The algorithm is very simple. Each step performs several multiplications of real numbers and several comparisons. No, I'm not talking about the algorithm itself, but about the calls to MyFunc. In your case, it is simple, but I could imagine that such a function can be quite complex. To count the function calls you can introduce some counting variable which you increment in MyFunc, reset at the top of Paintbox OnPaint handler and read at the end of it: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  NumCalls: Integer; procedure TForm1.PaintBox1Paint(Sender: TObject);begin  NumCalls := 0;  // ... your code here ...  Caption := IntToStr(NumCalls);end; function TForm1.MyFunc(x: double): double;begin  Result:= -1/(abs(x)+0.001);  inc(NumCalls);end; ---------------------------------------------------------------------- hedgehog · 2026-03-10 07:54 QuoteNo, I'm not talking about the algorithm itself, but about the calls to MyFunc. In your case, it is simple, but I could imagine that such a function can be quite complex. Just need to lower the sampling frequency. Instead: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i dx:= kx/100; //100 samples/pixel need: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i dx:= kx/15; //15 samples/pixel ---------------------------------------------------------------------- wp · 2026-03-10 10:28 Are you sure that your left-right vector math is correct? Assume vector A pointing to the right, A = (1, 0), and B pointing upward B = (0, 1). Code: [Select]   ^ B    |    |      - - -  > A Looking along the direction of A the left vector is B, and conversely, the same result is obtained when looking along B where A is on the right side, i.d. the "left" vector must be B. Doing your calculation in GetLeftVector, however, returns A as the left vector: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; {$modeswitch advancedrecords} type  TVector = record    x, y: double;    function IsLeft(V: TVector): boolean;  end; function TVector.IsLeft(V: TVector): boolean;begin  Result:= (x*V.y) > (V.x*y);end; function Vector(x, y: double): TVector; inline;begin  Result.x:= x;  Result.y:= y;end; function GetLeftVector(A, B: TVector): TVector; inline;begin  if A.IsLeft(B) then Result:= A else Result:= B;end; procedure WriteVector(AName: String; v: TVector);begin  WriteLn(AName, ' = (', v.x:0:3, ',', v.y:0:3, ')');end; var  A, B: TVector;begin  A := Vector(1, 0);  B := Vector (0, 1);   WriteVector('A', A);  WriteVector('B', B);  WriteVector('GetLeftVector(A, B)', GetLeftVector(A, B));   ReadLn;end. ---------------------------------------------------------------------- wp · 2026-03-10 10:40 Quote from: hedgehog on March 10, 2026, 08:54:14 amQuoteNo, I'm not talking about the algorithm itself, but about the calls to MyFunc. In your case, it is simple, but I could imagine that such a function can be quite complex. Just need to lower the sampling frequency. Instead: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i dx:= kx/100; //100 samples/pixel need: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i dx:= kx/15; //15 samples/pixelAh, as I understand now you are doing some massive oversampling of each pixel which helps you to detect the sharp maximum, and use the "swing door trend" algorithm to reject all duplicate pixels and pixels which do not change in y significantly. Although the peak detection is greatly improved compared with the current TAChart routine calculating only a single value per pixel it is not "fool-proof": If I am stupid enough to plot your function y = 1/(abs(x)+0.001) in the range -1E9 to +1E9 there are also cases, where the position of the maximum is missed visibly. ---------------------------------------------------------------------- hedgehog · 2026-03-10 12:29 QuoteAh, as I understand now you are doing some massive oversampling of each pixel which helps you to detect the sharp maximum, and use the "swing door trend" algorithm to reject all duplicate pixels and pixels which do not change in y significantly. Not exactly. It's not about finding a maximum. The SDT algorithm replaces a group of points with a line, guaranteeing that all "discarded" points are no more than epsilon away from the line. I tried plotting it over the range of -1e9 to 1e9. The result, as you can see in the image, isn't too bad. The peak height is certainly smaller, but it's still easily discernible visually. ---------------------------------------------------------------------- wp · 2026-03-10 12:43 Quote from: hedgehog on March 10, 2026, 01:29:59 pmQuoteAh, as I understand now you are doing some massive oversampling of each pixel which helps you to detect the sharp maximum, and use the "swing door trend" algorithm to reject all duplicate pixels and pixels which do not change in y significantly. Not exactly. It's not about finding a maximum. The SDT algorithm replaces a group of points with a line, guaranteeing that all "discarded" points are no more than epsilon away from the line. The algorithm, ok. But applied to the topic of this post, massive oversampling is the only way to detect such a sharp maximum (or minimum), isn't it? Quote from: hedgehog on March 10, 2026, 01:29:59 pmI tried plotting it over the range of -1e9 to 1e9. The result, as you can see in the image, isn't too bad. The peak height is certainly smaller, but it's still easily discernible visually. I also client-aligned the Paintbox and increased/decreased the width of the form. Then the peak height was jumping up and down. One more question: Wouldn't it be sufficient to compare the slopes of the test lines, rather than doing these multiple left-right comparisons? Of course, division is more expensive than multiplication. But how many multiplications have the same effect as one division? ---------------------------------------------------------------------- hedgehog · 2026-03-10 13:03 QuoteBut applied to the topic of this post, massive oversampling is the only way to detect such a sharp maximum (or minimum), isn't it Yes, that's correct. Note that the calculations are performed on the original data, which is very fast. I ran tests and found that the simplification function runs in 0.3 ms for a screen width of 900 pixels and in 0.6 ms for a screen width of 1800 pixels. Furthermore, this function creates a polyline from just a few dozen points! This significantly reduces rendering time. ---------------------------------------------------------------------- hedgehog · 2026-03-11 08:50 QuoteLooking along the direction of A the left vector is B, and conversely, the same result is obtained when looking along B where A is on the right side, i.d. the "left" vector must be B. You've noticed that correctly. But the algorithm is symmetrical about the x-axis. Nevertheless, to avoid confusion, I've made the appropriate changes. Also: Vectors have been renamed (UpVector, DownVector) Since we're dealing with a function (where x is monotonically increasing), the vector type simply degenerates into a real number. (type TVector = double) Moreover, with minimal modifications, this also applies to time series. ---------------------------------------------------------------------- wp · 2026-03-12 23:36 Now I spent some time with this algorithm and was able to integrate it into TAChart's TFuncSeries. I am attaching a small demo testing a variety of topics (rotation of axes, axis transforms, domain exclusions), and it seems to me that everything is working correctly, but I would appreciate if you could test it before I commit it to the Lazarus repository. Make a backup copy of your tafuncseries.pas and tacustomfuncseries.pas files (in folder components/tachart of your Lazarus installation) and replace these two files by those that you find in the attached zip. Rebuild the IDE. The TFuncSeries has a few new properties now: - StepMode = (smConstant, smAdaptive) -- constant is the previous (and still default) behaviour with constant steps, adaptive is the new behaviour. Having StepSize=smAdaptive replaces the curve drawing method ForEachPoint by a new method ForEachAdaptivePoint - PixelOversampling -- determines how often a pixel is sampled at different locations. This is the constant 100 or 15 that you mentioned in reply #10. - Epsilon -- determines the maximum pixel deviation in y direction at which a line segment is drawn. The old property Step is reused as maximum step size after which a line segment is drawn for sure. Switching StepMode stores the current Step settings and restores those for the other mode. There seems to be an issue in the combination of "xy rotated" and "y logarithmic", but the standard TFuncSeries has the same, therefore, I am ignoring this for the moment. ---------------------------------------------------------------------- hedgehog · 2026-03-14 07:37 Hi. In my case (Lazarus 4.4 and Windows 10 64-bit), rebuilding the IDE causes a compilation error in the TACustomFuncSeries unit. tacustomfuncseries.pas(202,11) Error: identifier idents no member "SetEnhancedBrokenLines" tacustomfuncseries.pas(203,28) Error: identifier idents no member "GetPenStyle" tacustomfuncseries.pas(211,11) Error: identifier idents no member "SetEnhancedBrokenLines" tacustomfuncseries.pas(212,11) Error: identifier idents no member "SetPenStyle" ---------------------------------------------------------------------- wp · 2026-03-14 09:43 Comment these lines out. They belong to features planned for Laz 5.0. The modified funcseries should work without them. ---------------------------------------------------------------------- hedgehog · 2026-03-14 13:14 Unfortunately, the result was negative. I had to comment out about 300..400 lines in unit TAFuncSeries. Result: nothing. ---------------------------------------------------------------------- wp · 2026-03-14 14:05 I see that the EnhancedChartPen is used at many many places. It would have been better for me to tell you that you should redefine a dummy pen type TEnhancedChartPen instead... Please test the attached files in which I made all modification needed for Laz 4.4 (TATypes is included now, too, because this is where TEnhancedChartPen is declared). Tested on my system (Windows 11), and the demo is working fine. ---------------------------------------------------------------------- hedgehog · 2026-03-15 05:58 Hi, wp Yes, everything is fine now. So, at first glance, the function series with adaptive stepping works perfectly. P.S. I ran some tests and measured the rendering time. The results are extremely interesting. In some cases, the function graph rendering speed is 2-4 times faster when using simplification. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Draw with simplify  (epsilon=1; step = 20; PixelOversampling = 16)Width=900; Pen=1;  t = 0.65 ms; 58 ptsWidth=900; Pen=3;  t = 0.85 ms; 58 ptsWidth=1900; Pen=1; t = 1.7 ms;  97 ptsWidth=1900; Pen=3; t = 2.0 ms;  97 pts Dummy draw (step = 1)Width=900; Pen=1;  t = 0.83 ms; 901 ptsWidth=900; Pen=3;  t = 3.61 ms; 901 ptsWidth=1900; Pen=1; t = 2.1 ms; 1901 ptsWidth=1900; Pen=3; t = 7.8 ms; 1901 pts Dummy draw (step = 2)Width=900; Pen=1;  t = 0.5 ms; 451 ptsWidth=900; Pen=3;  t = 1.9 ms; 451 ptsWidth=1900; Pen=1; t = 1.4 ms; 954 ptsWidth=1900; Pen=3; t = 4.3 ms; 954 pts