1 // digitalfilter.cxx - a selection of digital filters
3 // Written by Torsten Dreyer
4 // Based heavily on work created by Curtis Olson, started January 2004.
6 // Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt
7 // Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de
9 // Washout/high-pass filter, lead-lag filter and integrator added.
10 // low-pass and lag aliases added to Exponential filter,
11 // rate-limit added. A J Teeder 2013
13 // This program is free software; you can redistribute it and/or
14 // modify it under the terms of the GNU General Public License as
15 // published by the Free Software Foundation; either version 2 of the
16 // License, or (at your option) any later version.
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 // General Public License for more details.
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include "digitalfilter.hxx"
29 #include "functor.hxx"
37 namespace FGXMLAutopilot {
43 class DigitalFilterImplementation : public SGReferenced {
45 virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode) = 0;
47 virtual ~DigitalFilterImplementation() {}
48 DigitalFilterImplementation();
49 virtual void initialize( double initvalue ) {}
50 virtual double compute( double dt, double input ) = 0;
51 bool configure( SGPropertyNode_ptr configNode );
53 void setDigitalFilter( DigitalFilter * digitalFilter ) { _digitalFilter = digitalFilter; }
56 DigitalFilter * _digitalFilter;
59 /* --------------------------------------------------------------------------------- */
60 /* --------------------------------------------------------------------------------- */
61 class GainFilterImplementation : public DigitalFilterImplementation {
63 InputValueList _gainInput;
64 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
66 GainFilterImplementation() : _gainInput(1.0) {}
67 double compute( double dt, double input );
70 class ReciprocalFilterImplementation : public GainFilterImplementation {
72 double compute( double dt, double input );
75 class DerivativeFilterImplementation : public GainFilterImplementation {
76 InputValueList _TfInput;
78 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
80 DerivativeFilterImplementation();
81 double compute( double dt, double input );
82 virtual void initialize( double initvalue );
85 class ExponentialFilterImplementation : public GainFilterImplementation {
87 InputValueList _TfInput;
88 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
90 double _output_1, _output_2;
92 ExponentialFilterImplementation();
93 double compute( double dt, double input );
94 virtual void initialize( double initvalue );
97 class MovingAverageFilterImplementation : public DigitalFilterImplementation {
99 InputValueList _samplesInput;
101 std::deque <double> _inputQueue;
102 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
104 MovingAverageFilterImplementation();
105 double compute( double dt, double input );
106 virtual void initialize( double initvalue );
109 class NoiseSpikeFilterImplementation : public DigitalFilterImplementation {
112 InputValueList _rateOfChangeInput;
113 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
115 NoiseSpikeFilterImplementation();
116 double compute( double dt, double input );
117 virtual void initialize( double initvalue );
120 class RateLimitFilterImplementation : public DigitalFilterImplementation {
123 InputValueList _rateOfChangeMax;
124 InputValueList _rateOfChangeMin ;
125 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
127 RateLimitFilterImplementation();
128 double compute( double dt, double input );
129 virtual void initialize( double initvalue );
132 class IntegratorFilterImplementation : public GainFilterImplementation {
134 InputValueList _TfInput;
135 InputValueList _minInput;
136 InputValueList _maxInput;
139 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
141 IntegratorFilterImplementation();
142 double compute( double dt, double input );
143 virtual void initialize( double initvalue );
146 class HighPassFilterImplementation : public GainFilterImplementation {
148 InputValueList _TfInput;
151 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
153 HighPassFilterImplementation();
154 double compute( double dt, double input );
155 virtual void initialize( double initvalue );
157 class LeadLagFilterImplementation : public GainFilterImplementation {
159 InputValueList _TfaInput;
160 InputValueList _TfbInput;
163 bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode );
165 LeadLagFilterImplementation();
166 double compute( double dt, double input );
167 virtual void initialize( double initvalue );
169 /* --------------------------------------------------------------------------------- */
170 /* --------------------------------------------------------------------------------- */
172 } // namespace FGXMLAutopilot
174 using namespace FGXMLAutopilot;
176 /* --------------------------------------------------------------------------------- */
177 /* --------------------------------------------------------------------------------- */
178 DigitalFilterImplementation::DigitalFilterImplementation() :
183 bool DigitalFilterImplementation::configure( SGPropertyNode_ptr configNode )
185 for (int i = 0; i < configNode->nChildren(); ++i ) {
186 SGPropertyNode_ptr prop;
188 SGPropertyNode_ptr child = configNode->getChild(i);
189 string cname(child->getName());
191 if( configure( cname, child ) )
194 } // for configNode->nChildren()
199 /* --------------------------------------------------------------------------------- */
200 /* --------------------------------------------------------------------------------- */
202 double GainFilterImplementation::compute( double dt, double input )
204 return _gainInput.get_value() * input;
207 bool GainFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
209 if (nodeName == "gain" ) {
210 _gainInput.push_back( new InputValue( configNode, 1 ) );
217 /* --------------------------------------------------------------------------------- */
218 /* --------------------------------------------------------------------------------- */
220 double ReciprocalFilterImplementation::compute( double dt, double input )
222 if( input >= -SGLimitsd::min() && input <= SGLimitsd::min() )
223 return SGLimitsd::max();
225 return _gainInput.get_value() / input;
229 /* --------------------------------------------------------------------------------- */
230 /* --------------------------------------------------------------------------------- */
232 DerivativeFilterImplementation::DerivativeFilterImplementation() :
237 void DerivativeFilterImplementation::initialize( double initvalue )
239 _input_1 = initvalue;
243 bool DerivativeFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
245 if( GainFilterImplementation::configure( nodeName, configNode ) )
248 if (nodeName == "filter-time" ) {
249 _TfInput.push_back( new InputValue( configNode, 1 ) );
256 double DerivativeFilterImplementation::compute( double dt, double input )
258 double output = (input - _input_1) * _TfInput.get_value() * _gainInput.get_value() / dt;
264 /* --------------------------------------------------------------------------------- */
265 /* --------------------------------------------------------------------------------- */
267 MovingAverageFilterImplementation::MovingAverageFilterImplementation() :
272 void MovingAverageFilterImplementation::initialize( double initvalue )
274 _output_1 = initvalue;
277 double MovingAverageFilterImplementation::compute( double dt, double input )
279 typedef std::deque<double>::size_type size_type;
280 size_type samples = _samplesInput.get_value();
282 if (_inputQueue.size() != samples) {
283 // For constant size filters, this code executed once.
284 bool shrunk = _inputQueue.size() > samples;
285 _inputQueue.resize(samples, _output_1);
288 for (size_type ii = 0; ii < samples; ii++)
289 _output_1 += _inputQueue[ii];
290 _output_1 /= samples;
294 double output_0 = _output_1 + (input - _inputQueue.back()) / samples;
296 _output_1 = output_0;
297 _inputQueue.pop_back();
298 _inputQueue.push_front(input);
302 bool MovingAverageFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
304 if (nodeName == "samples" ) {
305 _samplesInput.push_back( new InputValue( configNode, 1 ) );
312 /* --------------------------------------------------------------------------------- */
313 /* --------------------------------------------------------------------------------- */
315 NoiseSpikeFilterImplementation::NoiseSpikeFilterImplementation() :
320 void NoiseSpikeFilterImplementation::initialize( double initvalue )
322 _output_1 = initvalue;
325 double NoiseSpikeFilterImplementation::compute( double dt, double input )
327 double delta = input - _output_1;
328 if( fabs(delta) <= SGLimitsd::min() ) return input; // trivial
330 double maxChange = _rateOfChangeInput.get_value() * dt;
331 const PeriodicalValue * periodical = _digitalFilter->getPeriodicalValue();
332 if( periodical ) delta = periodical->normalizeSymmetric( delta );
334 if( fabs(delta) <= maxChange )
335 return (_output_1 = input);
337 return (_output_1 = _output_1 + copysign( maxChange, delta ));
340 bool NoiseSpikeFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
342 if (nodeName == "max-rate-of-change" ) {
343 _rateOfChangeInput.push_back( new InputValue( configNode, 1 ) );
350 /* --------------------------------------------------------------------------------- */
352 RateLimitFilterImplementation::RateLimitFilterImplementation() :
357 void RateLimitFilterImplementation::initialize( double initvalue )
359 _output_1 = initvalue;
362 double RateLimitFilterImplementation::compute( double dt, double input )
364 double delta = input - _output_1;
367 if( fabs(delta) <= SGLimitsd::min() ) return input; // trivial
369 double maxChange = _rateOfChangeMax.get_value() * dt;
370 double minChange = _rateOfChangeMin.get_value() * dt;
371 // const PeriodicalValue * periodical = _digitalFilter->getPeriodicalValue();
372 // if( periodical ) delta = periodical->normalizeSymmetric( delta );
375 if(delta >= maxChange ) output = _output_1 + maxChange;
376 if(delta <= minChange ) output = _output_1 + minChange;
382 bool RateLimitFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
384 if (nodeName == "max-rate-of-change" ) {
385 _rateOfChangeMax.push_back( new InputValue( configNode, 1 ) );
388 if (nodeName == "min-rate-of-change" ) {
389 _rateOfChangeMin.push_back( new InputValue( configNode, 1 ) );
396 /* --------------------------------------------------------------------------------- */
397 /* --------------------------------------------------------------------------------- */
399 ExponentialFilterImplementation::ExponentialFilterImplementation()
400 : _isSecondOrder(false),
406 void ExponentialFilterImplementation::initialize( double initvalue )
408 _output_1 = _output_2 = initvalue;
411 double ExponentialFilterImplementation::compute( double dt, double input )
413 input = GainFilterImplementation::compute( dt, input );
414 double tf = _TfInput.get_value();
418 // avoid negative filter times
419 // and div by zero if -tf == dt
421 double alpha = tf > 0.0 ? 1 / ((tf/dt) + 1) : 1.0;
424 output_0 = alpha * alpha * input +
425 2 * (1 - alpha) * _output_1 -
426 (1 - alpha) * (1 - alpha) * _output_2;
428 output_0 = alpha * input + (1 - alpha) * _output_1;
430 _output_2 = _output_1;
431 return (_output_1 = output_0);
434 bool ExponentialFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
436 if( GainFilterImplementation::configure( nodeName, configNode ) )
439 if (nodeName == "filter-time" ) {
440 _TfInput.push_back( new InputValue( configNode, 1 ) );
444 if (nodeName == "type" ) {
445 string type(configNode->getStringValue());
446 _isSecondOrder = type == "double-exponential";
452 /* --------------------------------------------------------------------------------- */
454 IntegratorFilterImplementation::IntegratorFilterImplementation() :
460 void IntegratorFilterImplementation::initialize( double initvalue )
462 _input_1 = _output_1 = initvalue;
466 bool IntegratorFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
468 if( GainFilterImplementation::configure( nodeName, configNode ) )
470 if (nodeName == "u_min" ) {
471 _minInput.push_back( new InputValue( configNode, 1 ) );
474 if (nodeName == "u_max" ) {
475 _maxInput.push_back( new InputValue( configNode, 1 ) );
481 double IntegratorFilterImplementation::compute( double dt, double input )
483 double output = _output_1 + input * _gainInput.get_value() * dt;
484 double u_min = _minInput.get_value();
485 double u_max = _maxInput.get_value();
486 if (output >= u_max) output = u_max; // clamping inside "::compute" prevents integrator wind-up
487 if (output <= u_min) output = u_min;
494 /* --------------------------------------------------------------------------------- */
496 HighPassFilterImplementation::HighPassFilterImplementation() :
503 void HighPassFilterImplementation::initialize( double initvalue )
505 _input_1 = initvalue;
506 _output_1 = initvalue;
509 double HighPassFilterImplementation::compute( double dt, double input )
511 input = GainFilterImplementation::compute( dt, input );
512 double tf = _TfInput.get_value();
516 // avoid negative filter times
517 // and div by zero if -tf == dt
519 double alpha = tf > 0.0 ? 1 / ((tf/dt) + 1) : 1.0;
520 output = (1 - alpha) * (input - _input_1 + _output_1);
526 bool HighPassFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
528 if( GainFilterImplementation::configure( nodeName, configNode ) )
531 if (nodeName == "filter-time" ) {
532 _TfInput.push_back( new InputValue( configNode, 1 ) );
539 /* --------------------------------------------------------------------------------- */
541 LeadLagFilterImplementation::LeadLagFilterImplementation() :
548 void LeadLagFilterImplementation::initialize( double initvalue )
550 _input_1 = initvalue;
551 _output_1 = initvalue;
554 double LeadLagFilterImplementation::compute( double dt, double input )
556 input = GainFilterImplementation::compute( dt, input );
557 double tfa = _TfaInput.get_value();
558 double tfb = _TfbInput.get_value();
562 // avoid negative filter times
563 // and div by zero if -tf == dt
565 double alpha = tfa > 0.0 ? 1 / ((tfa/dt) + 1) : 1.0;
566 double beta = tfb > 0.0 ? 1 / ((tfb/dt) + 1) : 1.0;
567 output = (1 - beta) * (input / (1 - alpha) - _input_1 + _output_1);
573 bool LeadLagFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode )
575 if( GainFilterImplementation::configure( nodeName, configNode ) )
578 if (nodeName == "filter-time-a" ) {
579 _TfaInput.push_back( new InputValue( configNode, 1 ) );
582 if (nodeName == "filter-time-b" ) {
583 _TfbInput.push_back( new InputValue( configNode, 1 ) );
588 /* --------------------------------------------------------------------------------- */
589 /* Digital Filter Component Implementation */
590 /* --------------------------------------------------------------------------------- */
592 DigitalFilter::DigitalFilter() :
594 _initializeTo(INITIALIZE_INPUT)
598 DigitalFilter::~DigitalFilter()
603 static map<string,FunctorBase<DigitalFilterImplementation> *> componentForge;
605 bool DigitalFilter::configure(const string& nodeName, SGPropertyNode_ptr configNode)
607 if( componentForge.empty() ) {
608 componentForge["gain"] = new CreateAndConfigureFunctor<GainFilterImplementation,DigitalFilterImplementation>();
609 componentForge["exponential"] = new CreateAndConfigureFunctor<ExponentialFilterImplementation,DigitalFilterImplementation>();
610 componentForge["double-exponential"] = new CreateAndConfigureFunctor<ExponentialFilterImplementation,DigitalFilterImplementation>();
611 componentForge["moving-average"] = new CreateAndConfigureFunctor<MovingAverageFilterImplementation,DigitalFilterImplementation>();
612 componentForge["noise-spike"] = new CreateAndConfigureFunctor<NoiseSpikeFilterImplementation,DigitalFilterImplementation>();
613 componentForge["rate-limit"] = new CreateAndConfigureFunctor<RateLimitFilterImplementation,DigitalFilterImplementation>();
614 componentForge["reciprocal"] = new CreateAndConfigureFunctor<ReciprocalFilterImplementation,DigitalFilterImplementation>();
615 componentForge["derivative"] = new CreateAndConfigureFunctor<DerivativeFilterImplementation,DigitalFilterImplementation>();
616 componentForge["high-pass"] = new CreateAndConfigureFunctor<HighPassFilterImplementation,DigitalFilterImplementation>();
617 componentForge["lead-lag"] = new CreateAndConfigureFunctor<LeadLagFilterImplementation,DigitalFilterImplementation>();
618 componentForge["integrator"] = new CreateAndConfigureFunctor<IntegratorFilterImplementation,DigitalFilterImplementation>();
621 SG_LOG( SG_AUTOPILOT, SG_BULK, "DigitalFilter::configure(" << nodeName << ")" << endl );
622 if( AnalogComponent::configure( nodeName, configNode ) )
625 if (nodeName == "type" ) {
626 string type( configNode->getStringValue() );
627 if( componentForge.count(type) == 0 ) {
628 SG_LOG( SG_AUTOPILOT, SG_BULK, "unhandled filter type <" << type << ">" << endl );
631 _implementation = (*componentForge[type])( configNode->getParent() );
632 _implementation->setDigitalFilter( this );
636 if( nodeName == "initialize-to" ) {
637 string s( configNode->getStringValue() );
639 _initializeTo = INITIALIZE_INPUT;
640 } else if( s == "output" ) {
641 _initializeTo = INITIALIZE_OUTPUT;
642 } else if( s == "none" ) {
643 _initializeTo = INITIALIZE_NONE;
645 SG_LOG( SG_AUTOPILOT, SG_WARN, "unhandled initialize-to value '" << s << "' ignored" );
650 SG_LOG( SG_AUTOPILOT, SG_BULK, "DigitalFilter::configure(" << nodeName << ") [unhandled]" << endl );
651 return false; // not handled by us, let the base class try
654 void DigitalFilter::update( bool firstTime, double dt)
656 if( _implementation == NULL ) return;
659 switch( _initializeTo ) {
661 case INITIALIZE_INPUT:
662 SG_LOG(SG_AUTOPILOT,SG_DEBUG, "First time initialization of " << get_name() << " to " << _valueInput.get_value() );
663 _implementation->initialize( _valueInput.get_value() );
666 case INITIALIZE_OUTPUT:
667 SG_LOG(SG_AUTOPILOT,SG_DEBUG, "First time initialization of " << get_name() << " to " << get_output_value() );
668 _implementation->initialize( get_output_value() );
672 SG_LOG(SG_AUTOPILOT,SG_DEBUG, "First time initialization of " << get_name() << " to (uninitialized)" );
677 double input = _valueInput.get_value() - _referenceInput.get_value();
678 double output = _implementation->compute( dt, input );
680 set_output_value( output );
683 cout << "input:" << input
684 << "\toutput:" << output << endl;