summaryrefslogtreecommitdiffstats
path: root/lib/zigzag.c
blob: 50549e23f659042697d0c18e74dc30f4871b10ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Zigzag
//
// zigzag
//
// ZigZag Filter
//
// 
//
// Inputs:    1
// Outputs:   2
// Constants: 1


#include "ts.h"


typedef struct {
    fp_t threshold;
} ts_zigzag_params_t;

ts_parameter_t const ts_zigzag_p = { .n_inputs = 1, .n_outputs = 2, .n_constants = 1, .params_size = sizeof(ts_zigzag_params_t) };


uint_t ts_zigzag_offset( ts_constant_t const *c )
{
	( void )c;
	return ( 0 );
}

int ts_zigzag(
	fp_t * const *y, uint_t y_n,
	fp_t const * const *x, uint_t x_n,
	uint_t n, ts_constant_t const *c
)
{
	TS_PROLOGUE( ts_zigzag_p );
	if ( !c ) return -1;
	if (n == 0) return -1;

	fp_t threshold = ((ts_zigzag_params_t *)c)->threshold;
	if (threshold <= 0 || isnan(threshold) || isinf(threshold)) return -1;

	y[0][0] = x[0][0];
	y[1][0] = 0;

	for( uint_t i = 1; i < n; ++i )
	{
		fp_t last_zz = y[0][i - 1];
		fp_t dir = y[1][i - 1];
		fp_t change = last_zz != 0 ? ( x[0][i] - last_zz ) / last_zz * 100.0 : 0;

		if( dir == 0 )
		{
			if( change >= threshold )
			{
				y[0][i] = x[0][i];
				y[1][i] = 1;
			}
			else if( change <= -threshold )
			{
				y[0][i] = x[0][i];
				y[1][i] = -1;
			}
			else
			{
				y[0][i] = last_zz;
				y[1][i] = 0;
			}
		}
		else if( dir == 1 )
		{
			if( change <= -threshold )
			{
				y[0][i] = x[0][i];
				y[1][i] = -1;
			}
			else
			{
				y[0][i] = last_zz;
				y[1][i] = 1;
			}
		}
		else
		{
			if( change >= threshold )
			{
				y[0][i] = x[0][i];
				y[1][i] = 1;
			}
			else
			{
				y[0][i] = last_zz;
				y[1][i] = -1;
			}
		}
	}
	return 0;
}