klipper icon indicating copy to clipboard operation
klipper copied to clipboard

S-Curve acceleration?

Open dragonnn opened this issue 8 years ago • 653 comments

klipper uses standard trapezoid acceleration as far I know. I never seen a firmware with s-curve like acceleration and I think it would work better for printers Some video from https://www.youtube.com/watch?v=qYJpl7SNoww

Since klipper has enough processing power and the code is well organized I think it should be easy to implement.

dragonnn avatar Dec 14 '17 18:12 dragonnn

On Thu, Dec 14, 2017 at 10:22:54AM -0800, Mateusz wrote:

klipper uses standard trapezoid acceleration as far I know. I never seen a firmware with s-curve like acceleration and I think it would work better for printers Some video from https://www.youtube.com/watch?v=qYJpl7SNoww

Since klipper has enough processing power and the code is well organized I think it should be easy to implement.

This certainly would be interesting. I don't have any immediate plans to implement it.

S-curves would only need host code changes (no need to change the micro-controller code).

I think one challenge to implementing s-curves would be proper handling of lots of small moves. The current trapezoid generator can seamless accelerate over many small moves, seamlessly cruise over lots of small moves, and seamlessly decelerate over lots of small moves. In effect, if one big long move is broken up into many small moves, there is no adverse impact. This is a nice feature as current g-code slicers tend to emit lots of tiny moves when handling arcs. Having similar flexibility while using s-curves might be challenging.

-Kevin

KevinOConnor avatar Dec 15 '17 04:12 KevinOConnor

Yeah I know it would only need host code changes. Probably you are right that handling many small moves like on a arc could be challenging. But I think it could be worth the trouble.

dragonnn avatar Dec 15 '17 07:12 dragonnn

https://github.com/synthetos/TinyG/wiki/Jerk-Controlled-Motion-Explained

I stumbled over tinyGs implementation yesterday ( Was searching for an alternative to Mach3 for my cnc ) and thought it might be helpful.

Tiny G even accepts Marlin formatted G-Code but has no pressure advance implemented and relies on doing the calculations on a Arduino Due which is not as elegant as doing them on a pi imo.

In a perfect world i would control Cnc, co2 Laser and 3D printers straight from klipper.

My soul is on sale, what do you need kevin ;)

Edit: interestingly enough, ultimaker cloned tinyg for their next commercial controller ( based on a "Tigershark" motion controller board https://github.com/adamjvr/Tigershark3D )

lenne0815 avatar Dec 27 '17 10:12 lenne0815

That TinyG wiki page is an amazing find! Those graphs are glorious :)

The 6th-order motion planning seems to be implemented here. Pay attention to the code sections that are #ifndef __JERK_EXEC:

https://github.com/synthetos/TinyG/blob/master/firmware/tinyg/plan_exec.c#L243

They're using 5th-order Bezier velocity curves to get 6th-order position planning. The velocity planning takes in a starting velocity (Vi), a target velocity (Vt), and the number of steps over which you would like to change velocity (mr.segments). The code then plans a velocity for each one of those steps using a 5th-order Bezier curve.

When planning each velocity change, the math assumes that acceleration and jerk start at zero. This allows them to significantly simplify the math.

I think this means that velocity can be non-zero at the start of each line, but acceleration must be zero at the start of each line. So if a large line were to be broken into many small colinear lines, I think the motion planning would be able to seamlessly cruise over those lines, but not seamlessly accelerate over them. Acceleration would happen briefly within each small line, but the acceleration would start/stop frequently across the many small lines.

I think they mitigate the issue by ignoring moves that are small until the accumulated error is larger than a certain threshold. I'm not sure how effective that mitigation would be for the gcode generated by 3D printer slicers.

Note that this is just my interpretation of the code/math, I could be wrong =P

ceryen avatar Jan 03 '18 20:01 ceryen

Note that they are still using trapezoids to drive overall velocity changes, it's just that the velocity changes are smoothed using the 5th-order Bezier curves.

If the Bezier math could be updated so that the start of each velocity curve has non-zero initial acceleration and initial jerk, then you could chain the acceleration ramp of multiple trapezoids together. This might then allow smooth acceleration over many small lines segments.

Within the Bezier math, I believe that D corresponds to initial jerk, E corresponds to initial acceleration, and F corresponds to initial velocity. They set the D and E coefficients to zero under the assumption that each velocity curve starts with zero initial acceleration and initial jerk. You could instead set the D and E coefficients to non-zero initial acceleration and initial jerk values. The D, E, and F coefficients would then constrain the values of P_0, P_1, and P_2, they would no longer be set to the initial velocity. The constrained values of P_0, P_1, and P_2 would then have to be propagated into the A, B, and C coefficients, and the rest of the math would have to be updated.

ceryen avatar Jan 03 '18 21:01 ceryen

Hmmm would be make a difference if we would use a true s-curce or a smoothed trapezoid? I think the second would be even better for printing times and speeds.

dragonnn avatar Jan 03 '18 21:01 dragonnn

A true S-curve would theoretically lead to the smoothest motion, translating to less vibration, less noise, and higher quality prints. Simply smoothing the trapezoid might be good enough though depending on the smoothing used.

ceryen avatar Jan 03 '18 22:01 ceryen

I think the main advantage of using s curve smoothing over plain trapezoidal planning is that the inertia of the linear drive is taken into account, doesnt matter that much with belts and pulleys and a light extruder, makes a much bigger difference trying to rotate a 5kg leadscrew. Ill have g2core up and running soonish on my big gantry cnc, im exited to see what it brings to the table irl, especially how it behaves in conjunction with toolpath smoothing from fusion360, beforehand toolpath smoothing was done by mach3 with sometimes more than lacking results.

lenne0815 avatar Jan 03 '18 22:01 lenne0815

all these kinds of planning with curves are approximations.

In general, we have a physical system with physical limitations. We calculate some movement for it. But it can only follow the calculated movement if those physical limitations are obeyed.

The perfect planning would simulate the complete physical model with something like differential equations and would optimize movement calculations within the known limits.

For a limited acceleration you get the fastest movement if you always accelerate with the maximum (so the result is constant acceleration, which is used by ).

Acceleration is limited by the mass to be moved and the torque of the steppers, and also limited by the construction of the printer (e.g. you want to reduce resonance). It's not easily determined, so the value will be a result of experimentation and experience or you keep it safe by staying below a limit.

Now the question is, what is the physical meaning of higher derivatives (jerk, etc.) and by which physical conditions they are limited. Sure, you could limit those too, which is done by the 6th-order motion planning.

BUT, who said it's the main problem? All this assumes that these are constant limits. But for example the maximum torque a motor can produce is everything else but a constant. That's why I agree with @lenne0815 that this kind of motion planning is probably most effective for CNC machines, because they have big masses and their motion limits may mostly depend on these alone.

Stepping is a mathematical problem in itself. A pure theoretical step would mean you have infinite velocity for an infinitesimal short time (-> Dirac pulse) at the edge of the step and zero for the rest. In reality there are several physical effects that smooth the behavior, like inductance of the motor coils, mass etc. It needs some clever engineering to optimize the behavior, that's why it takes something like a tmc2130...

I am not sure if simply adding more derivatives will help a lot, when at the same time assuming constant limits is known to be wrong. They claim to be the only that use 6 orders, but I think it has a reason why the industry still uses only three. Probably the higher derivations are hidden by other errors in the model. At least the 3rd order seems to make sense.

Seeing improvements depends a lot on the competition. I am sure 6th order motion planning will be better than Marlin. Though, I also saw improvement when switching from Smoothieware to Marlin, which was caused by Marlin forcing me to use lower acceleration, which improved a lot in the print. But real comparision is done by pushing the limits. However, Klipper was clearly ahead of both. So, I am excited to see some comparison between Klipper and some 6th order motion planning on a real machine.

The general strategy for movement algorithms seems to be trial and error. Usually they assume some physical relations, then implement an algorithm based on these assumptions and try that. Some of this may improve movement, but then it's still not clear, if the success is only based on a random correlation or if the physical behavior is really understood. I am usually missing the measurements to prove those assumptions. I understand that nobody wants to do this because it is a lot of work. Today everything is simulated, but from time to time you need to prove if the simulation provides correct results.

I see some potential in the measurement features of the tmc2130. It could be used to really measure what's going on while moving and to find hotspots where movements could be improved. May be at some time we can manage to log these values together with coordinates. If everything is fast enough, measurements could also be used to adjust movement parameters in real time. TMC seems to have hardware controllers that can use those measurements. May be the distributed nature of Klipper is not ideal to handle this kind of scenario. But at least it allows to have a dedicated MCU for the main axes (usually XY), which could handle such a control loop.

hg42 avatar Jan 04 '18 13:01 hg42

@hg42 Hmm, albeit creating a real physical model is obviously the best way to do it i personally think that "6th" order motion planning is close enough, dialing in mms3 on my machine by trial and error will yield a pretty spot on image of the forces at play, after finding these values you usually back of that for atleast 20% because youll need to compensate for cutting forces etc, so dialing it in after a model wouldnt yield to much advantage irl.

Interesting find that you found marlin to be better than smoothieware, can you maybe check at what point in time that was ? Right now smoothieware and klipper are based on the same base model for motion planning and i wouldnt know how to explain a bigger difference there, so i guess it wasnt implemented into smoothieware at that point.

The reason we dont see advanced motion planners anywere is simple i think, machine manufacturers keep them well under wraps, cncs are usually sold by "look at this surface finish in this material at these feeds" which includes the motion planner part but its nowhere discussed.

I think the best bet is to test it but as long as g2core doesnt support pressure advance theres not really a point, that would hold back printing speeds so much that motion planner differences wouldnt really come into play imo.

lenne0815 avatar Jan 04 '18 15:01 lenne0815

@lenne0815 my point is that even 6th order calculation doesn't help if it doesn't take into account all important(!) dependencies. Example: on a delta printer, you have the linear axes along the towers where the masses of the carriages have to be part of the calculation and you have to add the mass of the effector with hotend, eventually an extruder etc. via some geometric calculation. This is not trivial, but usually the acceleration is still given as a fixed value for the linear axes. In this case 6th order doesn't help. Or what about microstep length being different depending on the position in the step cycle? The same goes for torque. I guess these kinds of errors always have a greater effect than orders 4-6.

The firmware changed from Smoothieware to a recent Marlin bugfix-2.0.x (some weeks ago, also on the same Smoothieboard) to Klipper on Pi3+Mega2560/RAMPS+some_Melzi. Marlin ran smoother than Smoothieware on my Smoothieboard, but as I tried to say, this was some kind of imaginary improvement, because Marlin somehow forced me to lower the acceleration settings. I am sure if I would use the same settings for Smoothieware it would be similar. But I also found if using sane settings Marlin2 can work as smooth as Smoothieware on my corexy. I mentioned Marlin to show that comparisons are dangerous. There are too many things to forget. E.g. how do you compare the jerk setting in Marlin with the junction deviation in Smoothieware? This has a huge effect on acceleration settings (and in fact this was the reason I had to lower acceleration with Marlin). I found if I use jerk near zero in Marlin it is quite similar to Klipper, but still not as smooth. There seems to be some roughness.

At least my Smoothieware version doesn't compare to Klipper, because Smoothieware uses segmentation (though I read that it now supports segment free planning, which I also tried but it didn't work). And I think Klipper calculates more exact, at least the movement is noticeably smoother than with Smoothie (and Marlin2). I can use higher speeds and I could also use some a higher acceleration if I would want. But I prefer to use low currents on my motors. So acceleration is low but speed is high.

I also used all three firmwares with tmc2130 on XY (in standalone mode for now ~= tmc2100) where you can hear every non-smooth movement as some kind of hum. But I cannot compare because it's difficult to do from memory. The difference is not very big and even some wind can create much different impressions.

hg42 avatar Jan 04 '18 17:01 hg42

Hm,i think your over complicating it, a single delta stepper nearly always pulls the same load ( depending on the angle of the 3 axis it can differ a tiny bit obviously but in the grand scheme of things its negligible ) with setting mms3 close to its mechanical properties youll be very close to what the motor can actually achieve under ideal circumstances and then again one would back of that a bit so the motors dont stall when the extruder hits overextruded parts or warping overhangs.

A perfect model would just bring the system even closer to its theoretical maximum performance but after backing of a bit for rl reasons i think you would end up with pretty much the same outcome.

The main reason for scurve being theoretically better than trapezoidal is that accel ramps are not switched instantaneous but rather blended, just as the outcome of a simulation. Blending factors obviously not as precise as from a real simulation but then again as i mentioned already imo, plays no role irl as we have other factors outside of the linear system limiting machine movement.

Jerk from marlin cannot be compared because god bless it doesnt exist in klipper, its just a simple value how big an instantaneous speed change can happen, to high equates to stalling motors as they can compensate only so much oscillating overshoot, any value above 0 results in forced artificial ringing. At jerk 0 marlin is just dead slow as theres afaik none or only very little blending going on at directory changes. ( i never tested jerk 0 on marlin, luckily i could jump straight to klipper once i realized what jerk in marlin does )

lenne0815 avatar Jan 04 '18 18:01 lenne0815

isn't that what I said? I doubt the 4th to 6th order are noticeable at all. But if they are, I guess other things have to be taken into account first. 3rd order may be useful, but I am not sure. I want to see it, before I accept it.

Given that a stepper always starts at a minimum speed (it's not analog!) the jerk setting from Marlin may not be too unreal if not set too high. With my low settings this worked good enough. But I have to admit, I used Marlin only for a few weeks.

reason for scurve being theoretically better than trapezoidal is that accel ramps are not switched instantaneous but rather blended

I think this sounds better than it is. If you want to accelerate your car as fast as possible, do you slowly press down your pedal?

hg42 avatar Jan 04 '18 18:01 hg42

@hg42 Jerk is used at any cornering entry speed conceivable jerk 20 happens in marlin from f.e. 100mms to 80mms or from 50 up to 70, its used basically to cut of all the nifty motion planning necessary for smooth movements with one big slap.

A car is a bad analogy as its acceleration ramps are self limited by design and thereby "forced 3rd order" the motor is held back by its connection to the street, if you hold back a stepper from its commanded pulsing it just stalls, so ideally you need to estimate how much its held back and account for that.

lenne0815 avatar Jan 04 '18 18:01 lenne0815

You are taking this topic way too far. Just look at this video https://www.youtube.com/watch?v=qYJpl7SNoww this shows really good how in practice any think like s-curve is a good idea for a 3dprinter. It would allowing to maintain higher printing speed and acceleration without increasing the problem called "ringing". A good example of this problem https://cdn.thingiverse.com/renders/bc/d5/47/4c/c0/_7280628_preview_featured.jpg

dragonnn avatar Jan 04 '18 19:01 dragonnn

Note that the s-curve beer is even faster then the trapezoid and it doesn't split out. In a 3d printer we are to moving parts with have high inertia - a direct drive extuder, heatbead in a prusa like printer. When such mass stops or accelerates the belt stretches due the not smooth acceleration and this causes ringing

dragonnn avatar Jan 04 '18 19:01 dragonnn

Play the beer video at speed 0.25 in youtube. There is no noticeable acceleration phase at all or at least not appropriate for such a beer. The video created by Trinamic https://www.youtube.com/watch?v=PGYBqAphBHw looks more correct, but you cannot see it in comparison. The beer may be good for promotion and looks funny, but it is not exactly our problem.

However, I accept your explanation about the belts. It's a system with masses, springs and friction. Instead the beer has no damping at all. But anyways, I understand the effect. I already said 3rd order may be useful. But 4 or even 6?

The slower acceleration at start and end of the move has to be compensated by a higher speed in between. This has disadvantages:

  • to reach the same performance in total the moves must be longer
  • the speed is limited by extrusion

But on the other side bowden systems could have additional benefits? For bowden systems there are people that want to keep the speed constant, especially at direction changes, so acceleration near zero might be good for that.

To be clear, I am not speaking against experimenting. Klipper is the perfect platform to try this. Anyone can do...

hg42 avatar Jan 04 '18 20:01 hg42

I think the beer is good to visualize the effects but as its running a single up / constant / down ramp it doesnt reflect that much on what we are doing with our printers, the differences between scurve and trapezoidal arent that big imo. Still, it would be great to see somebody a lot more intelligent than we are implementing it in a way that it can handle shoddy slicer gcode output. Maybe some day soon slicers will be more akin to cnc gcode generators aswell, right now even basic functions like min segment length are not existing and i havent seen an arc ( might be wrong on that ) at all.

lenne0815 avatar Jan 04 '18 21:01 lenne0815

I had a quick look at the math here to and tried the follow it in plan_exec. See here.

What is missing is a proper understanding of the trapezoid generator and derive its math. But at least it is a start.

mabl avatar Feb 07 '18 13:02 mabl

I'm really interested in seeing s-curve motion profiling on Klipper. I was going to have a crack at it myself.

This might be a bit long, but I set myself a task recently of figuring out the trapezoidal and s-curve motion profile maths. I've done the trapezoidal motion, but I've hit a roadblock on the s-curve. It ends up being a bit more complex and I've not found a nice method of representing it. So if anyone has an idea then please met me know.

This might be a bit long, but I'll try and explain my current logic.

As the acceleration profile is a order equation, this gives a velocity profile of the order and a position of the this gives the following equations.

Integrating gives velocity

Integrating again gives position

if we have a cruising speed of and a cruising time of we can figure out the and times by

and

substituting these into the equation for x and solving for

solving the roots for this equation with gives you a positive root for

If the value for exceeds your then you rearrange this to solve for

The problem with s-curve equations is that each term is at least 1 order more complex, so you have to solve for a lot more variables. Basically the acceleration and deceleration phases are this complex and it just makes things that little bit more difficult. There are probably analytical methods to find the solution, but I'm trying to be a purist and find a numeric method.

Anyway. I thought this might be interesting for people.

richClubb avatar Mar 26 '18 23:03 richClubb