Tuesday 14 November 2017

Moving Average Savitzky Golay


Suavizado El suavizado elimina las variaciones a corto plazo, o quotnoisequot para revelar la importante forma subyacente no adulterada de los datos. Igoracutes Funcionamiento liso realiza caja, quotbinomialquot, y Savitzky-Golay suavizado. Los diferentes algoritmos de suavizado convolucionan los datos de entrada con diferentes coeficientes. El suavizado es un tipo de filtro de paso bajo. El tipo de suavizado y la cantidad de suavizado altera la respuesta de frecuencia del filtro: Promedio móvil (también conocido como suavizado de caja) La forma más simple de suavizado es el promedio de quotmoving que simplemente sustituye cada valor de datos por el promedio de valores vecinos. Para evitar el desplazamiento de los datos, lo mejor es promediar el mismo número de valores antes y después de donde se calcula el promedio. En la forma de la ecuación, el promedio móvil se calcula por: Otro término para este tipo de suavizado es quotsliding averagequot, quotbox smoothingquot o quotboxcar smoothingquot. Se puede implementar convolucionando los datos de entrada con un pulso en forma de caja de valores 2M1 todos iguales a 1 / (2M1). Llamamos a estos valores el quotcoefficientsquot del kernel quotsmoothing: Binomial Smoothing El suavizado binomial es un filtro gaussiano. Convoluciona sus datos con coeficientes normalizados derivados del triángulo Pascalacutes a un nivel igual al parámetro Smoothing. El algoritmo se deriva de un artículo de Marchand y Marmet (1983). Savitzky-Golay Smoothing El suavizado Savitzky-Golay utiliza un conjunto diferente de coeficientes precomputados populares en el campo de la química. Es un tipo de suavizado de polinomios de mínimos cuadrados. La cantidad de suavizado se controla mediante dos parámetros: el orden polinómico y el número de puntos utilizados para calcular cada valor de salida suavizado. Referencias Marchand, P. y L. Marmet, Filtro binomial de alisado: Una manera de evitar algunos escollos de alisamiento polinomial de mínimos cuadrados, Rev. Sci. Instrum. . 54. 1034 - 41, 1983. Savitzky, A. y M. J.E. Golay, Suavizado y diferenciación de datos mediante procedimientos simplificados de mínimos cuadrados, Química Analítica. 36. 1. Introducción El sistema de seguimiento esquelético (ST) de la interfaz de usuario natural (NUI) proporciona posiciones conjuntas de Esqueletos de personas rastreadas. Estas posiciones conjuntas son los datos que se consumen como posición y postura, y se utilizan para muchos propósitos, como detección de gestos, navegación de interfaces de usuario, etc. En la práctica, hay algo de ruido presente en las posiciones conjuntas devueltas por el sistema ST. Un paso importante antes de consumir datos ST es utilizar un filtro de reducción de ruido para eliminar tanto ruido como sea posible de los datos conjuntos. Estos filtros se llaman filtros de suavizado porque dan lugar a posiciones más suaves a lo largo del tiempo. Este documento describe las técnicas de filtrado y las mejores prácticas para el uso de datos conjuntos de skeleton para una aplicación habilitada con Kinect, y su objetivo es ayudar a los desarrolladores a elegir una técnica de filtrado adecuada y ajustar los parámetros del filtro para que coincidan con sus necesidades de aplicación. El papel abarca diferentes áreas relacionadas con el filtrado de las articulaciones, como el tipo de ruido que uno debería esperar en los datos ST como el filtrado afecta a la latencia y cómo se puede utilizar la previsión para reducir la latencia las características de un filtro de articulación ideal en términos de capacidad de respuesta, Y efecto de suavizado y cómo los datos de estado de seguimiento devueltos por ST se pueden utilizar para mejorar el filtrado. A continuación, se describen las características específicas de algunas técnicas de filtrado útiles en detalle. El documento concluye con un resumen de las mejores prácticas y consejos prácticos para el filtrado. 2. Por qué necesitamos un filtro conjunto Los errores de medición y el ruido son subproductos de casi cualquier sistema que mide una cantidad física a través de un sensor. Las características de este error se describen generalmente por la exactitud y precisión del sistema, donde la precisión se define como el grado de proximidad de la cantidad medida a su valor real, y la precisión se define como el grado en el que las mediciones repetidas están cercanas entre sí. Un sistema preciso no tiene ningún error sistemático en las mediciones y por lo tanto no añade un sesgo sistemático. Un sistema preciso resulta en mediciones cercanas entre sí cuando se repite la medición 1, 4. Los conceptos de precisión y precisión se ilustran en la Tabla 1 para un sistema que mide una posición de mano en el mundo real. Tabla 1. Precisión vs. Precisión: La X negra representa la posición de la mano en el mundo real, y los puntos rojos representan unas pocas mediciones de la posición de la mano por un sistema de medición. (A) Un sistema impreciso e inexacto genera mediciones al azar que son esencialmente inútiles en la práctica. (B) Un sistema de medición inexacto pero preciso genera mediciones cercanas entre sí, pero tiene un error o sesgo sistemático. (C) Un sistema preciso y preciso genera mediciones idénticas que están cerca de datos en el mundo real. Desafortunadamente, 100 sistemas exactos y precisos no existen en el mundo real, porque siempre habrá algún error en la práctica. (D) Un sistema preciso y modestamente preciso genera mediciones cercanas entre sí y no son sistemáticamente sesgadas con respecto a los datos en el mundo real. Esto es lo que uno debería esperar en un sistema bien diseñado en la práctica. Al igual que cualquier sistema de medición, los datos de posiciones conjuntas devueltos por el sistema NUI ST tienen cierto ruido. Hay muchos parámetros que afectan las características y el nivel de ruido, que incluyen la iluminación de la sala de un cuerpo de personas la distancia de las personas de la matriz de sensores que las personas poseen (por ejemplo, para los datos de mano, si la mano de las personas está abierta o fisted) Los efectos de redondeo del ruido de cuantificación del conjunto de sensores introducidos por los cálculos y así sucesivamente. Tenga en cuenta que las posiciones conjuntas devueltas por ST son precisas. Lo que significa que no hay sesgo en los datos de posición conjunta a las posiciones reales en el mundo real. Esto significa que si una persona se queda quieta, entonces el promedio de los datos de las posiciones conjuntas, con el tiempo, es cercano a las posiciones en el mundo real. Sin embargo, los datos de posiciones conjuntas no son necesariamente perfectamente precisos, lo que significa que están dispersos alrededor de las posiciones correctas en cada marco. En la práctica, las posiciones de las articulaciones son exactas dentro de un rango de centímetro, no milímetros. Hay casos en los que el sistema ST no tiene suficiente información en un marco capturado para determinar una posición de articulación específica. Ejemplos de estos casos incluyen la oclusión de muebles u otras personas, la auto-oclusión de una articulación por otras partes del cuerpo de la persona, y mover una articulación fuera del campo de visión de los sensores. En la mayoría de estos casos, el sistema ST todavía es capaz de inferir la posición de la articulación, y el parámetro NUISKELETONPOSITIONTRACKINGSTATE, devuelto como parte de una estructura NUISKELETONDATA, se establece en NUISKELETONPOSITIONINFERRED para esa unión. Este parámetro puede ser tratado como el nivel de confianza del sistema ST con respecto a la posición de la articulación. Aunque las posiciones conjuntas deducidas son una estimación muy refinada de la posición conjunta, pueden llegar a ser inexactas en algunos casos, dependiendo de la pose de una persona. Por lo tanto, se debe esperar que las articulaciones inferidas tengan valores de ruido más altos, junto con la posibilidad de un sesgo. Este sesgo se observa generalmente como picos temporales en los datos de la posición de la articulación, que desaparecen a medida que el nivel del estado de seguimiento conjunto vuelve a NUISKELETONPOSITIONTRACKED. Por lo tanto, dos tipos de ruido están presentes en posiciones conjuntas. Una es el ruido blanco relativamente pequeño que siempre está presente para todas las articulaciones y causado por la imprecisión y el otro es los picos temporales causados ​​por la inexactitud, que ocurre cuando la articulación tiene un estado de seguimiento inferido. Dado que estos ruidos tienen características diferentes, se deben utilizar diferentes técnicas de filtrado para cada uno. Es decir, los desarrolladores necesitan usar una combinación de dos o tres técnicas de filtrado para lograr buenos resultados en una aplicación habilitada para Kinect. 3. Bases de Filtros Conjuntos Antes de describir cualquier técnica de filtrado específica, hay algunos conceptos importantes que cubrir que están relacionados con el filtrado que incluyen la latencia y cómo se relaciona con los retrasos de filtrado, cómo la predicción puede mejorar la latencia, la compensación entre la latencia y los efectos de suavizado en Filtro de diseño, y lo que hace un filtro ideal. 3.1. La latencia y cómo se relaciona con el filtrado La latencia se puede definir como el tiempo que toma de cuando una persona hace un movimiento, hasta el momento en que la persona ve la respuesta a su movimiento del cuerpo en la pantalla. La latencia degrada la experiencia tan pronto como la gente empieza a notar que hay un retraso en la respuesta a sus movimientos. La investigación del usuario muestra que 72 de las personas empiezan a notar este retraso cuando la latencia es superior a 100 ms, por lo que se sugiere que los desarrolladores busquen una latencia total de 100 ms 15. Para una discusión detallada sobre latencia, consulte 14 en Referencias. La latencia de filtrado conjunto es el tiempo que tarda la salida del filtro en alcanzar la posición real de la articulación cuando hay un movimiento en una articulación. Esto se muestra en la Figura 1, que muestra que la salida del filtro se queda atrás de la entrada cuando hay cambios en la entrada. Es importante señalar que la latencia introducida por el filtrado conjunto no es el tiempo de CPU que se tarda en ejecutar la rutina de filtrado. Figura 1. Salida de un típico filtro de articulación en respuesta a un movimiento articular NUI. Obsérvese que la latencia añadida por el filtrado de las juntas es el retraso entre la salida y la entrada cuando hay movimiento en los datos de entrada, y la cantidad depende de la rapidez con la que la articulación se mueve. En general, el retardo de filtrado depende de la rapidez con que la entrada está cambiando y, por lo tanto, no se puede atribuir un valor de retardo específico a un filtro dado para todos los casos. Esto se denomina distorsión de fase en el procesamiento de señales 6, 7. Una clase especial de filtros llamados filtros de fase lineal tienen el mismo retardo para todas las frecuencias de entrada, y tal tiempo de retardo específico puede atribuirse al filtro para todas las entradas. Reducir la distorsión de fase es importante en algunas aplicaciones de procesamiento de señales, específicamente en el procesamiento de audio, sin embargo, no es necesariamente tan importante en el filtrado de juntas NUI, por lo que tener un filtro de fase lineal no es un criterio de diseño en el filtrado de juntas NUI. Una técnica útil para reducir la latencia es ajustar el filtro de articulación para predecir las futuras posiciones de las articulaciones. Es decir, la salida del filtro sería una estimación suavizada de la posición de la articulación en las tramas siguientes. Si se utiliza la predicción, entonces el filtrado conjunto reduciría la latencia total. Sin embargo, dado que los resultados previstos se estiman a partir de datos anteriores, los datos pronosticados pueden no ser siempre precisos, especialmente cuando un movimiento se inicia o se detiene repentinamente. La predicción puede propagar y ampliar el ruido en datos anteriores a datos futuros, y por lo tanto, puede aumentar el ruido. Casi todas las técnicas de filtrado conjunto pueden pronosticar o pueden modificarse para predecir los resultados futuros. La precisión de las salidas predichas depende del modelo de datos subyacente que el filtro está utilizando y de cómo se seleccionan los parámetros del filtro. Obsérvese que generalmente es práctico pronosticar una posición conjunta para aproximadamente dos tramas, lo que podría reducir la latencia de filtrado en unos 66 mseg en casos ideales. Sin embargo, en la práctica, el efecto de suavizado del filtro, junto con los errores de predicción en los datos previstos, daría lugar a reducciones de latencia más pequeñas. 3.2. Efecto de suavizado del filtro frente a retraso de filtración Un filtro de junta ideal eliminaría todo el ruido y nervios no deseados de los datos de la junta, dando como resultado datos de posición de la junta lisos a lo largo del tiempo. También seguiría los movimientos de la articulación sin ningún retardo o retraso. Desafortunadamente, existe un equilibrio entre estos dos objetivos en la práctica, y elegir una técnica de filtrado que suavice agresivamente los datos resultaría en un mayor retardo de filtrado, lo que aumentaría la latencia percibida. Como una explicación intuitiva para este concepto, considere un caso en el que una persona está parada y por lo tanto la entrada al filtro de la articulación es sobre todo una posición constante junto con algo de ruido. Con el fin de producir una salida suave, el filtro no debe ser sensible a los cambios en la entrada debido al ruido. Ahora suponga que la persona comienza a mover su mano. Con el fin de responder a estos movimientos, el filtro debe ser diseñado para ser sensible a los cambios debidos al movimiento, lo que es un opuesto a la necesidad de eliminación de ruido. En la práctica, la mayoría de los filtros tardan algún tiempo en ver suficiente movimiento antes de comenzar a seguir estos cambios en la salida y, por lo tanto, su salida se queda atrás de los cambios en la entrada. En consecuencia, se debe entender cómo la latencia y suavidad afectan a la experiencia del usuario, e identificar cuál es más importante para crear una buena experiencia. Luego, elija cuidadosamente un método de filtrado y ajuste sus parámetros para que coincidan con las necesidades específicas de la aplicación. En la mayoría de las aplicaciones de Kinect, la salida de datos del sistema ST se utiliza para una variedad de propósitos tales como detección de gestos, retargeting de avatar, interacción con elementos de interfaz de usuario y objetos virtuales y así sucesivamente, donde todos son diferentes en términos de lisura y latencia. Del mismo modo, las articulaciones tienen características diferentes entre sí en términos de la rapidez con que se pueden mover, o cómo se utilizan para crear la experiencia global. Por ejemplo, en algunas aplicaciones, las manos de una persona pueden moverse mucho más rápido que la articulación de la columna y, por lo tanto, es necesario utilizar diferentes técnicas de filtrado para las manos que la columna vertebral y otras articulaciones. Alternativamente, considere una aplicación que utiliza movimientos de las manos para anotar qué tan bien está haciendo una persona un ejercicio en particular (es decir, para marcar gestos) y para animar al avatar de personas en la pantalla al mismo tiempo. La latencia suele ser menos importante en la puntuación de los gestos, ya que todo el gesto debe hacerse antes de calcular la puntuación en consecuencia, la aplicación debe utilizar una técnica de filtrado de alta latencia con suavizado más agresivo para el gesto de puntuación, al tiempo que utiliza una diferente baja latencia técnica de filtrado Para animar un avatar de personas. Por lo tanto, no hay solución de filtrado que se ajuste a las necesidades de todos los casos de uso de todas las articulaciones. Dependiendo de qué datos conjuntos se van a utilizar y cómo se consume la salida del filtro, se deben aplicar diferentes técnicas de filtrado o afinar los parámetros por junta y por aplicación. 3.3. Propagación de errores a variables calculadas a partir de datos de seguimiento de esqueletos Se pueden aplicar las técnicas de filtrado discutidas en este documento a las variables calculadas a partir de posiciones conjuntas. Por ejemplo, una aplicación puede necesitar usar el ángulo de codo formado entre la mano de las personas, el codo y el hombro. A continuación, las mismas técnicas de filtrado discutidas aquí se pueden aplicar al ángulo calculado para suavizarlo a lo largo del tiempo. Otro ejemplo es el uso de sistemas de coordenadas esféricas locales para los padres de las articulaciones, donde cada punto en el espacio está representado por un triplete (,,), en lugar de un sistema cartesiano de coordenadas (x, y, z). Por ejemplo, se puede usar el hombro derecho como origen y representar la posición del codo usando este sistema de coordenadas esféricas locales. En este caso, las coordenadas cartesianas devueltas por ST se transforman en coordenadas esféricas locales (,,), y el filtrado se realiza en cada componente por separado. El radio. Que representa la longitud del hueso, se puede filtrar más agresivamente que los ángulos (,), que representan los movimientos de la articulación. Es importante notar que la aplicación de operaciones matemáticas a datos ruidosos conjunta propagar el ruido y puede amplificar el nivel de ruido. El concepto subyacente de propagación del ruido es similar en esencia a la propagación de los errores de redondeo o precisión de las variables de punto flotante en las operaciones matemáticas, aunque los errores de redondeo en los valores de punto flotante son pequeños y se ignoran en la mayoría de los casos prácticos, Mayor Las operaciones para calcular el tamaño de las partes del cuerpo, como suma, resta y multiplicación, amplifican el ruido 1-4. Por ejemplo, calcular la longitud del hueso o calcular las coordenadas relativas de la articulación, como la posición del codo en relación con el hombro o la posición de la mano con relación a la cabeza, todos requieren restar dos posiciones de la articulación. En todos estos casos, el ruido en los datos resultantes se amplifica. Las funciones trigonométricas (como el seno, el coseno o la tangente inversa), que se utilizan típicamente para calcular o manipular ángulos de articulación, afectan al ruido de diferentes maneras. El efecto de cualquier función sobre el ruido depende de la pendiente local de esa función, es decir, la derivada local de la función alrededor del punto de datos utilizado. Por ejemplo, supongamos que es un ángulo de articulación calculado a partir de datos ST ruidosos, y por lo tanto es ruidoso también. Ahora considere la función tan. Que es sensible alrededor de 90 o. Porque (d / d) tan converge a alrededor de 90 o. Por lo tanto, el cálculo de la función bronceado amplificaría el ruido drásticamente si es cercano a 90 o. Sin embargo, dado que (d / d) tan 1 alrededor de 0 o. Entonces el ruido no se amplifica ni disminuye si es cercano a cero. Una discusión más detallada de este tema se puede encontrar en Referencias bajo Análisis de errores y propagación de errores en datos ruidosos, ver 1-4 para más detalles. 3.4. Notación de filtro La aplicación de filtro de junta en una aplicación típica recibe posiciones de articulación de ST como entrada en cada trama, y ​​devuelve las posiciones de unión filtradas como salida. El filtro trata cada una de las articulaciones x. Y. Y z independientemente de otras articulaciones u otras dimensiones. Es decir, un filtro se aplica independientemente a la x. Y. Y la coordenada z de cada junta separadamente y potencialmente cada uno con diferentes parámetros de filtrado. Obsérvese que, aunque es típico filtrar directamente los datos de posición cartesiana devueltos por ST, se pueden aplicar las mismas técnicas de filtrado a cualquier dato calculado a partir de posiciones conjuntas. Esto significa que la entrada de cada filtro de unión es una serie temporal unidimensional que representa una posición de junta única en una dimensión dada en el marco n (por ejemplo, coordenadas y de la posición de la mano derecha). La entrada de filtro en la trama n está denotada por X n y la salida de filtro generada por la aplicación del filtro por n. Figura 2. Nota de filtro utilizada en este documento técnico 3.5. Respuesta del filtro a las entradas de la forma escalonada y de la forma de onda Sinus Para comprender una técnica de filtrado y cómo los parámetros de filtrado afectan las características del filtro, es útil estudiar la salida del filtro en respuesta a algunas entradas predefinidas. La entrada de función de paso modela un salto repentino en los datos de entrada y se define como: Es decir, la entrada X n es cero hasta un tiempo dado y luego salta y permanece en 1 en el instante N. Aunque uno no espera ver tal entrada en la práctica, una función de paso es útil porque muestra la rapidez y la precisión con que el filtro controla cambios repentinos en la entrada. La Figura 4 muestra la salida típica de un filtro a una entrada de función escalonada, así como definiciones para algunas de las características de filtro de nuestro interés. Figura 3. Respuesta típica de una entrada de función de filtro a paso El tiempo de subida es el tiempo requerido para que la salida del filtro alcance 90 del valor final asintótico, que es 0,90 en el caso de una entrada de función de escalón unitario. En algunos campos, se utiliza un parámetro similar llamado constante de tiempo, que es el tiempo requerido para que la salida del filtro alcance (1e 1) 63 de su valor asintótico final. Un pequeño tiempo de subida es una indicación de un filtro con baja latencia. Overshoot es cuando la salida del filtro alcanza un valor máximo más alto que la entrada, y esto generalmente se representa como un porcentaje del valor asintótico final. Tenga en cuenta que no todos los filtros tienen exceso en su salida. El rebasamiento es indeseable, y generalmente está presente en filtros de baja latencia que son sensibles a cambios en la entrada. El timbre es el efecto donde la salida del filtro oscila antes de que se establezca hasta su valor final. El tiempo de estabilización es aplicable a los filtros que tienen sobrepaso o timbrado, y es el tiempo que tarda la salida del filtro en alcanzar y permanecer dentro de un margen de error dado de su valor asintótico final. El rango del margen de error es usualmente 10 por ciento. El tiempo de subida muestra la rapidez con que el filtro detecta cambios repentinos en la entrada, mientras que el exceso, el timbre y el tiempo de estabilización son indicaciones de lo bien que un filtro puede asentarse después de haber respondido a un cambio repentino en la entrada. Una respuesta de filtros a una función escalonada no revela todas las características útiles de una técnica de filtrado, porque sólo muestra la respuesta de los filtros a cambios repentinos. También es útil estudiar una respuesta de los filtros a la entrada de la forma de onda senoidal, tanto en los dominios de tiempo como de frecuencia. Como se muestra en la Figura 4, la respuesta en el dominio del tiempo puede mostrar el retraso en la salida del filtro, que depende de la frecuencia de entrada en la mayoría de los casos (es decir, en filtros de fase no lineales). Tenga en cuenta que la salida puede no alcanzar el nivel máximo o mínimo de la entrada debido a que el filtro atenúa esa frecuencia. Esto a veces se conoce como amortiguamiento de los picos y valles en la entrada por suavizado agresivo. A modo de ejemplo, la Figura 5 muestra la posición de la mano x de una persona que ha abierto y cerrado su brazo rápidamente dos veces, dando como resultado un pico sinusoidal en la entrada. Como se ha indicado, el suavizado agresivo de los datos ha dado como resultado que la salida del filtro no alcance el mismo nivel máximo y mínimo de la entrada. Además, es interesante observar en las figuras 4 y 5 que, en algunos cuadros, la entrada está aumentando mientras la salida está disminuyendo, esto se puede atribuir a la latencia de filtrado. Este filtro no sería una buena opción para dibujar un cursor en la pantalla basado en la posición actual de la mano de las personas, ya que produciría un efecto indeseable cuando la mano de las personas cambia de dirección, el cursor se pondría al día y cambiaría de dirección después de un tiempo Crear una experiencia incómoda para la persona. Figura 4. Respuesta típica de un filtro a la entrada de forma de onda sinusoidal Figura 5. El suavizado agresivo reduciría el mínimo y el máximo en los datos de entrada sinusoidales. Los datos son del movimiento real de la mano donde una persona ha abierto y cerrado sus brazos rápidamente dos veces. La respuesta de los filtros en el dominio de la frecuencia muestra cómo un filtro responde a todos los rangos de entradas de frecuencia. Todos los filtros de suavizado utilizados para el filtrado de juntas NUI son filtros de paso bajo, en los que un filtro de paso bajo ideal deja pasar los componentes de frecuencia de entrada que son inferiores a una frecuencia de corte, pero elimina los componentes de frecuencia que son más altos que la frecuencia de corte . Las características de paso bajo de los filtros de articulación NUI se basan en la suposición de que los movimientos de las articulaciones tienen una frecuencia relativamente más baja que el ruido, aunque esto no es necesariamente una suposición correcta para todos los casesspecifically, cuando una persona hace movimientos rápidos, Saltos bruscos Tenga en cuenta que existen métodos poderosos de diseño de filtros disponibles en los libros de texto de procesamiento de señales que realizan una respuesta de frecuencia deseada, tal como un filtro de paso bajo de orden dado N y con una frecuencia de corte 6 dada. Debido a que el rango de frecuencias de los datos de la unión NUI se superpone con el ruido, los filtros de paso bajo con un diseño basado únicamente en los criterios de respuesta de frecuencia no proporcionan necesariamente buenos resultados en las aplicaciones de Kinect. Los métodos de diseño de filtros de dominio de frecuencia no están dentro del alcance de este documento. Sin embargo, puede familiarizarse con los conceptos subyacentes utilizados en el diseño de filtros en el dominio de la frecuencia para comprender mejor las características de filtrado en general y los puntos 6 y 7 en Referencias son buenos puntos de partida. 3,6. Uso del estado de seguimiento conjunto en el filtrado Las articulaciones inferidas son más propensas a tener ruidos temporales debido a que son menos precisas. Además, los niveles de ruido aleatorios suelen ser más altos para las articulaciones inferidas. En la práctica, para las aplicaciones de Kinect, los desarrolladores deberían considerar un estado de seguimiento de las juntas como una valiosa información sobre la calidad de los datos de la articulación y aplicar un filtro de suavizado más agresivo cuando se deduce un estado de las articulaciones. Esto se puede hacer fácilmente comprobando el estado de seguimiento de las juntas en la implementación de los filtros y actualizando de forma adaptativa los parámetros del filtro basados ​​en el estado de seguimiento de las juntas. Además, los filtros que son específicamente más potentes en la eliminación de ruido de picos deben aplicarse cuando se deduce un estado de articulaciones. 3.7. Uso de la cinemática del cuerpo para corregir los datos de salida del filtro La anatomía y la cinemática de una persona proporcionan información valiosa que se puede utilizar para mejorar los datos de la articulación ST. Por ejemplo, algunas articulaciones se mueven o se doblan sólo en una dirección determinada, o algunas articulaciones, como las manos, pueden moverse más rápido que otras articulaciones. La forma en que estos datos pueden aplicarse depende de la articulación y de los contextos en los que se utilizan los datos conjuntos. Como un ejemplo práctico, supongamos que una junta de mano derecha de personas es filtrada con un filtro de baja latencia que pronostica una trama en el futuro. Este tipo de filtro por lo general resulta en overshoots en respuesta a los movimientos repentinos. Por lo tanto, debido al rebasamiento, el filtro puede calcular la posición de la mano para estar demasiado lejos del cuerpo de las personas. Este rebasamiento puede ser corregido usando una estimación de la longitud del hueso de la mano y corrigiendo la posición de la mano filtrada de modo que la mano se posicione a una distancia aceptable del cuerpo de la persona. Otra propiedad cinemática útil es las limitaciones de la articulación articular. Una articulación de bisagra es una articulación que puede doblarse a lo largo de un solo eje (es decir, tiene sólo un grado de libertad). Por ejemplo, los codos y las rodillas son articulaciones de bisagra, porque pueden doblarse en una sola dirección y dentro de un rango limitado. Estas limitaciones cinemáticas del codo o de la rodilla se pueden utilizar para corregir las posiciones de la articulación filtrada. 4. Filtros de Suavizado Esta sección discute detalles de algunas técnicas de filtrado de suavizado que son útiles para filtros de juntas NUI. Primero son los filtros de Auto Regressive Moving Average (ARMA), que son una clase general de filtros. También se cubren los filtros de suavizado específicos para la eliminación de ruido, incluyendo Promedio móvil, Promedio móvil doble, Filtro exponencial, Filtro exponencial doble y Filtros Savitzky-Golay. Todos estos filtros de suavizado son casos especiales de filtros ARMA. Finalmente, la sección discute un filtro basado en la serie de Taylor que es útil para la previsión. También están cubiertos los filtros Median y Jitter Removal, que aunque tienen algún efecto suavizante, son específicamente útiles para eliminar el ruido de picos de los datos. 4.1. Filtros de media móvil regresiva regresiva (ARMA) Los filtros de promedio móvil regresivo regresivo (ARMA) son una clase general de filtros lineales. Todos los filtros de suavizado que discutimos en este documento son un caso especial de filtros ARMA. La salida de un filtro ARMA es un promedio ponderado de la corriente y N entradas anteriores, y M salidas del filtro anterior: Donde los coeficientes a i y b i son los parámetros de filtrado. El primer término se conoce como término de media móvil (MA), y el segundo término se conoce como término auto-regresivo (AR). Los filtros de media móvil (MA) son un caso especial de filtros ARMA donde todos los parámetros b i son cero: Los coeficientes a i son los factores de peso y se seleccionan de tal manera que un i 1 en todas las aplicaciones de filtro de juntas NUI. Esta propiedad es el resultado del uso de filtros de paso bajo y permite que los componentes de CC pasen sin atenuación. Como explicación intuitiva, supongamos que la entrada a filtrar es la constante 1 para todos los fotogramas n. Entonces, uno intuitivamente espera que la salida del filtro sea igual a 1 para todos los n. Lo que daría lugar a un i 1. Esto se puede utilizar como una verificación de sanidad rápida que los coeficientes a i derivados son correctos. El filtro de media móvil se puede extender a un filtro de media móvil central, donde la salida del filtro es el promedio ponderado de N pasado y M entradas futuras: Dado que la salida de este filtro depende de M entradas futuras después de X n. Entonces cualquier implementación de este filtro agregará una latencia de al menos M frames. Por lo tanto, este filtro sólo es práctico en casos sin conexión en los que todos los datos están disponibles de antemano, o en casos en los que el aumento de la latencia por un orden de unos pocos marcos es tolerable. Por ejemplo, en algunas aplicaciones habilitadas para Kinect, puede tener sentido anotar qué tan bien la persona ha hecho un ejercicio después de que todo el rendimiento haya terminado. Los filtros MA centrales suelen funcionar mejor en términos de eliminación de ruido que los simples filtros MA. Los filtros ARMA suelen diseñarse asumiendo un modelo de datos subyacente para los datos y utilizando este modelo para calcular los pedidos de filtro N y M. Y los coeficientes a i y b i. El modelo de datos debe elegirse en función de las características reales de los datos. En algunos enfoques los modelos de datos subyacentes se eligen sobre la base de un enfoque estadístico que preservaría los momentos de mayor orden de los datos. Los detalles de estos métodos están fuera del alcance de este documento ver 5 para una discusión detallada. En este trabajo se menciona el orden de los momentos estadísticos hasta los cuales los datos de entrada son preservados por el filtro. En general, los filtros que preservan los momentos de mayor orden tienen un mejor desempeño. 4.2. Filtro de promedio simple El filtro de promedio simple es el filtro de articulación más simple, donde la salida del filtro es el promedio de N entradas recientes, que es un filtro MA de orden N con ai 1 / (N 1) para todo i: , El filtro de promediación es un filtro ingenuo que se ajusta a una línea horizontal (es decir, una constante) a N entradas recientes y lo utiliza como salida del filtro. Por lo tanto, un filtro de promediado no está aprovechando las características de datos conjuntos o la distribución estadística de ruido, y sólo preserva el momento de primer orden de los datos, que es el promedio. Un simple filtro de promedio no proporciona resultados satisfactorios en la mayoría de los casos de filtrado de juntas NUI. Un filtro de promedio utilizando un N grande daría lugar a más suavizado que un N más pequeño. Pero introduciría más retardo de filtrado. El retardo de filtrado puede observarse en la salida de un filtro de promediado en respuesta a las entradas de las funciones escalonadas y las formas de onda sinusoidales. Donde el retardo de filtrado es directamente proporcional a N. --gtPor ejemplo, el tiempo de subida de la función de escalón para N 5 y N 10 es de aproximadamente 4,5 fotogramas (148 ms) y 9 fotogramas (297 ms), respectivamente. El promedio simple es un filtro de fase lineal, lo que significa que todas las componentes de frecuencia en la entrada se retrasan en la misma cantidad [6]. Para experimentar esto, pruebe diferentes frecuencias para la entrada sinusoidal en la hoja de cálculo y observe que el retardo de salida es el mismo para todos los filtros. El efecto de suavizado del filtro se puede notar más fácilmente cuando se agrega ruido a la función de paso o entradas sinusoidales. Observe también que la salida del filtro de promedio no puede alcanzar los picos y valles de la mayoría de las entradas de forma de onda sinusoidales. Dado que un filtro de promedio se ajusta a una línea horizontal de datos, también pronostica las salidas futuras como una constante, que es el promedio de las últimas N entradas hasta el tiempo n: El filtro de promediado simple funciona bien en términos de pronóstico sólo si los datos de entrada Es estacionario y no hay tendencia en los datos. En el filtrado de juntas NUI, los datos de entrada estacionarios significan que una articulación tiene poco movimiento. Si hay movimiento en la articulación, entonces los datos de entrada de los filtros tendrán una pendiente, y por lo tanto, el promedio de los filtros tiene un desempeño pobre, especialmente en términos de previsión. Para datos de unión NUI con movimiento a velocidad constante, se puede demostrar que el filtro de promediado tiene un sesgo constante en su salida 8, 9. Un método para eliminar este error es usar un método de filtrado llamado media móvil doble. Que se analiza en la siguiente sección. 4.3. Filtro de promedio de movilidad doble Las medias móviles dobles se utilizan en muchas aplicaciones, como la previsión del mercado de valores, y son útiles cuando los datos tienen una tendencia lineal. La tendencia en los datos de la unión NUI es equivalente a un movimiento de la articulación a una velocidad constante. El modelo de datos subyacente utilizado por el filtro de promediado doble es ajustar una línea lineal a los datos de entrada locales y, por lo tanto, es más adaptable para seguir los cambios en los datos de entrada que el filtro de promedio simple 8, 9. Sea y sea las medias móviles de primer y segundo orden de los datos de entrada en el tiempo n: Por lo tanto, es una media móvil de una media móvil de datos de entrada (de ahí el nombre de media móvil doble). Si asumimos que los datos subyacentes siguen un modelo lineal, puede demostrarse que se retrasa sistemáticamente detrás de los datos reales, y también se puede demostrar que una segunda media móvil se desplaza al promedio aproximadamente en la misma cantidad. Para tener en cuenta el rezago sistemático, la diferencia de promedios de segundo y primer orden () se agrega a la salida del filtro. A continuación, el filtro de salida se da como el primer orden de media móvil más el término de ajuste de tendencia: Un enfoque similar se utiliza para ajustar las tendencias en la predicción, y los datos futuros se estiman como: El filtro de doble movimiento promedio tiene la ventaja de ser más sensible a los cambios En datos de entrada en comparación con un filtro de promediado móvil. Tenga en cuenta que para una ventana determinada N. Las ecuaciones de filtrado pueden combinarse y la ecuación de salida del filtro puede ser reescrita en términos de una media móvil ponderada de insumos pasados, lo que resultaría en una implementación más fácil. For example, for N 2, the second moving average and filter output are given by: which would result in: It is interesting to note that this filter uses larger weights for recent inputs, which is generally true for any filtering window N . 4.4. SavitzkyGolay Smoothing Filter A Savitzky-Golay smoothing filter (also known as a smoothing polynomial filter or a least squares smoothing filter ) fits a polynomial to neighbor input data for each input X n in a least-square sense and uses the value of the polynomial at time n as the filter output. A polynomial of order K is defined as: If we use N previous and M future samples as the neighbor samples, then a Savitzky-Golay filter finds c i coefficients such that minimize the term: and uses the polynomial value at time n as the filter outputthat is, n f K ( n ). Though it may first seem that this filter results in a complicated implementation, it turns out to be easy. It has been shown that the output of a Savitzky-Golay filter can be expressed as a weighted moving average filter that is: where the filtering coefficients a i are all constant for all X n values and do not change for different n . or even different inputs. Thus, to implement a Savitzky-Golay filter requires only choosing the appropriate filter order K . and determining how many samples before and after should be used (that is, choose N and M ). Then, the coefficients a i can be calculated offline by using available off-the-shelf algorithms, and filter output is easily calculated using these coefficients 11 ,12 . Savitzky-Golay filters are optimal in two different senses firstly, they minimize the least-squares error in fitting a polynomial to each windowed frame of input data, and secondly, in preserving the K first statistical moments of the input signal. In general, Savitzky-Golay filters are useful for cases in which the frequency span of input data without noise is large, and therefore, Savitzky-Golay filters are good candidates for NUI joint filtering. A Savitzky-Golay filter of order K preserves the first K 1 moments of the data 11 . For K 0, the Savitzky-Golay filter fits f K ( x ) c 0. or a constant value, to neighbors of each input, which would turn to a simple averaging filter with equal weight coefficients a i . For K 1, a straight line is fitted to local input data, which is usually referred to as linear regression in statistics text books. For K 2 and K 3, a parabola and a cubic curve are fitted, respectively. The choice of n affects the filter smoothing effect, where a cubic curve using K 3 seems to be a good choice for NUI joint filtering, since it is the lowest-degree polynomial that supports inflection and is still smooth. Using a higher-order polynomial yields jumpy curves with too many local minima and maxima, which would result in a lessened smoothing effect. The Savitzky-Golay filter can also be used for estimating the derivatives of input 11 , which is easily calculated from the coefficients c i . Thus, a Savitzky-Golay filter can produce the joint speed and acceleration along the smoothed position for NUI joint data. 4.5. Exponential Smoothing Filter An exponential smoothing filter, also known as an exponentially weighted moving average (EWMA), is a popular filter in many different fields. The exponential filter output is given by: Where is called the dampening factor and 01. By substituting ( n 1) this can be expanded to obtain: Therefore, filter output at time n is a weighted average of all past inputs, where weights a i (1) i decrease exponentially with time (more precisely, with geometric progression, which is the discrete version of an exponential function). Also, all previous inputs contribute to the smoothed filter output, but their contribution is dampened by increasing power of parameter 1. Since n depends on all past inputs, an exponential filter is said to have an infinite memory of all past inputs. Similar to a simple averaging filter, the exponential filter fits a straight horizontal line to the input data. The difference is that an exponential filter places relatively more weight on recent input data, and is correspondingly more responsive to recent changes in input than a simple averaging filter. The dampening factor affects the filtering delay and smoothing effect. A larger corresponds to larger weight on recent inputs, and results in faster dampening of older inputs. This results in less latency and less smoothing of the data. A small gives larger weight to older input samples, and hence, the effect of older inputs is larger. This results in a more aggressive smoothing effect and more latency, as shown in Figure 6. Figure 6. Effect of on filtering delay of an exponential smoothing filter Since an exponential filter fits a horizontal line to data, it forecasts the future data as a constant value similar to an averaging filter: A variant of exponential filter, called a double exponential filter, addresses this limitation of exponential filters and is described in the next section. One can incorporate state data for a joint into the implementation of an exponential filter by adaptively using a smaller for joints for which tracking state indicates inferred positions. This results in more aggressive filtering of inferred joints. 4.6. Double Exponential Smoothing Filter The double exponential smoothing filter is a popular smoothing filter used in many applications. Similar to a double moving averaging filter, the double exponential smoothing filter smoothes the smoothed output by applying a second exponential filter (hence the name double exponential), and it uses this to account for trends in input data. There are various formulations of double exponential smoothing filters, with minor differences between them, but the most popular formulation is defined by the following set of equations: As can be noted, the trend b n is calculated as an exponential filter of the difference between a filters last two outputs. Then the sum of the current trend and the previous filter outputthat is, ( n 1) b ( n 1) are used in calculating the filter output. Including the trend helps to reduce the delay as the filter fits a line to local input data, where the trend b n is the slope of this fitted line. The parameter controls the weights on the input data that was used for calculating the trend, and hence, controls how sensitive the trends is to recent changes in input. A large results in less latency in trend that is, the trend element follows the recent changes in input faster, while a small gives larger weight to older input samples and, hence, results in longer delay in trend elements catching up with changes in input. Note that a trend is the smoothed difference between the last two estimated joint positions (that is, a trend is the smoothed value of n ( n1 ) ) so a trend can be thought of as the estimated velocity of the joint in the case of NUI joint filtering. Therefore, we can think of as the dampening factor used in exponential filtering of joint velocity and that the smoothed joint velocity is accounted for when joint position is calculated as the filter output. The trend factor b n can easily result in overshooting in filter outputs when there are sudden joint movements or stops. For example, suppose a person suddenly moves his or her hand and then stops, which results in a filter input similar to a step function (that is, a sudden jump in filter input). This is shown in Figure 7. In this case, the trend term b n helps the filter output to catch up more quickly with this change in input however, since b n itself is smoothed out, b n will need some time to settle back to zero, which will result in overshoot and ringing in output. Note that there is a delay between b n maximum and overshoot. Figure 7. Output and trend of a double exponential smoothing filter in response to step function input 0.35 and 0.70 The double exponential smoothing filter fits a line to data and, therefore, forecasts the future data as a straight line with a slope equal to trend term b n . In general, this filter performs better than a single smoothing filter in terms of forecasting. However, as shown in Figure 8, the filter overshoot is larger in forecasted outputs. Figure 8. Output and trend of a double exponential smoothing filter in response to step function input 0.50 and 0.40 There are numerical techniques that adaptively update the and parameters such that the error in filter predictions for a given k are minimized in a least-square sense. For example, when predicting one sample ahead (that is, k 1), the prediction error at time n considering the past N forecasts is given by: Then and are updated at time n in a direction that this prediction error is minimized (for details, see the Levenberg-Marquardt algorithm in 10 ,12 ). This criterion is useful if precise forecasting is the only concern however, it does not take into account the smoothing effect of the filter, and so the and parameters calculated by this approach do not necessarily result in smooth output. 4.7. Adaptive Double Exponential Smoothing Filter A simple but useful improvement to a double exponential smoothing filter for NUI joints is to adjust the and parameters adaptively based on the joint velocity, such that when the joint is not moving quickly more aggressive filtering is applied by using smaller and parameters. This adaptation results in smoothed output when a joint is not moving quickly. Alternately, larger and parameters are used when the joint is moving quickly, which results in better responsiveness to input changes and, hence, a lower latency. This idea can be implemented in different ways. For example, an adaptive double exponential smoothing filter could be implemented by using two preset and parameters: one for low-velocity cases, say low and low . and one for high-velocity cases, say high and high . There could also be two velocity thresholds used, say v low and v high . Then for each input X n . the velocity is estimated as v n X n X ( n 1) , and filtering parameters and are set as a linear interpolation between their low and high values based on the current velocity. For example, the parameter used at time n . denoted by n . is set to be: 4.8. Taylor Series Filter The Taylor series expansion is a well-known representation of a function in mathematics, where a continuous function f ( x ) is expressed as an infinite sum of terms, calculated from its derivatives at a given point a 13 : f ( i ) ( a ) is the i th derivative of function f ( x ) at point a . This series is used in many applications for approximating a function as a polynomial of order N at points close to expansion point a . where N is the number of terms in the expansion that are included in this approximation. The Taylor series can be used for forecasting NUI joint data. The underlying assumption is that joint movement is approximated with a polynomial of order N over time. In other terms, we fit a polynomial of size N to past N inputs, and then use this polynomial approximation to forecast next joint data. Note that the NUI joint data are in discrete time therefore, the derivatives used in Taylor series coefficients are approximated numerically as higher order backward differences of input data. For example, the first, second and third degree derivatives are approximated as: As said, the next input is estimated by using the fitted polynomialthat is, X ( n 1 n ) f ( n 1). Substituting the preceding terms for f ( i ) ( n ) in a Taylor series polynomial expansion of size N and choosing a n results in an estimate for next inputs in term of past inputs: For example, for N 3, by using the preceding equations, one obtains: which is, again, a weighted moving average of past N inputs. The Taylor series expansion is helpful, because it can forecast the future positions of joints. Note that the Taylor series does not smooth the data or attempt to remove any noise by itself, though this can be compensated for by applying a smoothing filter, such as exponential smoothing filter, to the output of a Taylor series filter. One approach for tweaking the Taylor series filter is to smooth the data that the Taylor series uses to forecast the current input from previous inputs (that is, X ( n n 1) ) and then calculate the smoothed output as a linear interpolation between X n and X ( n n 1). That is, the filter output is given by: Also note that the approximation of derivatives using only the backward differences is a naive approximation of the derivatives 13 . This is imposed on us, because we do not have any future input data to use in difference equations to estimate the derivatives. The Savitzky-Golay filter is known to create good estimates for the derivatives. So, instead of the difference equations presented in the preceding text, one can use the Savitzky-Golay filter to calculate the derivatives and use them in a Taylor series filter to forecast future outputs. Also remember that the approximation by a Taylor series is accurate when the expansion is around a near point (that is, when x a is small), which means it is not practical to forecast more than one input into the future by using the Taylor series. Note that the Taylor series filter may, at first, seem identical to the Savitzky-Golay filter, because both are fitting a local polynomial to input data. However, they are different, because a Savitzky-Golay filter is over-fitting a local polynomial to input samples, which means that the number of input data used to calculate the model parameters is greater than the model parameters. Since there is more than one potential solution, the least-square error approach is used to find the model parameters that minimize the error in a least-square sense. This allows the Savitzky-Golay filter to handle noise in the input data better, and the results are much smoother. However, in a Taylor series filter, there is no over-fitting of data, and the underlying polynomial is simply approximated by approximating the derivatives of input. This can be noted as exactly N 1 samples ( N previous samples along current sample) are used in calculating the N 1 polynomial coefficients in a Taylor series approach. 4.9. Median Filter In a median filter (also known as moving median filter ), the filters output is the median of the last N inputs. Median filters are useful in removing impulsive spike noises, as shown in Figure 9. Ideally, the filter size N should be selected to be larger than the duration of the spike noise peaks. However, the filters latency directly depends on N . and hence, a larger N adds more latency. Figure 9. Median filter applied to actual NUI data. Ideally, the filter order N should be larger than the duration of the spike noises. Median filters do not take advantage of the statistical distribution of data or noise, and though they have some smoothing effect, they are not suitable for removing random noise from joint data. 4.10. Jitter Removal Filter A jitter removal filter attempts to dampen the spikes in input by limiting the changes allowed in output in each frame. That is, filter output is the same as input if the difference between the current input data and the previous filter output is less than a threshold. Otherwise, the filter limits the changes in output, which can be done by using different methods. For example, the following variant of a jitter removal filter uses an exponential filter to dampen large changes seen in input: Alternately, one can use a simple averaging filter instead of the exponential filter. Since median filters usually perform better in terms of removing spikes, changes in input can be limited by the median: Where X med denotes the median of the last N inputs. Jitter removal filters basically bypass the filtering for cases in which a jump has not been detected that is as large as the threshold in input data. Ideally, the threshold should be selected to be less than the impulsive jumps in the input that are due to spike noise, but larger than normal changes that are due to actual joint movements in practice, these two criteria may overlap with each other. In a Kinect-enabled application, the joint tracking state can be used to adaptively select this thresholdthat is, to use a smaller threshold when the joint data is inferred. 5. Practical Tips and Takeaways Following is a summary of the tips described in this white paper: No filtering solution fits all cases: There is no filtering technique that can be universally used in all Kinect-enabled applications. You must choose and fine-tune the filtering techniques that are right for your application. Latency vs. Smoothing Tradeoff: Be aware of the tradeoff between latency and smoothing in joint filtering. Understand how latency affects your application, and become familiar with different filtering techniques so you can choose and fine-tune the right filter for your application. Filter per-joint and per-application: Joints have a variety of characteristics, and depending on how the filter output is to be used, different filtering techniques should be used per joint. Remember you can filter any data: We usually apply filtering to the Cartesian coordinates ( x , y , z ) of joints however, filtering can be applied to any data calculated from joint positions. For example, one can directly filter the bone length, relative coordinates of a joint with reference to another joint, spherical coordinates of a joint, and so on. Applying mathematical calculations to noisy data or calculating relative joints usually amplifies the noise, so be careful. It may take more than one filter to get good results: A good filtering solution is usually a combination of various filtering techniques, which may include applying a jitter removal filter to remove spike noise, a smoothing filter, and a forecasting filter to reduce latency, and then adjusting the outputs based on person kinematics and anatomy to avoid awkward cases caused by overshoot. Use the joint tracking state: Take advantage of the joint tracking state data, and use it in your filter implementations to apply more aggressive smoothing and jitter removal when a joint position is inferred. Include future frame data in filtering, if possible: In offline cases, or in cases when its acceptable to increase latency by a few frames, include the future joint data in filtering (for example, use ARMA filters, such as central moving average or Savitzky-Golay with M 0), which will result in better noise removal. Account for the actual time elapsed between two NUI frames: In some cases, the call to get the joint positions from the ST system may fail, which would result in a dropped frame. Therefore, the input data to the filter would be missing for that dropped frame, which means that the joint positions are no longer 33 msec apart from each other. Make sure that your filtering implementation uses the time stamp of the NUI frames and that it estimates the missing data points with an interpolation of data before and after the missing data. Reset the filter when a skeleton is lost: When a person moves outside of the cameras field of view, its skeleton is lost and is no longer tracked. The ST system may use a different tracking ID for the same person later, or it may reuse that tracking ID for other persons. So make sure you reset the filter after a person skeleton is lost. Use debug visualization to see how filter parameters affect your application: Visualizing the filtered joint positions on top of the depth map is useful to see how your filtered data is different from the actual depth data. It is useful to visualize only one joint, like the right hand, and render a history of previous positions on screen. This joint path will show you how smooth the filter output was over the past frames. Use Kinect Studio to export joint data and analyze them offline: You can use Kinect Studio to export joint data and analyze them offline. Use Note that the SDK includes the NuiTransformSmooth method, which is an implementation of a joint filter that is based on double exponential smoothing combined with jitter removal and some overshoot control. 6. References Error Analysis and Error Propagation in Noisy Data 1. John Robert Taylor, An Introduction to Error Analysis: The Study of Uncertainties in Physical Measurements . University Science Books, 1999. 2. Manfred Drosg, Dealing with Uncertainties: A Guide to Error Analysis . Springer, 2009. 3. Bevington, Philip, and D. Keith Robinson, Data Reduction and Error Analysis for the Physical Sciences . McGraw-Hill Science, 3rd edition, 2003. 4. Hughes, Ifan, and Thomas Hase, Measurements and their Uncertainties: A practical guide to modern error analysis . Oxford University Press, 2010. ARMA Filters 5. Brockwell, Peter J. and Richard A. Davis, Time Series: Theory and Methods . 2nd edition. Springer, 2009. Digital Filter Design in Frequency Domain 6. Oppenheim, Alan V. Ronald W. Schafer, and John R. Buck, Discrete-Time Signal Processing . Prentice Hall, 1999. 7. A. Antoniou, Digital Filters: Analysis, Design, and Applications . McGraw-Hill, 2000. Moving Average and Exponential Filters 8. Robert Goodell Brown, Smoothing, Forecasting and Prediction of Discrete Time Series . Dover Publications, 2004. 9. Hoang Pham, Springer handbook of engineering statistics . Springer, 2006. 10. Nocedal, Jorger, and Stephen J. Wright, Numerical Optimization . 2nd edition. Springer, 2006. Savitzky-Golay Filter 11. Vijay Madisetti, The digital signal processing handbook . CRC Press, 2009. 12. William H. Press, Numerical Recipes: the art of scientific computing . Cambridge University Press, 2007. Taylor Series and Derivative Estimation Using Difference Equations 13. Joe D. Hoffman, Numerical Methods for Engineers and Scientists . 2nd edition. CRC Press, 2001.This class contains methods for smoothing two dimensional data, i. e. a surface, z f ( x . y ). A choice of smoothing method is offered: Savitzky-Golay filter smoothing Smoothed data Smoothed derivatives, Moving average window smoothing Smoothed data The class also contains methods for: Interpolation within the smoothed data See CurveSmooth for the one dimensional equivalent of this class, i. e. for curve smoothing See ThreeDimensionalSmooth for the three dimensional equivalent of this class. SUMMARY OF METHODS public SurfaceSmooth( double xData, double yData, double zData) public SurfaceSmooth( double zData) public SurfaceSmooth( double xData, double yData, Matrix zData) public SurfaceSmooth( Matrix zData) public SurfaceSmooth( float xData, float yData, float zData) public SurfaceSmooth( float zData) public SurfaceSmooth( long xData, long yData, long zData) public SurfaceSmooth( long zData) public SurfaceSmooth( int xData, int yData, int zData) public SurfaceSmooth( int zData) public SurfaceSmooth( BigDecimal xData, BigDecimal yData, BigDecimal zData) public SurfaceSmooth( BigDecimal zData) public SurfaceSmooth( BigInteger xData, BigInteger yData, BigInteger zData) public double plotMovingAverageY( int xIndex) CONSTRUCTORS public SurfaceSmooth( double xData, double yData, double zData) public SurfaceSmooth( double xData, double yData, Matrix zData) public SurfaceSmooth( float xData, float yData, float zData) public SurfaceSmooth( long xData, long yData, long zData) public SurfaceSmooth( int xData, int yData, int zData) public SurfaceSmooth( BigDecimal xData, BigDecimal yData, BigDecimal zData) public SurfaceSmooth( BigInteger xData, BigInteger yData, BigInteger zData) Usage: SurfaceSmooth ssm new SurfaceSmooth(xData, yData, zData) Creates an instance of SurfaceSmooth. The data is entered as arrays of the x . y and z values, arguments xData . yData and zData . for a surface, z f ( x . y ). The data may be entered as type double, float, long, int, BigDecimal, BigInteger or as any appropriate data type through Matrix. All data, except types BigDecimal and BigInteger, are converted to type double before processing. BigInteger is converted to BigDecimal. Moving average window smoothing is performed in arbitrary precision arithmetic for BigDecimal and BigInteger entered data. Savitzky-Golay filtering is performed in double precision arithmetic for BigDecimal and BigInteger entered data. The data are ordered as ascending x and ascending y values before processing. The ordering of the data in the matrix z argument zData should be as: where m is the number of x values in argument xData and n is the number of y values in argument yData . i. e. the 2D array z argument zData should be dimensioned as zDatanm where n is the number of y yData values and m is the number of x xData values. public SurfaceSmooth( double zData) public SurfaceSmooth( Matrix zData) public SurfaceSmooth( float zData) public SurfaceSmooth( long zData) public SurfaceSmooth( int zData) public SurfaceSmooth( BigDecimal zData) public SurfaceSmooth( BigInteger zData) Usage: SurfaceSmooth ssm new SurfaceSmooth(zData) Creates an instance of SurfaceSmooth. The data is entered as an array of z values, argument zData . for a surface, z f ( x . y ). As no x or y values are entered the data is treated as data sampled at equal x value and y value intervals. Values of 0, 1, 2. to m -1 are assigned to the m x - values. Values of 0, 1, 2. to n -1 are assigned to the n y - values. The data may be entered as type double, float, long, int, BigDecimal, BigInteger or as any appropriate data type through Matrix. All data, except types BigDecimal and BigInteger, are converted to type double before processing. BigInteger is converted to BigDecimal. Moving average window smoothing is performed in arbitrary precision arithmetic for BigDecimal and BigInteger entered data. Savitzky-Golay filtering is performed in double precision arithmetic for BigDecimal and BigInteger entered data. SMOOTHING METHODS SAVITZKY-GOLAY FILTER METHODS Savitzky-Golay Smoothed Curves public double savitzkyGolay( int sgFilterWidthx, int sgFilterWidthy) public double savitzkyGolay( int sgFilterWidth) public double getsavitzkyGolaySmoothedValues() Usage: smoothedData ssm. savitzkyGolay(sgFilterWidthx, sgFilterWidthy) This method returns the smoothed z values, for the data entered via the constructor arguments, using a two dimensional Savitzky-Golay filter of width sgFilterWidthx points in the x dimension and of width sgFilterWidthy points in the y dimension. The default value of the degree of the fitting polynomial is 4. This value may be reset using the setSGpolyDeg method. Usage: smoothedData ssm. savitzkyGolay(sgFilterWidth) This method returns the smoothed z values, for the data entered via the constructor arguments, using a two dimensional Savitzky-Golay filter of width sgFilterWidth points in the x dimension and of the same width, sgFilterWidth points, in the y dimension. The default value of the degree of the fitting polynomial is 4. This value may be reset using the setSGpolyDeg method. Usage: smoothedData ssm. getSavitzkyGolaySmoothedValues() This method returns the smoothed z values if the above Savitzky-Golay filter method has already been called. Savitzky-Golay Smoothed Derivatives public double savitzkyGolay( int sgFilterWidthx, int sgFilterWidthy, int m, int n) public double getSavitzkyGolayDerivatives() Usage: smoothedDataPlusDeriv ssm. savitzkyGolay(sgFilterWidthx, sgFilterWidthy, m, n) This method returns the smoothed z values and the smoothed derivatives. for the data entered via the constructor arguments, using a two dimensional Savitzky-Golay filter of width sgFilterWidthx points in the x dimension and of width sgFilterWidthy points in the y dimension. The arguments m and n contains the values of the required orders of the derivative, m and n . The smoothed z values are returned, in the above usage, in smoothedDataPlusDeriv0 . the derivatives are returned in smoothedDataPlusDeriv1 . The sum of m m and n n must be less than or equal to the degree of the fitting polynomial. The default value of this degree is 4. This value may be reset using the method setSGpolyDegree . Usage: smoothedData ssm. getSavitzkyDerivatives() This method returns the Savitzky-Golay smoothed derivatives. The Savitzky-Golay derivative method must already have been called as the last derivative method and the values of m and n will be that used in this last call. The Savitzky-Golay Filter public double getSGcoefficients() Usage: sgCoefficients ssm. getSGcoefficients() This method returns the Savitzky-Golay filter coefficients, c . used in the smoothing m w and n w are the lengths of the filter in the y and x directions respectively, m l and n l are the number of points preceeding the data point on which the filter is operating, z k, l . in the y and x directions respectively and m u and n u are the number of points following the data point, z k, l,in the y and x directions respectively. If the filter is used as a smoothing filter s k, l is the smoothed value of the data point z k, l and the c values used are those stored in the zeroth row of the returned matrix sgCoefficients . Each row of sgCoefficients is the array of coefficients c m w n w arranged linearly as the m w blocks of rows each of length n w . Each row, when applied to the data gives the smoothed m , n th derivatives. The zeroth row, indices 0,0, gives the smoothed zeroth derivative, i. e. the smoothed data values, the second row, indices 0,1, gives the derivatives. The pair of indices associated with each row may be obtained by calling the method getSGpolyIndices() and they correspond to the indices of the coefficients of the fitting polynomial (see below). The default value of the degree of the fitting polynomial is 4: This value may be reset using the setSGpolyDegree method. The smoothing method, savitzkyGolay . uses a symmetrical filter, i. e. m l m u and n l n u . public int getSGpolyIndices() Usage: indicesPairs ssm. getSGpolyIndices() This method returns the pairs of indices of the fitting polynomial (see immediately above). The value in indices i0 is the first index of the ith coefficient of the polynomial and is also the power of y in the ith term. The value in indices i1 is the second index of the ith coefficient of the polynomial and is also the power of x in the ith term. These returned pairs are also ordered to match the rows in the returned c matrix (See savitzkyGolayFilter method above. public void setSGpolyDegree( int degree) public int getSGpolyDegree() Usage: ssm. setSGpolyDegree(degree) This method resets the degree of the Savitzky-Golay fitting polynomial. The default value is 4 if this method is not called. Usage: deg ssm. getSGpolyDegree() This method returns the degree of the Savitzky-Golay fitting polynomial. The default value is 4. Static methods for returning a Savitzky-Golay filter public static double savitzkyGolayFilter( int nBackwardx, int nForwardx, int nBackwardy, int nForwardy, int polyDegree) Usage: sgCoefficients SurfaceSmooth. savitzkyGolayFilter(nBackwardx, nForwardx, nBackwardx, nForwardx, polyDegree) This method returns the coefficients, c . of a two dimensional Savitzky-Golay filter of x dimension length, m w nBackWardx nForWardx 1, and y dimension length, n w nBackWardy nForWardy 1, with a fitting polynomial of degree, polyDegree . A description of the coefficients, c . their application and their ordering within the returned two dimensional array, sgCoefficients . may be found above. The arguments nBackWardx m l and nBackWardy n l are the number of points preceeding the data point, upon which the filter is operating, in the x and y dimensions respectively and nForWardx m u and nForWardy n u are the number of points following the data point in the x and y dimensions respectively. public static int filterIndices( int degree) Usage: indicesPairs SurfaceSmooth. filterIndices(deg) This method returns the pairs of indices of a fitting polynomial of degree deg . The value in indices i0 is the first index of the ith coefficient of the polynomial and is also the power of y in the ith term. The value in indices i1 is the second index of the ith coefficient of the polynomial and is also the power of x in the ith term. An example of such a fitting polynomial and its coefficients is shown above. These returned pairs are also ordered to match the rows in the corresponding c matrix. MOVING AVERAGE WINDOW SMOOTHING public double movingAverage( int windowWidthx, int windowWidthy) public double movingAverage( int windowWidth) public BigDecimal movingAverageAsBigDecimal( int windowWidthx, int windowWidthy) public BigDecimal movingAverageAsBigDecimal( int windowWidth) public double getMovingAverageValues() public BigDecimal getMovingAverageValuesAsBigDecimal() Usage: smoothedData ssm. movingAverage(windowWidthx, windowWidthy) This method returns the smoothed z values, for the data entered via the constructor arguments, using a moving average window of n w argument windowWidthx points in the x dimension and of m w argument windowWidthy points in the y dimension: s k, l is the smoothed value of the data point z k, l . The entered value for the number of points in the windows are adjusted to the next higher odd number if an even number has been entered. The values of n l . n u . m l and m u are truncated appropriately if, when close to the data extremes, they fall below or above the first or last data point respectively. The smoothed data is returned as type double. Usage: smoothedData ssm. movingAverage(windowWidth) As immediately above for movingAverage(windowWidthx, windowWidthy) with a square window, i. e. windowWidthx windowWidth and windowWidthy windowWidth . Usage: smoothedData ssm. movingAverageAsBigDecimal(windowWidthx, windowWidthy) As above for movingAverage(windowWidthx, windowWidthy) with the exception that the smoothed data is returned as type BigDecimal. If the data was entered as type BigDecimal or BigInteger the smoothing will have been performed in arbitrary arithmetic. Usage: smoothedData ssm. movingAverageAsBigDecimal(windowWidth) As above for movingAverage(windowWidthx, windowWidthy) with a square window, i. e. windowWidthx windowWidth and windowWidthy windowWidth . and with the exception that the smoothed data is returned as type BigDecimal. If the data was entered as type BigDecimal or BigInteger the smoothing will have been performed in arbitrary arithmetic. Usage: smoothedData ssm. getMovingAverageValues() This method returns the smoothed z values if the above moving average window method has already been called. Usage: smoothedData ssm. getMovingAverageValuesAsBigDecimal() This method returns the smoothed z values if the above moving average window method has already been called. The smoothed values are returned as type BigDecimal. EXTENT OF SMOOTHING public double extentSavitzkyGolay() public double extentMovingAverage() These methods return the value of the function where z i, j is the original z value of the i th, j th data point, s i, j is its smoothed value, z min is the minimum value of the z i, j . z max is the maximum value of the z i, j and n is the number of x coordinates and m is the number of y coordinates. Usage: extent ssm. extentSavitzkyGolay() In this method s i, j is the Savitzky-Golay smoothed value. Usage: extent ssm. extentMovingAverage() In this method s i, j is its moving average smoothed value. INTERPOLATION public double interpolateSavitzkyGolay( double xi, double yi) public double interpolateMovingAverage( double xi, double yi) Usage: zi ssm. interpolateSavitzkyGolay(xi, yi) This method returns the interpolated value of z zi for the supplied x argument xi and y argument yi values for the Savitzky-Golay smoothed data. The interpolation procedure uses the BiCubicSpline class. A Savitzky-Golay smoothing method must have been called previously. Usage: zi ssm. interpolateMovingAverage(xi, yi) This method returns the interpolated value of z zi for the supplied x argument xi and y argument yi values for the moving average smoothed data. The interpolation procedure uses the BiCubicSpline class. A moving average smoothing method must have been called previously. PLOT Savitzky-Golay public double plotSavitzkyGolayX( double yValue) public double plotSavitzkyGolayX( int yIndex) public double plotSavitzkyGolayY( double xValue) public double plotSavitzkyGolayY( int xIndex) Usage: ssm. plotSavitzkyGolayX(yValue) This method displays a plot of both the original data and the Savitzky-Golay smoothed data for a section through the surface parallel to the x - axis at a value of y supplied as the argument yValue . The value, yValue . must be one of the values supplied in the array yData via a Constructor. Usage: ssm. plotSavitzkyGolayX(yIndex) This method displays a plot of both the original data and the Savitzky-Golay smoothed data for a section through the surface parallel to the x - axis at the value of y whose index in the array yData entered via a Constructor is the integer supplied as the argument yIndex . NB indices start at 0. Usage: ssm. plotSavitzkyGolayY(xValue) This method displays a plot of both the original data and the Savitzky-Golay smoothed data for a section through the surface parallel to the y - axis at a value of x supplied as the argument xValue . The value, xValue . must be one of the values supplied in the array xData via a Constructor. Usage: ssm. plotSavitzkyGolayY(xIndex) This method displays a plot of both the original data and the Savitzky-Golay smoothed data for a section through the surface parallel to the y - axis at the value of x whose index in the array xData entered via a Constructor is the integer supplied as the argument xIndex . NB indices start at 0. Moving average public double plotMovingAverageX( double yValue) public double plotMovingAverageX( int yIndex) public double plotMovingAverageY( double xValue) public double plotMovingAverageY( int xIndex) Usage: ssm. plotMovingAverageX(yValue) This method displays a plot of both the original data and the Moving Average smoothed data for a section through the surface parallel to the x - axis at a value of y supplied as the argument yValue . The value, yValue . must be one of the values supplied in the array yData via a Constructor. Usage: ssm. plotMovingAverageX(yIndex) This method displays a plot of both the original data and the Moving Average smoothed data for a section through the surface parallel to the x - axis at the value of y whose index in the array yData entered via a Constructor is the integer supplied as the argument yIndex . NB indices start at 0. Usage: ssm. plotMovingAverageY(xValue) This method displays a plot of both the original data and the Moving Average smoothed data for a section through the surface parallel to the y - axis at a value of x supplied as the argument xValue . The value, xValue . must be one of the values supplied in the array xData via a Constructor. Usage: ssm. plotMovingAverageY(xIndex) This method displays a plot of both the original data and the Moving Average smoothed data for a section through the surface parallel to the y - axis at the value of x whose index in the array xData entered via a Constructor is the integer supplied as the argument xIndex . NB indices start at 0. OTHER CLASSES USED BY THIS CLASS

No comments:

Post a Comment