]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/dsp/cmsis_dsp/FilteringFunctions/arm_lms_norm_f32.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / dsp / cmsis_dsp / FilteringFunctions / arm_lms_norm_f32.c
1 /* ----------------------------------------------------------------------    
2 * Copyright (C) 2010-2013 ARM Limited. All rights reserved.    
3 *    
4 * $Date:        17. January 2013
5 * $Revision:    V1.4.1
6 *    
7 * Project:          CMSIS DSP Library    
8 * Title:            arm_lms_norm_f32.c    
9 *    
10 * Description:  Processing function for the floating-point Normalised LMS.    
11 *    
12 * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
13 *  
14 * Redistribution and use in source and binary forms, with or without 
15 * modification, are permitted provided that the following conditions
16 * are met:
17 *   - Redistributions of source code must retain the above copyright
18 *     notice, this list of conditions and the following disclaimer.
19 *   - Redistributions in binary form must reproduce the above copyright
20 *     notice, this list of conditions and the following disclaimer in
21 *     the documentation and/or other materials provided with the 
22 *     distribution.
23 *   - Neither the name of ARM LIMITED nor the names of its contributors
24 *     may be used to endorse or promote products derived from this
25 *     software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
30 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
31 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
34 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
35 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
37 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38 * POSSIBILITY OF SUCH DAMAGE.   
39 * -------------------------------------------------------------------- */
40
41 #include "arm_math.h"
42
43 /**    
44  * @ingroup groupFilters    
45  */
46
47 /**    
48  * @defgroup LMS_NORM Normalized LMS Filters    
49  *    
50  * This set of functions implements a commonly used adaptive filter.    
51  * It is related to the Least Mean Square (LMS) adaptive filter and includes an additional normalization    
52  * factor which increases the adaptation rate of the filter.    
53  * The CMSIS DSP Library contains normalized LMS filter functions that operate on Q15, Q31, and floating-point data types.    
54  *    
55  * A normalized least mean square (NLMS) filter consists of two components as shown below.    
56  * The first component is a standard transversal or FIR filter.    
57  * The second component is a coefficient update mechanism.    
58  * The NLMS filter has two input signals.    
59  * The "input" feeds the FIR filter while the "reference input" corresponds to the desired output of the FIR filter.    
60  * That is, the FIR filter coefficients are updated so that the output of the FIR filter matches the reference input.    
61  * The filter coefficient update mechanism is based on the difference between the FIR filter output and the reference input.    
62  * This "error signal" tends towards zero as the filter adapts.    
63  * The NLMS processing functions accept the input and reference input signals and generate the filter output and error signal.    
64  * \image html LMS.gif "Internal structure of the NLMS adaptive filter"    
65  *    
66  * The functions operate on blocks of data and each call to the function processes    
67  * <code>blockSize</code> samples through the filter.    
68  * <code>pSrc</code> points to input signal, <code>pRef</code> points to reference signal,    
69  * <code>pOut</code> points to output signal and <code>pErr</code> points to error signal.    
70  * All arrays contain <code>blockSize</code> values.    
71  *    
72  * The functions operate on a block-by-block basis.    
73  * Internally, the filter coefficients <code>b[n]</code> are updated on a sample-by-sample basis.    
74  * The convergence of the LMS filter is slower compared to the normalized LMS algorithm.    
75  *    
76  * \par Algorithm:    
77  * The output signal <code>y[n]</code> is computed by a standard FIR filter:    
78  * <pre>    
79  *     y[n] = b[0] * x[n] + b[1] * x[n-1] + b[2] * x[n-2] + ...+ b[numTaps-1] * x[n-numTaps+1]    
80  * </pre>    
81  *    
82  * \par    
83  * The error signal equals the difference between the reference signal <code>d[n]</code> and the filter output:    
84  * <pre>    
85  *     e[n] = d[n] - y[n].    
86  * </pre>    
87  *    
88  * \par    
89  * After each sample of the error signal is computed the instanteous energy of the filter state variables is calculated:    
90  * <pre>    
91  *    E = x[n]^2 + x[n-1]^2 + ... + x[n-numTaps+1]^2.    
92  * </pre>    
93  * The filter coefficients <code>b[k]</code> are then updated on a sample-by-sample basis:    
94  * <pre>    
95  *     b[k] = b[k] + e[n] * (mu/E) * x[n-k],  for k=0, 1, ..., numTaps-1    
96  * </pre>    
97  * where <code>mu</code> is the step size and controls the rate of coefficient convergence.    
98  *\par    
99  * In the APIs, <code>pCoeffs</code> points to a coefficient array of size <code>numTaps</code>.    
100  * Coefficients are stored in time reversed order.    
101  * \par    
102  * <pre>    
103  *    {b[numTaps-1], b[numTaps-2], b[N-2], ..., b[1], b[0]}    
104  * </pre>    
105  * \par    
106  * <code>pState</code> points to a state array of size <code>numTaps + blockSize - 1</code>.    
107  * Samples in the state buffer are stored in the order:    
108  * \par    
109  * <pre>    
110  *    {x[n-numTaps+1], x[n-numTaps], x[n-numTaps-1], x[n-numTaps-2]....x[0], x[1], ..., x[blockSize-1]}    
111  * </pre>    
112  * \par    
113  * Note that the length of the state buffer exceeds the length of the coefficient array by <code>blockSize-1</code> samples.    
114  * The increased state buffer length allows circular addressing, which is traditionally used in FIR filters,    
115  * to be avoided and yields a significant speed improvement.    
116  * The state variables are updated after each block of data is processed.    
117  * \par Instance Structure    
118  * The coefficients and state variables for a filter are stored together in an instance data structure.    
119  * A separate instance structure must be defined for each filter and    
120  * coefficient and state arrays cannot be shared among instances.    
121  * There are separate instance structure declarations for each of the 3 supported data types.    
122  *    
123  * \par Initialization Functions    
124  * There is also an associated initialization function for each data type.    
125  * The initialization function performs the following operations:    
126  * - Sets the values of the internal structure fields.    
127  * - Zeros out the values in the state buffer.    
128  * To do this manually without calling the init function, assign the follow subfields of the instance structure:
129  * numTaps, pCoeffs, mu, energy, x0, pState. Also set all of the values in pState to zero. 
130  * For Q7, Q15, and Q31 the following fields must also be initialized;
131  * recipTable, postShift
132  *
133  * \par    
134  * Instance structure cannot be placed into a const data section and it is recommended to use the initialization function.    
135  * \par Fixed-Point Behavior:    
136  * Care must be taken when using the Q15 and Q31 versions of the normalised LMS filter.    
137  * The following issues must be considered:    
138  * - Scaling of coefficients    
139  * - Overflow and saturation    
140  *    
141  * \par Scaling of Coefficients:    
142  * Filter coefficients are represented as fractional values and    
143  * coefficients are restricted to lie in the range <code>[-1 +1)</code>.    
144  * The fixed-point functions have an additional scaling parameter <code>postShift</code>.    
145  * At the output of the filter's accumulator is a shift register which shifts the result by <code>postShift</code> bits.    
146  * This essentially scales the filter coefficients by <code>2^postShift</code> and    
147  * allows the filter coefficients to exceed the range <code>[+1 -1)</code>.    
148  * The value of <code>postShift</code> is set by the user based on the expected gain through the system being modeled.    
149  *    
150  * \par Overflow and Saturation:    
151  * Overflow and saturation behavior of the fixed-point Q15 and Q31 versions are    
152  * described separately as part of the function specific documentation below.    
153  */
154
155
156 /**    
157  * @addtogroup LMS_NORM    
158  * @{    
159  */
160
161
162   /**    
163    * @brief Processing function for floating-point normalized LMS filter.    
164    * @param[in] *S points to an instance of the floating-point normalized LMS filter structure.    
165    * @param[in] *pSrc points to the block of input data.    
166    * @param[in] *pRef points to the block of reference data.    
167    * @param[out] *pOut points to the block of output data.    
168    * @param[out] *pErr points to the block of error data.    
169    * @param[in] blockSize number of samples to process.    
170    * @return none.    
171    */
172
173 void arm_lms_norm_f32(
174   arm_lms_norm_instance_f32 * S,
175   float32_t * pSrc,
176   float32_t * pRef,
177   float32_t * pOut,
178   float32_t * pErr,
179   uint32_t blockSize)
180 {
181   float32_t *pState = S->pState;                 /* State pointer */
182   float32_t *pCoeffs = S->pCoeffs;               /* Coefficient pointer */
183   float32_t *pStateCurnt;                        /* Points to the current sample of the state */
184   float32_t *px, *pb;                            /* Temporary pointers for state and coefficient buffers */
185   float32_t mu = S->mu;                          /* Adaptive factor */
186   uint32_t numTaps = S->numTaps;                 /* Number of filter coefficients in the filter */
187   uint32_t tapCnt, blkCnt;                       /* Loop counters */
188   float32_t energy;                              /* Energy of the input */
189   float32_t sum, e, d;                           /* accumulator, error, reference data sample */
190   float32_t w, x0, in;                           /* weight factor, temporary variable to hold input sample and state */
191
192   /* Initializations of error,  difference, Coefficient update */
193   e = 0.0f;
194   d = 0.0f;
195   w = 0.0f;
196
197   energy = S->energy;
198   x0 = S->x0;
199
200   /* S->pState points to buffer which contains previous frame (numTaps - 1) samples */
201   /* pStateCurnt points to the location where the new input data should be written */
202   pStateCurnt = &(S->pState[(numTaps - 1u)]);
203
204   /* Loop over blockSize number of values */
205   blkCnt = blockSize;
206
207
208 #ifndef ARM_MATH_CM0_FAMILY
209
210   /* Run the below code for Cortex-M4 and Cortex-M3 */
211
212   while(blkCnt > 0u)
213   {
214     /* Copy the new input sample into the state buffer */
215     *pStateCurnt++ = *pSrc;
216
217     /* Initialize pState pointer */
218     px = pState;
219
220     /* Initialize coeff pointer */
221     pb = (pCoeffs);
222
223     /* Read the sample from input buffer */
224     in = *pSrc++;
225
226     /* Update the energy calculation */
227     energy -= x0 * x0;
228     energy += in * in;
229
230     /* Set the accumulator to zero */
231     sum = 0.0f;
232
233     /* Loop unrolling.  Process 4 taps at a time. */
234     tapCnt = numTaps >> 2;
235
236     while(tapCnt > 0u)
237     {
238       /* Perform the multiply-accumulate */
239       sum += (*px++) * (*pb++);
240       sum += (*px++) * (*pb++);
241       sum += (*px++) * (*pb++);
242       sum += (*px++) * (*pb++);
243
244       /* Decrement the loop counter */
245       tapCnt--;
246     }
247
248     /* If the filter length is not a multiple of 4, compute the remaining filter taps */
249     tapCnt = numTaps % 0x4u;
250
251     while(tapCnt > 0u)
252     {
253       /* Perform the multiply-accumulate */
254       sum += (*px++) * (*pb++);
255
256       /* Decrement the loop counter */
257       tapCnt--;
258     }
259
260     /* The result in the accumulator, store in the destination buffer. */
261     *pOut++ = sum;
262
263     /* Compute and store error */
264     d = (float32_t) (*pRef++);
265     e = d - sum;
266     *pErr++ = e;
267
268     /* Calculation of Weighting factor for updating filter coefficients */
269     /* epsilon value 0.000000119209289f */
270     w = (e * mu) / (energy + 0.000000119209289f);
271
272     /* Initialize pState pointer */
273     px = pState;
274
275     /* Initialize coeff pointer */
276     pb = (pCoeffs);
277
278     /* Loop unrolling.  Process 4 taps at a time. */
279     tapCnt = numTaps >> 2;
280
281     /* Update filter coefficients */
282     while(tapCnt > 0u)
283     {
284       /* Perform the multiply-accumulate */
285       *pb += w * (*px++);
286       pb++;
287
288       *pb += w * (*px++);
289       pb++;
290
291       *pb += w * (*px++);
292       pb++;
293
294       *pb += w * (*px++);
295       pb++;
296
297
298       /* Decrement the loop counter */
299       tapCnt--;
300     }
301
302     /* If the filter length is not a multiple of 4, compute the remaining filter taps */
303     tapCnt = numTaps % 0x4u;
304
305     while(tapCnt > 0u)
306     {
307       /* Perform the multiply-accumulate */
308       *pb += w * (*px++);
309       pb++;
310
311       /* Decrement the loop counter */
312       tapCnt--;
313     }
314
315     x0 = *pState;
316
317     /* Advance state pointer by 1 for the next sample */
318     pState = pState + 1;
319
320     /* Decrement the loop counter */
321     blkCnt--;
322   }
323
324   S->energy = energy;
325   S->x0 = x0;
326
327   /* Processing is complete. Now copy the last numTaps - 1 samples to the    
328      satrt of the state buffer. This prepares the state buffer for the    
329      next function call. */
330
331   /* Points to the start of the pState buffer */
332   pStateCurnt = S->pState;
333
334   /* Loop unrolling for (numTaps - 1u)/4 samples copy */
335   tapCnt = (numTaps - 1u) >> 2u;
336
337   /* copy data */
338   while(tapCnt > 0u)
339   {
340     *pStateCurnt++ = *pState++;
341     *pStateCurnt++ = *pState++;
342     *pStateCurnt++ = *pState++;
343     *pStateCurnt++ = *pState++;
344
345     /* Decrement the loop counter */
346     tapCnt--;
347   }
348
349   /* Calculate remaining number of copies */
350   tapCnt = (numTaps - 1u) % 0x4u;
351
352   /* Copy the remaining q31_t data */
353   while(tapCnt > 0u)
354   {
355     *pStateCurnt++ = *pState++;
356
357     /* Decrement the loop counter */
358     tapCnt--;
359   }
360
361 #else
362
363   /* Run the below code for Cortex-M0 */
364
365   while(blkCnt > 0u)
366   {
367     /* Copy the new input sample into the state buffer */
368     *pStateCurnt++ = *pSrc;
369
370     /* Initialize pState pointer */
371     px = pState;
372
373     /* Initialize pCoeffs pointer */
374     pb = pCoeffs;
375
376     /* Read the sample from input buffer */
377     in = *pSrc++;
378
379     /* Update the energy calculation */
380     energy -= x0 * x0;
381     energy += in * in;
382
383     /* Set the accumulator to zero */
384     sum = 0.0f;
385
386     /* Loop over numTaps number of values */
387     tapCnt = numTaps;
388
389     while(tapCnt > 0u)
390     {
391       /* Perform the multiply-accumulate */
392       sum += (*px++) * (*pb++);
393
394       /* Decrement the loop counter */
395       tapCnt--;
396     }
397
398     /* The result in the accumulator is stored in the destination buffer. */
399     *pOut++ = sum;
400
401     /* Compute and store error */
402     d = (float32_t) (*pRef++);
403     e = d - sum;
404     *pErr++ = e;
405
406     /* Calculation of Weighting factor for updating filter coefficients */
407     /* epsilon value 0.000000119209289f */
408     w = (e * mu) / (energy + 0.000000119209289f);
409
410     /* Initialize pState pointer */
411     px = pState;
412
413     /* Initialize pCcoeffs pointer */
414     pb = pCoeffs;
415
416     /* Loop over numTaps number of values */
417     tapCnt = numTaps;
418
419     while(tapCnt > 0u)
420     {
421       /* Perform the multiply-accumulate */
422       *pb += w * (*px++);
423       pb++;
424
425       /* Decrement the loop counter */
426       tapCnt--;
427     }
428
429     x0 = *pState;
430
431     /* Advance state pointer by 1 for the next sample */
432     pState = pState + 1;
433
434     /* Decrement the loop counter */
435     blkCnt--;
436   }
437
438   S->energy = energy;
439   S->x0 = x0;
440
441   /* Processing is complete. Now copy the last numTaps - 1 samples to the        
442      satrt of the state buffer. This prepares the state buffer for the        
443      next function call. */
444
445   /* Points to the start of the pState buffer */
446   pStateCurnt = S->pState;
447
448   /* Copy (numTaps - 1u) samples  */
449   tapCnt = (numTaps - 1u);
450
451   /* Copy the remaining q31_t data */
452   while(tapCnt > 0u)
453   {
454     *pStateCurnt++ = *pState++;
455
456     /* Decrement the loop counter */
457     tapCnt--;
458   }
459
460 #endif /*   #ifndef ARM_MATH_CM0_FAMILY */
461
462 }
463
464 /**    
465    * @} end of LMS_NORM group    
466    */