or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-arithmetic.mdelementary-functions.mdelliptic-modular-functions.mdindex.mdlinear-algebra.mdmathematical-constants.mdnumerical-calculus.mdpattern-recognition.mdsignal-processing.mdspecial-functions.mdvisualization.md

signal-processing.mddocs/

0

# Signal Processing and Waveform Functions

1

2

Standard waveform functions and signal processing utilities for mathematical modeling, digital signal processing, and engineering applications.

3

4

## Capabilities

5

6

### Standard Waveforms

7

8

Basic periodic waveforms commonly used in signal processing and engineering.

9

10

```python { .api }

11

def squarew(t, period=1):

12

"""

13

Square wave function.

14

15

Args:

16

t: Time variable

17

period: Period of the waveform (default: 1)

18

19

Returns:

20

Square wave value: +1 for first half of period, -1 for second half

21

"""

22

23

def trianglew(t, period=1):

24

"""

25

Triangle wave function.

26

27

Args:

28

t: Time variable

29

period: Period of the waveform (default: 1)

30

31

Returns:

32

Triangle wave value: linear ramp from -1 to +1 and back

33

"""

34

35

def sawtoothw(t, period=1, rising=True):

36

"""

37

Sawtooth wave function.

38

39

Args:

40

t: Time variable

41

period: Period of the waveform (default: 1)

42

rising: True for rising sawtooth, False for falling (default: True)

43

44

Returns:

45

Sawtooth wave value: linear ramp within each period

46

"""

47

48

def unit_triangle(t, center=0, width=1):

49

"""

50

Unit triangle function (triangular pulse).

51

52

Args:

53

t: Time variable

54

center: Center position of triangle (default: 0)

55

width: Base width of triangle (default: 1)

56

57

Returns:

58

Unit triangle: 1 at center, 0 outside width, linear in between

59

"""

60

```

61

62

### Sigmoid and Activation Functions

63

64

Smooth functions commonly used in signal processing and neural networks.

65

66

```python { .api }

67

def sigmoid(x):

68

"""

69

Sigmoid (logistic) function.

70

71

Args:

72

x: Input value

73

74

Returns:

75

1 / (1 + exp(-x))

76

Smooth S-curve from 0 to 1

77

"""

78

```

79

80

### Usage Examples

81

82

```python

83

import mpmath

84

from mpmath import mp

85

import numpy as np # For demonstration arrays

86

87

# Set precision

88

mp.dps = 25

89

90

# Example 1: Generate square wave

91

print("=== Square Wave ===")

92

t_values = [i * 0.1 for i in range(-20, 21)] # -2 to 2 with step 0.1

93

square_values = [mp.squarew(t, period=1) for t in t_values]

94

95

print("Time\tSquare Wave")

96

for i in range(0, len(t_values), 4): # Print every 4th value

97

print(f"{t_values[i]:.1f}\t{square_values[i]}")

98

99

# Example 2: Triangle wave

100

print("\n=== Triangle Wave ===")

101

triangle_values = [mp.trianglew(t, period=2) for t in t_values]

102

103

print("Time\tTriangle Wave")

104

for i in range(0, len(t_values), 4):

105

print(f"{t_values[i]:.1f}\t{triangle_values[i]}")

106

107

# Example 3: Sawtooth waves

108

print("\n=== Sawtooth Waves ===")

109

rising_sawtooth = [mp.sawtoothw(t, period=1.5, rising=True) for t in t_values]

110

falling_sawtooth = [mp.sawtoothw(t, period=1.5, rising=False) for t in t_values]

111

112

print("Time\tRising\tFalling")

113

for i in range(0, len(t_values), 4):

114

print(f"{t_values[i]:.1f}\t{rising_sawtooth[i]:.3f}\t{falling_sawtooth[i]:.3f}")

115

116

# Example 4: Unit triangle function

117

print("\n=== Unit Triangle ===")

118

unit_tri_values = [mp.unit_triangle(t, center=0, width=2) for t in t_values]

119

120

print("Time\tUnit Triangle")

121

for i in range(len(t_values)):

122

if unit_tri_values[i] > 0: # Only print non-zero values

123

print(f"{t_values[i]:.1f}\t{unit_tri_values[i]:.3f}")

124

125

# Example 5: Sigmoid function

126

print("\n=== Sigmoid Function ===")

127

x_values = [-3, -2, -1, 0, 1, 2, 3]

128

sigmoid_values = [mp.sigmoid(x) for x in x_values]

129

130

print("x\tSigmoid(x)")

131

for x, sig in zip(x_values, sigmoid_values):

132

print(f"{x}\t{sig:.6f}")

133

134

# Example 6: Fourier series approximation using square wave

135

print("\n=== Fourier Series Approximation ===")

136

def fourier_square_wave(t, n_terms=5):

137

"""Approximate square wave using Fourier series."""

138

result = 0

139

for k in range(1, n_terms + 1):

140

if k % 2 == 1: # Only odd harmonics

141

coefficient = 4 / (mp.pi * k)

142

result += coefficient * mp.sin(2 * mp.pi * k * t)

143

return result

144

145

t_test = [0, 0.25, 0.5, 0.75, 1.0]

146

print("Time\tSquare Wave\tFourier Approx (5 terms)")

147

for t in t_test:

148

exact = mp.squarew(t)

149

approx = fourier_square_wave(t, 5)

150

print(f"{t:.2f}\t{exact:8.3f}\t{approx:8.3f}")

151

152

# Example 7: Signal modulation examples

153

print("\n=== Signal Modulation ===")

154

155

def amplitude_modulated_signal(t, carrier_freq=5, mod_freq=1, mod_depth=0.5):

156

"""AM signal: carrier modulated by triangle wave."""

157

carrier = mp.sin(2 * mp.pi * carrier_freq * t)

158

modulation = mp.trianglew(t, period=1/mod_freq)

159

return (1 + mod_depth * modulation) * carrier

160

161

def pulse_width_modulated(t, freq=1, duty_cycle_func=None):

162

"""PWM signal with varying duty cycle."""

163

if duty_cycle_func is None:

164

duty_cycle_func = lambda x: 0.5 + 0.3 * mp.sin(2 * mp.pi * 0.2 * x)

165

166

period = 1 / freq

167

t_mod = t % period

168

duty = duty_cycle_func(t)

169

return 1 if t_mod < duty * period else -1

170

171

# Test modulated signals

172

t_mod = 0.5

173

am_signal = amplitude_modulated_signal(t_mod)

174

pwm_signal = pulse_width_modulated(t_mod)

175

print(f"AM signal at t={t_mod}: {am_signal:.4f}")

176

print(f"PWM signal at t={t_mod}: {pwm_signal}")

177

178

# Example 8: Window functions (using sigmoid)

179

print("\n=== Window Functions ===")

180

181

def sigmoid_window(t, width=2, steepness=5):

182

"""Smooth window using sigmoid functions."""

183

left_edge = mp.sigmoid(steepness * (t + width/2))

184

right_edge = mp.sigmoid(-steepness * (t - width/2))

185

return left_edge * right_edge

186

187

window_t = [-2, -1, 0, 1, 2]

188

print("Time\tSigmoid Window")

189

for t in window_t:

190

window_val = sigmoid_window(t, width=2, steepness=3)

191

print(f"{t:4.1f}\t{window_val:.6f}")

192

193

# Example 9: Digital filter simulation

194

print("\n=== Digital Filter Simulation ===")

195

196

def moving_average_filter(signal_func, t, window_size=0.2, samples=21):

197

"""Simple moving average filter."""

198

dt = window_size / (samples - 1)

199

sum_val = 0

200

for i in range(samples):

201

sample_time = t - window_size/2 + i * dt

202

sum_val += signal_func(sample_time)

203

return sum_val / samples

204

205

# Apply filter to noisy square wave

206

def noisy_square(t):

207

base = mp.squarew(t, period=1)

208

noise = 0.1 * mp.sin(20 * mp.pi * t) # High frequency noise

209

return base + noise

210

211

test_times = [0, 0.1, 0.25, 0.4, 0.5]

212

print("Time\tNoisy Signal\tFiltered")

213

for t in test_times:

214

noisy = noisy_square(t)

215

filtered = moving_average_filter(noisy_square, t)

216

print(f"{t:.2f}\t{noisy:8.4f}\t{filtered:8.4f}")

217

218

# Example 10: Harmonic analysis

219

print("\n=== Harmonic Analysis ===")

220

221

def analyze_harmonics(waveform_func, period=1, max_harmonic=5):

222

"""Simple harmonic analysis using integration."""

223

fundamental_freq = 1 / period

224

225

print(f"Harmonic analysis for period = {period}")

226

print("n\tAmplitude\tPhase")

227

228

for n in range(1, max_harmonic + 1):

229

# Compute Fourier coefficients

230

def integrand_cos(t):

231

return waveform_func(t) * mp.cos(2 * mp.pi * n * fundamental_freq * t)

232

233

def integrand_sin(t):

234

return waveform_func(t) * mp.sin(2 * mp.pi * n * fundamental_freq * t)

235

236

# Simple numerical integration (Riemann sum)

237

a_n = 0

238

b_n = 0

239

samples = 100

240

dt = period / samples

241

242

for i in range(samples):

243

t_sample = i * dt

244

a_n += integrand_cos(t_sample) * dt

245

b_n += integrand_sin(t_sample) * dt

246

247

a_n *= 2 / period

248

b_n *= 2 / period

249

250

amplitude = mp.sqrt(a_n**2 + b_n**2)

251

phase = mp.atan2(b_n, a_n) * 180 / mp.pi

252

253

print(f"{n}\t{amplitude:.4f}\t\t{phase:.1f}°")

254

255

# Analyze square wave harmonics

256

analyze_harmonics(lambda t: mp.squarew(t, period=1), period=1, max_harmonic=3)

257

258

print("\n=== Signal Processing Examples Complete ===")

259

```

260

261

### Mathematical Properties

262

263

#### Waveform Characteristics

264

265

**Square Wave**:

266

- Discontinuous jumps between ±1

267

- Fourier series: Sum of odd harmonics only

268

- Fundamental frequency plus 3rd, 5th, 7th harmonics...

269

270

**Triangle Wave**:

271

- Continuous but non-differentiable at peaks

272

- Smoother than square wave

273

- Faster convergence in Fourier series

274

275

**Sawtooth Wave**:

276

- Linear ramp with discontinuous reset

277

- Contains all harmonics (odd and even)

278

- Useful for sweep generators

279

280

**Sigmoid Function**:

281

- Smooth S-curve transition

282

- Derivative is bell-shaped

283

- Used in neural networks and smooth windowing

284

285

### Applications

286

287

#### Signal Processing

288

- **Waveform generation**: Test signals for systems

289

- **Modulation**: AM, FM, PWM signal generation

290

- **Filtering**: Window functions and digital filters

291

- **Analysis**: Harmonic content and spectral analysis

292

293

#### Mathematical Modeling

294

- **Switching systems**: On/off behaviors

295

- **Biological models**: Activation functions

296

- **Control systems**: Reference signals and step responses

297

- **Physics**: Periodic phenomena and wave equations

298

299

#### Engineering Applications

300

- **Electronics**: Clock signals and timing

301

- **Communications**: Carrier and modulation signals

302

- **Power systems**: AC waveforms and harmonics

303

- **Audio processing**: Synthesis and effects

304

305

The high precision arithmetic ensures accurate waveform generation even for demanding applications requiring exact timing relationships or minimal distortion.