-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilterCodeGenerator.py
More file actions
228 lines (198 loc) · 6.85 KB
/
Copy pathFilterCodeGenerator.py
File metadata and controls
228 lines (198 loc) · 6.85 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
from datetime import datetime
class FilterCodeGenerator:
def __init__(self, filter):
self.header_template = """
/* Auto-generated filter implementation
* Generated on: {timestamp}
* Filter order: {order}
*/
#ifndef {header_guard}
#define {header_guard}
#include <stdint.h>
{struct_definitions}
{function_declarations}
#endif /* {header_guard} */
"""
self.source_template = """
#include "{header_name}"
{function_definitions}
"""
self.header_path = None
self.source_path = None
self.filter = filter
def export_c_code(self, file_path, name="filter"):
base_name = file_path.rsplit('.', 1)[0]
base_filename = base_name.split('/')[-1]
code_parts = self._generate_code_parts(name)
header_content, source_content = self._get_files_content(
code_parts,
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
base_filename
)
self.header_path = f"{base_name}.h"
self.source_path = f"{base_name}.c"
self._write_files(header_content, source_content)
return self.header_path, self.source_path
def _generate_code_parts(self, name):
tf = self.filter.get_transfer_function(self)
denominator_coeffs = tf[1]
numerator_coeffs = tf[0]
order = max(len(denominator_coeffs), len(numerator_coeffs)) - 1
# Generate structure definition
struct_def = f"""
typedef struct {{
float state[{order}]; // Delay line
float output; // Latest output
}} {name}_filter_t;
"""
# Generate initialization function
init_func = f"""
void {name}_init({name}_filter_t* f) {{
for(int i = 0; i < {order}; i++) {{
f->state[i] = 0.0f;
}}
f->output = 0.0f;
}}
"""
# Generate coefficient arrays
coeff_arrays = f"""
// Filter coefficients
static const float {name}_num[] = {{{', '.join([f"{x}f" for x in numerator_coeffs])}}};
static const float {name}_den[] = {{{', '.join([f"{x}f" for x in denominator_coeffs[1:]])}}}; // Skip a0
"""
# Generate processing function
process_func = f"""
float {name}_process({name}_filter_t* f, float input) {{
float new_state = input;
// Apply feedback
for(int i = 0; i < {order}; i++) {{
new_state -= {name}_den[i] * f->state[i];
}}
// Calculate output
float output = {name}_num[0] * new_state;
for(int i = 0; i < {order}; i++) {{
output += {name}_num[i + 1] * f->state[i];
}}
// Update state
for(int i = {order - 1}; i > 0; i--) {{
f->state[i] = f->state[i-1];
}}
f->state[0] = new_state;
f->output = output;
return output;
}}
"""
return {
'struct_definitions': struct_def,
'function_declarations': f"""
void {name}_init({name}_filter_t* f);
float {name}_process({name}_filter_t* f, float input);
""",
'function_definitions': coeff_arrays + init_func + process_func
}
def _get_files_content(self, code_parts, timestamp, base_filename):
"""Generate header and source files
Args:
base_filename: The base filename without extension (e.g., 'myfilter')
code_parts: Dictionary containing struct definitions, function declarations, and function definitions
timestamp: Timestamp for the code generation
base_filename: Base filename for the generated files
"""
# Create header guard from filename (e.g., MYFILTER_H)
header_guard = f"{base_filename.upper()}_H"
# Get just the filename without path for include statement
header_name = f"{base_filename.split('/')[-1]}.h"
header_content = self.header_template.format(
timestamp=timestamp,
order="N/A",
header_guard=header_guard,
struct_definitions=code_parts['struct_definitions'],
function_declarations=code_parts['function_declarations']
)
source_content = self.source_template.format(
header_name=header_name,
function_definitions=code_parts['function_definitions']
)
return header_content, source_content
def _write_files(self, header, source):
"""Write header and source files to disk"""
with open(self.header_path, "w") as f:
f.write(header)
with open(self.source_path, "w") as f:
f.write(source)
# def generate_cascade_form(self, name, sections):
# """Generate C code for Cascade Form implementation"""
# total_sections = len(sections)
# max_order = max(max(len(d), len(n)) - 1 for d, n in sections)
#
# # Generate structure definition
# struct_def = f"""
# typedef struct {{
# float state[{total_sections}][{max_order}]; // State for each section
# float output; // Latest output
# }} {name}_filter_t;
# """
#
# # Generate initialization function
# init_func = f"""
# void {name}_init({name}_filter_t* f) {{
# for(int s = 0; s < {total_sections}; s++) {{
# for(int i = 0; i < {max_order}; i++) {{
# f->state[s][i] = 0.0f;
# }}
# }}
# f->output = 0.0f;
# }}
# """
#
# # Generate coefficient arrays for each section
# coeff_arrays = []
# for i, (deno, num) in enumerate(sections):
# coeff_arrays.extend([
# f"static const float {name}_num{i}[] = {{{', '.join([f'{x}f' for x in num])}}};"
# f"static const float {name}_den{i}[] = {{{', '.join([f'{x}f' for x in deno[1:]])}}};"
# ])
# coeff_arrays = "\n".join(coeff_arrays)
#
# # Generate processing function
# process_sections = []
# for i, (deno, num) in enumerate(sections):
# order = max(len(deno), len(num)) - 1
# section = f"""
# // Section {i}
# float new_state{i} = section_input;
# for(int i = 0; i < {order}; i++) {{
# new_state{i} -= {name}_den{i}[i] * f->state[{i}][i];
# }}
#
# section_input = {name}_num{i}[0] * new_state{i};
# for(int i = 0; i < {order}; i++) {{
# section_input += {name}_num{i}[i + 1] * f->state[{i}][i];
# }}
#
# for(int i = {order - 1}; i > 0; i--) {{
# f->state[{i}][i] = f->state[{i}][i-1];
# }}
# f->state[{i}][0] = new_state{i};
# """
# process_sections.append(section)
#
# process_func = f"""
# float {name}_process({name}_filter_t* f, float input) {{
# float section_input = input;
#
# {' '.join(process_sections)}
#
# f->output = section_input;
# return f->output;
# }}
# """
#
# return {
# 'struct_definitions': struct_def,
# 'function_declarations': f"""
# void {name}_init({name}_filter_t* f);
# float {name}_process({name}_filter_t* f, float input);
# """,
# 'function_definitions': coeff_arrays + init_func + process_func
# }