• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

feihoo87 / waveforms / 7222551172

15 Dec 2023 01:16PM UTC coverage: 33.393% (-0.07%) from 33.465%
7222551172

push

github

feihoo87
fix wave_sum

1 of 1 new or added line in 1 file covered. (100.0%)

233 existing lines in 2 files now uncovered.

2795 of 8370 relevant lines covered (33.39%)

2.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

48.02
/waveforms/waveform.py
1
from fractions import Fraction
9✔
2

3
import numpy as np
9✔
4
from numpy import e, inf, pi
9✔
5
from scipy.signal import sosfilt
9✔
6

7
from ._waveform import (_D, COS, COSH, DRAG, ERF, EXP, EXPONENTIALCHIRP,
9✔
8
                        GAUSSIAN, HYPERBOLICCHIRP, INTERP, LINEAR, LINEARCHIRP,
9
                        NDIGITS, SINC, SINH, _baseFunc, _baseFunc_latex,
10
                        _const, _half, _one, _zero, add, basic_wave,
11
                        calc_parts, filter, is_const, merge_waveform, mul, pow,
12
                        registerBaseFunc, registerBaseFuncLatex,
13
                        registerDerivative, shift, simplify, wave_sum)
14

15

16
def _test_spec_num(num, spec):
9✔
17
    x = Fraction(num / spec).limit_denominator(1000000000)
×
18
    if x.denominator <= 24:
×
19
        return True, x, 1
×
20
    x = Fraction(spec * num).limit_denominator(1000000000)
×
21
    if x.denominator <= 24:
×
22
        return True, x, -1
×
23
    return False, x, 0
×
24

25

26
def _spec_num_latex(num):
9✔
27
    for spec, spec_latex in [(1, ''), (np.sqrt(2), '\\sqrt{2}'),
×
28
                             (np.sqrt(3), '\\sqrt{3}'),
29
                             (np.sqrt(5), '\\sqrt{5}'),
30
                             (np.log(2), '\\log{2}'), (np.log(3), '\\log{3}'),
31
                             (np.log(5), '\\log{5}'), (np.e, 'e'),
32
                             (np.pi, '\\pi'), (np.pi**2, '\\pi^2'),
33
                             (np.sqrt(np.pi), '\\sqrt{\\pi}')]:
34
        flag, x, sign = _test_spec_num(num, spec)
×
35
        if flag:
×
36
            if sign < 0:
×
37
                spec_latex = f"\\frac{{{1}}}{{{spec_latex}}}"
×
38
            if x.denominator == 1:
×
39
                if x.numerator == 1:
×
40
                    return f"{spec_latex}"
×
41
                else:
42
                    return f"{x.numerator:g}{spec_latex}"
×
43
            else:
44
                if x.numerator < 0:
×
45
                    return f"-\\frac{{{-x.numerator}}}{{{x.denominator}}}{spec_latex}"
×
46
                else:
47
                    return f"\\frac{{{x.numerator}}}{{{x.denominator}}}{spec_latex}"
×
48
    return f"{num:g}"
×
49

50

51
def _num_latex(num):
9✔
52
    if num == -np.inf:
×
53
        return r"-\infty"
×
54
    elif num == np.inf:
×
55
        return r"\infty"
×
56
    if num.imag > 0:
×
57
        return f"\\left({_num_latex(num.real)}+{_num_latex(num.imag)}j\\right)"
×
58
    elif num.imag < 0:
×
59
        return f"\\left({_num_latex(num.real)}-{_num_latex(-num.imag)}j\\right)"
×
60
    s = _spec_num_latex(num.real)
×
61
    if s == '' and round(num.real) == 1:
×
62
        return '1'
×
63
    if "e" in s:
×
64
        a, n = s.split("e")
×
65
        n = float(n)
×
66
        s = f"{a} \\times 10^{{{n:g}}}"
×
67
    return s
×
68

69

70
def _fun_latex(fun):
9✔
71
    funID, *args, shift = fun
×
72
    if _baseFunc_latex[funID] is None:
×
73
        shift = _num_latex(shift)
×
74
        if shift == "0":
×
75
            shift = ""
×
76
        elif shift[0] != '-':
×
77
            shift = "+" + shift
×
78
        return r"\mathrm{Func}" + f"{funID}(t{shift}, ...)"
×
79
    return _baseFunc_latex[funID](shift, *args)
×
80

81

82
def _wav_latex(wav):
9✔
83

84
    if wav == _zero:
×
85
        return "0"
×
86
    elif is_const(wav):
×
87
        return f"{wav[1][0]}"
×
88

89
    sum_expr = []
×
90
    for mul, amp in zip(*wav):
×
91
        if mul == ((), ()):
×
92
            sum_expr.append(_num_latex(amp))
×
93
            continue
×
94
        mul_expr = []
×
95
        amp = _num_latex(amp)
×
96
        if amp != "1":
×
97
            mul_expr.append(amp)
×
98
        for fun, n in zip(*mul):
×
99
            fun_expr = _fun_latex(fun)
×
100
            if n != 1:
×
101
                mul_expr.append(fun_expr + "^{" + f"{n}" + "}")
×
102
            else:
103
                mul_expr.append(fun_expr)
×
104
        sum_expr.append(''.join(mul_expr))
×
105

106
    ret = sum_expr[0]
×
107
    for expr in sum_expr[1:]:
×
108
        if expr[0] == '-':
×
109
            ret += expr
×
110
        else:
111
            ret += "+" + expr
×
112
    return ret
×
113

114

115
class Waveform:
9✔
116
    __slots__ = ('bounds', 'seq', 'max', 'min', 'start', 'stop', 'sample_rate',
9✔
117
                 'filters', 'label')
118

119
    def __init__(self, bounds=(+inf, ), seq=(_zero, ), min=-inf, max=inf):
9✔
120
        self.bounds = bounds
9✔
121
        self.seq = seq
9✔
122
        self.max = max
9✔
123
        self.min = min
9✔
124
        self.start = None
9✔
125
        self.stop = None
9✔
126
        self.sample_rate = None
9✔
127
        self.filters = None
9✔
128
        self.label = None
9✔
129

130
    def _begin(self):
9✔
131
        for i, s in enumerate(self.seq):
×
132
            if s is not _zero:
×
133
                if i == 0:
×
134
                    return -inf
×
135
                return self.bounds[i - 1]
×
136
        return inf
×
137

138
    def _end(self):
9✔
139
        N = len(self.bounds)
×
140
        for i, s in enumerate(self.seq[::-1]):
×
141
            if s is not _zero:
×
142
                if i == 0:
×
143
                    return inf
×
144
                return self.bounds[N - i - 1]
×
145
        return -inf
×
146

147
    @property
9✔
148
    def begin(self):
9✔
149
        if self.start is None:
×
150
            return self._begin()
×
151
        else:
152
            return max(self.start, self._begin())
×
153

154
    @property
9✔
155
    def end(self):
9✔
156
        if self.stop is None:
×
157
            return self._end()
×
158
        else:
159
            return min(self.stop, self._end())
×
160

161
    def sample(self,
9✔
162
               sample_rate=None,
163
               out=None,
164
               chunk_size=None,
165
               function_lib=None,
166
               filters=None):
167
        if sample_rate is None:
9✔
168
            sample_rate = self.sample_rate
9✔
169
        if self.start is None or self.stop is None or sample_rate is None:
9✔
170
            raise ValueError(
×
171
                f'Waveform is not initialized. {self.start=}, {self.stop=}, {sample_rate=}'
172
            )
173
        if filters is None:
9✔
174
            filters = self.filters
9✔
175
        if chunk_size is None:
9✔
176
            x = np.arange(self.start, self.stop, 1 / sample_rate)
9✔
177
            sig = self.__call__(x, out=out, function_lib=function_lib)
9✔
178
            if filters is not None:
9✔
179
                sos, initial = filters
9✔
180
                if initial:
9✔
181
                    sig = sosfilt(sos, sig - initial) + initial
×
182
                else:
183
                    sig = sosfilt(sos, sig)
9✔
184
            return sig
9✔
185
        else:
186
            return self._sample_iter(sample_rate, chunk_size, out,
×
187
                                     function_lib, filters)
188

189
    def _sample_iter(self, sample_rate, chunk_size, out, function_lib,
9✔
190
                     filters):
191
        start = self.start
×
192
        start_n = 0
×
193
        if filters is not None:
×
194
            sos, initial = filters
×
195
            # zi = sosfilt_zi(sos)
196
            zi = np.zeros((sos.shape[0], 2))
×
197
        length = chunk_size / sample_rate
×
198
        while start < self.stop:
×
199
            if start + length > self.stop:
×
200
                length = self.stop - start
×
201
                stop = self.stop
×
202
                size = round((stop - start) * sample_rate)
×
203
            else:
204
                stop = start + length
×
205
                size = chunk_size
×
206
            x = np.linspace(start, stop, size, endpoint=False)
×
207

208
            if filters is None:
×
209
                if out is not None:
×
UNCOV
210
                    yield self.__call__(x,
×
211
                                        out=out[start_n:],
212
                                        function_lib=function_lib)
213
                else:
214
                    yield self.__call__(x, function_lib=function_lib)
×
215
            else:
UNCOV
216
                sig = self.__call__(x, function_lib=function_lib)
×
UNCOV
217
                if initial:
×
UNCOV
218
                    sig -= initial
×
219
                sig, zi = sosfilt(sos, sig, zi=zi)
×
220
                if initial:
×
221
                    sig += initial
×
222
                if out is not None:
×
UNCOV
223
                    out[start_n:start_n + size] = sig
×
224
                yield sig
×
225

UNCOV
226
            start = stop
×
227
            start_n += chunk_size
×
228

229
    @staticmethod
9✔
230
    def _tolist(bounds, seq, ret=None):
9✔
231
        if ret is None:
9✔
UNCOV
232
            ret = []
×
233
        ret.append(len(bounds))
9✔
234
        for seq, b in zip(seq, bounds):
9✔
235
            ret.append(b)
9✔
236
            tlist, amplist = seq
9✔
237
            ret.append(len(amplist))
9✔
238
            for t, amp in zip(tlist, amplist):
9✔
239
                ret.append(amp)
9✔
240
                mtlist, nlist = t
9✔
241
                ret.append(len(nlist))
9✔
242
                for fun, n in zip(mtlist, nlist):
9✔
243
                    ret.append(n)
9✔
244
                    ret.append(len(fun))
9✔
245
                    ret.extend(fun)
9✔
246
        return ret
9✔
247

248
    @staticmethod
9✔
249
    def _fromlist(l, pos=0):
9✔
250

251
        def _read(l, pos, size):
9✔
252
            try:
9✔
253
                return tuple(l[pos:pos + size]), pos + size
9✔
UNCOV
254
            except:
×
UNCOV
255
                raise ValueError('Invalid waveform format')
×
256

257
        (nseg, ), pos = _read(l, pos, 1)
9✔
258
        bounds = []
9✔
259
        seq = []
9✔
260
        for _ in range(nseg):
9✔
261
            (b, nsum), pos = _read(l, pos, 2)
9✔
262
            bounds.append(b)
9✔
263
            amp = []
9✔
264
            t = []
9✔
265
            for _ in range(nsum):
9✔
266
                (a, nmul), pos = _read(l, pos, 2)
9✔
267
                amp.append(a)
9✔
268
                nlst = []
9✔
269
                mt = []
9✔
270
                for _ in range(nmul):
9✔
271
                    (n, nfun), pos = _read(l, pos, 2)
9✔
272
                    nlst.append(n)
9✔
273
                    fun, pos = _read(l, pos, nfun)
9✔
274
                    mt.append(fun)
9✔
275
                t.append((tuple(mt), tuple(nlst)))
9✔
276
            seq.append((tuple(t), tuple(amp)))
9✔
277

278
        return tuple(bounds), tuple(seq), pos
9✔
279

280
    def tolist(self):
9✔
281
        l = [self.max, self.min, self.start, self.stop, self.sample_rate]
9✔
282
        if self.filters is None:
9✔
283
            l.append(None)
9✔
284
        else:
285
            sos, initial = self.filters
9✔
286
            sos = list(sos.reshape(-1))
9✔
287
            l.append(len(sos))
9✔
288
            l.extend(sos)
9✔
289
            l.append(initial)
9✔
290

291
        return self._tolist(self.bounds, self.seq, l)
9✔
292

293
    @classmethod
9✔
294
    def fromlist(cls, l):
9✔
295
        w = cls()
9✔
296
        pos = 6
9✔
297
        (w.max, w.min, w.start, w.stop, w.sample_rate, sos_size) = l[:pos]
9✔
298
        if sos_size is not None:
9✔
299
            sos = np.array(l[pos:pos + sos_size]).reshape(-1, 6)
9✔
300
            pos += sos_size
9✔
301
            initial = l[pos]
9✔
302
            pos += 1
9✔
303
            w.filters = sos, initial
9✔
304

305
        w.bounds, w.seq, pos = cls._fromlist(l, pos)
9✔
306
        return w
9✔
307

308
    def totree(self):
9✔
309
        if self.filters is None:
9✔
310
            header = (self.max, self.min, self.start, self.stop,
9✔
311
                      self.sample_rate, None)
312
        else:
313
            header = (self.max, self.min, self.start, self.stop,
9✔
314
                      self.sample_rate, self.filters)
315
        body = []
9✔
316

317
        for seq, b in zip(self.seq, self.bounds):
9✔
318
            tlist, amplist = seq
9✔
319
            new_seq = []
9✔
320
            for t, amp in zip(tlist, amplist):
9✔
321
                mtlist, nlist = t
9✔
322
                new_t = []
9✔
323
                for fun, n in zip(mtlist, nlist):
9✔
324
                    new_t.append((n, fun))
9✔
325
                new_seq.append((amp, tuple(new_t)))
9✔
326
            body.append((b, tuple(new_seq)))
9✔
327
        return header, tuple(body)
9✔
328

329
    @staticmethod
9✔
330
    def fromtree(tree):
9✔
331
        w = Waveform()
9✔
332
        header, body = tree
9✔
333

334
        (w.max, w.min, w.start, w.stop, w.sample_rate, w.filters) = header
9✔
335
        bounds = []
9✔
336
        seqs = []
9✔
337
        for b, seq in body:
9✔
338
            bounds.append(b)
9✔
339
            amp_list = []
9✔
340
            t_list = []
9✔
341
            for amp, t in seq:
9✔
342
                amp_list.append(amp)
9✔
343
                n_list = []
9✔
344
                mt_list = []
9✔
345
                for n, mt in t:
9✔
346
                    n_list.append(n)
9✔
347
                    mt_list.append(mt)
9✔
348
                t_list.append((tuple(mt_list), tuple(n_list)))
9✔
349
            seqs.append((tuple(t_list), tuple(amp_list)))
9✔
350
        w.bounds = tuple(bounds)
9✔
351
        w.seq = tuple(seqs)
9✔
352
        return w
9✔
353

354
    def simplify(self, eps=1e-15):
9✔
355
        seq = [simplify(self.seq[0], eps)]
9✔
356
        bounds = [self.bounds[0]]
9✔
357
        for expr, b in zip(self.seq[1:], self.bounds[1:]):
9✔
358
            expr = simplify(expr, eps)
9✔
359
            if expr == seq[-1]:
9✔
UNCOV
360
                seq.pop()
×
UNCOV
361
                bounds.pop()
×
362
            seq.append(expr)
9✔
363
            bounds.append(b)
9✔
364
        return Waveform(tuple(bounds), tuple(seq))
9✔
365

366
    def filter(self, low=0, high=inf, eps=1e-15):
9✔
UNCOV
367
        seq = []
×
UNCOV
368
        for expr in self.seq:
×
UNCOV
369
            seq.append(filter(expr, low, high, eps))
×
370
        return Waveform(self.bounds, tuple(seq))
×
371

372
    def _comb(self, other, oper):
9✔
373
        return Waveform(*merge_waveform(self.bounds, self.seq, other.bounds,
9✔
374
                                        other.seq, oper))
375

376
    def __pow__(self, n):
9✔
377
        return Waveform(self.bounds, tuple(pow(w, n) for w in self.seq))
9✔
378

379
    def __add__(self, other):
9✔
380
        if isinstance(other, Waveform):
9✔
381
            return self._comb(other, add)
9✔
382
        else:
383
            return self + const(other)
9✔
384

385
    def __radd__(self, v):
9✔
UNCOV
386
        return const(v) + self
×
387

388
    def __ior__(self, other):
9✔
UNCOV
389
        return self | other
×
390

391
    def __or__(self, other):
9✔
UNCOV
392
        if isinstance(other, (int, float, complex)):
×
UNCOV
393
            other = const(other)
×
UNCOV
394
        w = self.marker + other.marker
×
395

396
        def _or(a, b):
×
UNCOV
397
            if a != _zero or b != _zero:
×
UNCOV
398
                return _one
×
399
            else:
UNCOV
400
                return _zero
×
401

402
        return self._comb(other, _or)
×
403

404
    def __iand__(self, other):
9✔
UNCOV
405
        return self & other
×
406

407
    def __and__(self, other):
9✔
408
        if isinstance(other, (int, float, complex)):
×
UNCOV
409
            other = const(other)
×
410
        w = self.marker + other.marker
×
411

412
        def _and(a, b):
×
UNCOV
413
            if a != _zero and b != _zero:
×
UNCOV
414
                return _one
×
415
            else:
UNCOV
416
                return _zero
×
417

418
        return self._comb(other, _and)
×
419

420
    @property
9✔
421
    def marker(self):
9✔
422
        w = self.simplify()
×
423
        return Waveform(w.bounds,
×
424
                        tuple(_zero if s == _zero else _one for s in w.seq))
425

426
    def mask(self, edge=0):
9✔
UNCOV
427
        w = self.marker
×
428
        in_wave = w.seq[0] == _zero
×
UNCOV
429
        bounds = []
×
UNCOV
430
        seq = []
×
431

432
        if w.seq[0] == _zero:
×
433
            in_wave = False
×
UNCOV
434
            b = w.bounds[0] - edge
×
UNCOV
435
            bounds.append(b)
×
UNCOV
436
            seq.append(_zero)
×
437

438
        for b, s in zip(w.bounds[1:], w.seq[1:]):
×
439
            if not in_wave and s != _zero:
×
440
                in_wave = True
×
UNCOV
441
                bounds.append(b + edge)
×
442
                seq.append(_one)
×
443
            elif in_wave and s == _zero:
×
444
                in_wave = False
×
445
                b = b - edge
×
446
                if b > bounds[-1]:
×
UNCOV
447
                    bounds.append(b)
×
448
                    seq.append(_zero)
×
449
                else:
450
                    bounds.pop()
×
451
                    bounds.append(b)
×
452
        return Waveform(tuple(bounds), tuple(seq))
×
453

454
    def __mul__(self, other):
9✔
455
        if isinstance(other, Waveform):
9✔
456
            return self._comb(other, mul)
9✔
457
        else:
458
            return self * const(other)
×
459

460
    def __rmul__(self, v):
9✔
461
        return const(v) * self
9✔
462

463
    def __truediv__(self, other):
9✔
464
        if isinstance(other, Waveform):
9✔
UNCOV
465
            raise TypeError('division by waveform')
×
466
        else:
467
            return self * const(1 / other)
9✔
468

469
    def __neg__(self):
9✔
470
        return -1 * self
9✔
471

472
    def __sub__(self, other):
9✔
473
        return self + (-other)
9✔
474

475
    def __rsub__(self, v):
9✔
UNCOV
476
        return v + (-self)
×
477

478
    def __rshift__(self, time):
9✔
479
        return Waveform(
9✔
480
            tuple(round(bound + time, NDIGITS) for bound in self.bounds),
481
            tuple(shift(expr, time) for expr in self.seq))
482

483
    def __lshift__(self, time):
9✔
484
        return self >> (-time)
9✔
485

486
    @staticmethod
9✔
487
    def _merge_parts(
9✔
488
        parts: list[tuple[int, int, np.ndarray | int | float | complex]],
489
        out: list[tuple[int, int, np.ndarray | int | float | complex]]
490
    ) -> list[tuple[int, int, np.ndarray | int | float | complex]]:
491
        # TODO: merge parts
UNCOV
492
        raise NotImplementedError
×
493

494
    @staticmethod
9✔
495
    def _fill_parts(parts, out):
9✔
496
        for start, stop, part in parts:
9✔
497
            out[start:stop] += part
9✔
498

499
    def __call__(self,
9✔
500
                 x,
501
                 frag=False,
502
                 out=None,
503
                 accumulate=False,
504
                 function_lib=None):
505
        if function_lib is None:
9✔
506
            function_lib = _baseFunc
9✔
507
        if isinstance(x, (int, float, complex)):
9✔
UNCOV
508
            return self.__call__(np.array([x]), function_lib=function_lib)[0]
×
509
        parts, dtype = calc_parts(self.bounds, self.seq, x, function_lib,
9✔
510
                                  self.min, self.max)
511
        if not frag:
9✔
512
            if out is None:
9✔
513
                out = np.zeros_like(x, dtype=dtype)
9✔
UNCOV
514
            elif not accumulate:
×
UNCOV
515
                out *= 0
×
516
            self._fill_parts(parts, out)
9✔
517
        else:
518
            if out is None:
×
UNCOV
519
                return parts
×
520
            else:
UNCOV
521
                if not accumulate:
×
UNCOV
522
                    out.clear()
×
UNCOV
523
                    out.extend(parts)
×
524
                else:
525
                    self._merge_parts(parts, out)
×
526
        return out
9✔
527

528
    def __hash__(self):
9✔
529
        return hash((self.max, self.min, self.start, self.stop,
×
530
                     self.sample_rate, self.bounds, self.seq))
531

532
    def __eq__(self, o: object) -> bool:
9✔
533
        if isinstance(o, (int, float, complex)):
9✔
UNCOV
534
            return self == const(o)
×
535
        elif isinstance(o, Waveform):
9✔
536
            a = self.simplify()
9✔
537
            b = o.simplify()
9✔
538
            return a.seq == b.seq and a.bounds == b.bounds and (
9✔
539
                a.max, a.min, a.start, a.stop) == (b.max, b.min, b.start,
540
                                                   b.stop)
541
        else:
UNCOV
542
            return False
×
543

544
    def _repr_latex_(self):
9✔
UNCOV
545
        parts = []
×
UNCOV
546
        start = -np.inf
×
UNCOV
547
        for end, wav in zip(self.bounds, self.seq):
×
UNCOV
548
            e_str = _wav_latex(wav)
×
UNCOV
549
            start_str = _num_latex(start)
×
UNCOV
550
            end_str = _num_latex(end)
×
UNCOV
551
            parts.append(e_str + r",~~&t\in" + f"({start_str},{end_str}" +
×
552
                         (']' if end < np.inf else ')'))
UNCOV
553
            start = end
×
UNCOV
554
        if len(parts) == 1:
×
555
            expr = ''.join(['f(t)=', *parts[0].split('&')])
×
556
        else:
557
            expr = '\n'.join([
×
558
                r"f(t)=\begin{cases}", (r"\\" + '\n').join(parts),
559
                r"\end{cases}"
560
            ])
561
        return "$$\n{}\n$$".format(expr)
×
562

563
    def _play(self, time_unit, volume=1.0):
9✔
564
        import pyaudio
×
565

UNCOV
566
        CHUNK = 1024
×
567
        RATE = 48000
×
568

UNCOV
569
        dynamic_volume = 1.0
×
UNCOV
570
        amp = 2**15 * 0.999 * volume * dynamic_volume
×
571

UNCOV
572
        p = pyaudio.PyAudio()
×
UNCOV
573
        try:
×
574
            stream = p.open(format=pyaudio.paInt16,
×
575
                            channels=1,
576
                            rate=RATE,
577
                            output=True)
UNCOV
578
            try:
×
579
                for data in self.sample(sample_rate=RATE / time_unit,
×
580
                                        chunk_size=CHUNK):
UNCOV
581
                    lim = np.abs(data).max()
×
582
                    if lim > 0 and dynamic_volume > 1.0 / lim:
×
583
                        dynamic_volume = 1.0 / lim
×
584
                        amp = 2**15 * 0.99 * volume * dynamic_volume
×
UNCOV
585
                    data = (amp * data).astype(np.int16)
×
UNCOV
586
                    stream.write(bytes(data.data))
×
587
            finally:
588
                stream.stop_stream()
×
589
                stream.close()
×
590
        finally:
591
            p.terminate()
×
592

593
    def play(self, time_unit=1, volume=1.0):
9✔
594
        import multiprocessing as mp
×
595
        p = mp.Process(target=self._play,
×
596
                       args=(time_unit, volume),
597
                       daemon=True)
598
        p.start()
×
599

600

601
class WaveVStack(Waveform):
9✔
602

603
    def __init__(self, wlist: list[Waveform] = []):
9✔
604
        self.wlist = [(w.bounds, w.seq) for w in wlist]
9✔
605
        self.start = None
9✔
606
        self.stop = None
9✔
607
        self.sample_rate = None
9✔
608
        self.offset = 0
9✔
609
        self.shift = 0
9✔
610
        self.filters = None
9✔
611
        self.label = None
9✔
612
        self.function_lib = None
9✔
613

614
    def __call__(self, x, frag=False, out=None, function_lib=None):
9✔
615
        assert frag is False, 'WaveVStack does not support frag mode'
9✔
616
        out = np.full_like(x, self.offset, dtype=complex)
9✔
617
        if self.shift != 0:
9✔
618
            x = x - self.shift
9✔
619
        if function_lib is None:
9✔
620
            if self.function_lib is None:
9✔
621
                function_lib = _baseFunc
9✔
622
            else:
UNCOV
623
                function_lib = self.function_lib
×
624
        for bounds, seq in self.wlist:
9✔
625
            parts, dtype = calc_parts(bounds, seq, x, function_lib)
9✔
626
            self._fill_parts(parts, out)
9✔
627
        return out.real
9✔
628

629
    def tolist(self):
9✔
630
        l = [
9✔
631
            self.start,
632
            self.stop,
633
            self.offset,
634
            self.shift,
635
            self.sample_rate,
636
        ]
637
        if self.filters is None:
9✔
638
            l.append(None)
9✔
639
        else:
640
            sos, initial = self.filters
9✔
641
            sos = list(sos.reshape(-1))
9✔
642
            l.append(len(sos))
9✔
643
            l.extend(sos)
9✔
644
            l.append(initial)
9✔
645
        l.append(len(self.wlist))
9✔
646
        for bounds, seq in self.wlist:
9✔
647
            self._tolist(bounds, seq, l)
9✔
648
        return l
9✔
649

650
    @classmethod
9✔
651
    def fromlist(cls, l):
9✔
652
        w = cls()
9✔
653
        pos = 6
9✔
654
        w.start, w.stop, w.offset, w.shift, w.sample_rate, sos_size = l[:pos]
9✔
655
        if sos_size is not None:
9✔
656
            sos = np.array(l[pos:pos + sos_size]).reshape(-1, 6)
9✔
657
            pos += sos_size
9✔
658
            initial = l[pos]
9✔
659
            pos += 1
9✔
660
            w.filters = sos, initial
9✔
661
        n = l[pos]
9✔
662
        pos += 1
9✔
663
        for _ in range(n):
9✔
664
            bounds, seq, pos = cls._fromlist(l, pos)
9✔
665
            w.wlist.append((bounds, seq))
9✔
666
        return w
9✔
667

668
    def simplify(self, eps=1e-15):
9✔
669
        if not self.wlist:
9✔
670
            return zero()
9✔
671
        bounds, seq = wave_sum(self.wlist)
9✔
672
        wav = Waveform(bounds=bounds, seq=seq)
9✔
673
        if self.offset != 0:
9✔
UNCOV
674
            wav += self.offset
×
675
        if self.shift != 0:
9✔
UNCOV
676
            wav >>= self.shift
×
677
        wav = wav.simplify(eps)
9✔
678
        wav.start = self.start
9✔
679
        wav.stop = self.stop
9✔
680
        wav.sample_rate = self.sample_rate
9✔
681
        return wav
9✔
682

683
    @staticmethod
9✔
684
    def _rshift(wlist, time):
9✔
UNCOV
685
        if time == 0:
×
686
            return wlist
×
UNCOV
687
        return [(tuple(round(bound + time, NDIGITS) for bound in bounds),
×
688
                 tuple(shift(expr, time) for expr in seq))
689
                for bounds, seq in wlist]
690

691
    def __rshift__(self, time):
9✔
692
        ret = WaveVStack()
9✔
693
        ret.wlist = self.wlist
9✔
694
        ret.sample_rate = self.sample_rate
9✔
695
        ret.start = self.start
9✔
696
        ret.stop = self.stop
9✔
697
        ret.shift = self.shift + time
9✔
698
        ret.offset = self.offset
9✔
699
        return ret
9✔
700

701
    def __add__(self, other):
9✔
702
        ret = WaveVStack()
9✔
703
        ret.wlist.extend(self.wlist)
9✔
704
        if isinstance(other, WaveVStack):
9✔
UNCOV
705
            if other.shift != self.shift:
×
UNCOV
706
                ret.wlist = self._rshift(ret.wlist, self.shift)
×
UNCOV
707
                ret.wlist.extend(self._rshift(other.wlist, other.shift))
×
708
            else:
UNCOV
709
                ret.wlist.extend(other.wlist)
×
UNCOV
710
            ret.offset = self.offset + other.offset
×
711
        elif isinstance(other, Waveform):
9✔
712
            other <<= self.shift
9✔
713
            ret.wlist.append((other.bounds, other.seq))
9✔
714
        else:
715
            # ret.wlist.append(((+inf, ), (_const(1.0 * other), )))
716
            ret.offset += other
9✔
717
        return ret
9✔
718

719
    def __radd__(self, v):
9✔
720
        return self + v
×
721

722
    def __mul__(self, other):
9✔
723
        if isinstance(other, Waveform):
9✔
724
            other = other.simplify() << self.shift
9✔
725
            ret = WaveVStack([Waveform(*w) * other for w in self.wlist])
9✔
726
            if self.offset != 0:
9✔
UNCOV
727
                w = other * self.offset
×
UNCOV
728
                ret.wlist.append((w.bounds, w.seq))
×
729
            return ret
9✔
730
        else:
UNCOV
731
            ret = WaveVStack([Waveform(*w) * other for w in self.wlist])
×
UNCOV
732
            ret.offset = self.offset * other
×
UNCOV
733
            return ret
×
734

735
    def __rmul__(self, v):
9✔
UNCOV
736
        return self * v
×
737

738
    def __eq__(self, other):
9✔
UNCOV
739
        if self.wlist:
×
UNCOV
740
            return False
×
741
        else:
742
            return zero() == other
×
743

744
    def _repr_latex_(self):
9✔
UNCOV
745
        return r"\sum_{i=1}^{" + f"{len(self.wlist)}" + r"}" + r"f_i(t)"
×
746

747
    def __getstate__(self) -> tuple:
9✔
748
        function_lib = self.function_lib
9✔
749
        if function_lib:
9✔
750
            try:
×
UNCOV
751
                import dill
×
752
                function_lib = dill.dumps(function_lib)
×
UNCOV
753
            except:
×
UNCOV
754
                function_lib = None
×
755
        return (self.wlist, self.start, self.stop, self.sample_rate,
9✔
756
                self.offset, self.shift, self.filters, self.label,
757
                function_lib)
758

759
    def __setstate__(self, state: tuple) -> None:
9✔
760
        (self.wlist, self.start, self.stop, self.sample_rate, self.offset,
9✔
761
         self.shift, self.filters, self.label, function_lib) = state
762
        if function_lib:
9✔
763
            try:
×
764
                import dill
×
UNCOV
765
                function_lib = dill.loads(function_lib)
×
UNCOV
766
            except:
×
UNCOV
767
                function_lib = None
×
768
        self.function_lib = function_lib
9✔
769

770

771
def play(data, rate=48000):
9✔
UNCOV
772
    import io
×
773

774
    import pyaudio
×
775

776
    CHUNK = 1024
×
777

UNCOV
778
    max_amp = np.max(np.abs(data))
×
779

UNCOV
780
    if max_amp > 1:
×
UNCOV
781
        data /= max_amp
×
782

UNCOV
783
    data = np.array(2**15 * 0.999 * data, dtype=np.int16)
×
784
    buff = io.BytesIO(data.data)
×
UNCOV
785
    p = pyaudio.PyAudio()
×
786

UNCOV
787
    try:
×
788
        stream = p.open(format=pyaudio.paInt16,
×
789
                        channels=1,
790
                        rate=rate,
791
                        output=True)
UNCOV
792
        try:
×
793
            while True:
×
794
                data = buff.read(CHUNK)
×
795
                if data:
×
UNCOV
796
                    stream.write(data)
×
797
                else:
798
                    break
×
799
        finally:
UNCOV
800
            stream.stop_stream()
×
UNCOV
801
            stream.close()
×
802
    finally:
803
        p.terminate()
×
804

805

806
_zero_waveform = Waveform()
9✔
807
_one_waveform = Waveform(seq=(_one, ))
9✔
808

809

810
def zero():
9✔
811
    return _zero_waveform
9✔
812

813

814
def one():
9✔
UNCOV
815
    return _one_waveform
×
816

817

818
def const(c):
9✔
819
    return Waveform(seq=(_const(1.0 * c), ))
9✔
820

821

822
# register base function
823
def _format_LINEAR(shift, *args):
9✔
UNCOV
824
    if shift != 0:
×
825
        shift = _num_latex(-shift)
×
UNCOV
826
        if shift[0] == '-':
×
UNCOV
827
            return f"(t{shift})"
×
828
        else:
UNCOV
829
            return f"(t+{shift})"
×
830
    else:
UNCOV
831
        return 't'
×
832

833

834
def _format_GAUSSIAN(shift, *args):
9✔
835
    sigma = _num_latex(args[0] / np.sqrt(2))
×
836
    shift = _num_latex(-shift)
×
837
    if shift != '0':
×
UNCOV
838
        if shift[0] != '-':
×
839
            shift = '+' + shift
×
UNCOV
840
        if sigma == '1':
×
841
            return ('\\exp\\left[-\\frac{\\left(t' + shift +
×
842
                    '\\right)^2}{2}\\right]')
843
        else:
UNCOV
844
            return ('\\exp\\left[-\\frac{1}{2}\\left(\\frac{t' + shift + '}{' +
×
845
                    sigma + '}\\right)^2\\right]')
846
    else:
847
        if sigma == '1':
×
848
            return ('\\exp\\left(-\\frac{t^2}{2}\\right)')
×
849
        else:
850
            return ('\\exp\\left[-\\frac{1}{2}\\left(\\frac{t}{' + sigma +
×
851
                    '}\\right)^2\\right]')
852

853

854
def _format_SINC(shift, *args):
9✔
UNCOV
855
    shift = _num_latex(-shift)
×
UNCOV
856
    bw = _num_latex(args[0])
×
857
    if shift != '0':
×
858
        if shift[0] != '-':
×
UNCOV
859
            shift = '+' + shift
×
860
        if bw == '1':
×
UNCOV
861
            return '\\mathrm{sinc}(t' + shift + ')'
×
862
        else:
UNCOV
863
            return '\\mathrm{sinc}[' + bw + '(t' + shift + ')]'
×
864
    else:
865
        if bw == '1':
×
866
            return '\\mathrm{sinc}(t)'
×
867
        else:
868
            return '\\mathrm{sinc}(' + bw + 't)'
×
869

870

871
def _format_COSINE(shift, *args):
9✔
UNCOV
872
    freq = args[0] / 2 / np.pi
×
873
    phase = -shift * freq
×
UNCOV
874
    freq = _num_latex(freq)
×
875
    if freq == '1':
×
876
        freq = ''
×
UNCOV
877
    phase = _num_latex(phase)
×
878
    if phase == '0':
×
UNCOV
879
        phase = ''
×
UNCOV
880
    elif phase[0] != '-':
×
UNCOV
881
        phase = '+' + phase
×
882
    if phase != '':
×
883
        return f'\\cos\\left[2\\pi\\left({freq}t{phase}\\right)\\right]'
×
884
    elif freq != '':
×
885
        return f'\\cos\\left(2\\pi\\times {freq}t\\right)'
×
886
    else:
887
        return '\\cos\\left(2\\pi t\\right)'
×
888

889

890
def _format_ERF(shift, *args):
9✔
891
    if shift > 0:
×
892
        return '\\mathrm{erf}(\\frac{t-' + f"{_num_latex(shift)}" + '}{' + f'{args[0]:g}' + '})'
×
893
    elif shift < 0:
×
894
        return '\\mathrm{erf}(\\frac{t+' + f"{_num_latex(-shift)}" + '}{' + f'{args[0]:g}' + '})'
×
895
    else:
UNCOV
896
        return '\\mathrm{erf}(\\frac{t}{' + f'{args[0]:g}' + '})'
×
897

898

899
def _format_COSH(shift, *args):
9✔
UNCOV
900
    if shift > 0:
×
901
        return '\\cosh(\\frac{t-' + f"{_num_latex(shift)}" + '}{' + f'{1/args[0]:g}' + '})'
×
902
    elif shift < 0:
×
903
        return '\\cosh(\\frac{t+' + f"{_num_latex(-shift)}" + '}{' + f'{1/args[0]:g}' + '})'
×
904
    else:
UNCOV
905
        return '\\cosh(\\frac{t}{' + f'{1/args[0]:g}' + '})'
×
906

907

908
def _format_SINH(shift, *args):
9✔
UNCOV
909
    if shift > 0:
×
910
        return '\\sinh(\\frac{t-' + f"{_num_latex(shift)}" + '}{' + f'{args[0]:g}' + '})'
×
911
    elif shift < 0:
×
912
        return '\\sinh(\\frac{t+' + f"{_num_latex(-shift)}" + '}{' + f'{args[0]:g}' + '})'
×
913
    else:
UNCOV
914
        return '\\sinh(\\frac{t}{' + f'{args[0]:g}' + '})'
×
915

916

917
def _format_EXP(shift, *args):
9✔
UNCOV
918
    if _num_latex(shift) and shift > 0:
×
919
        return '\\exp\\left(-' + f'{args[0]:g}' + '\\left(t-' + f"{_num_latex(shift)}" + '\\right)\\right)'
×
920
    elif _num_latex(-shift) and shift < 0:
×
921
        return '\\exp\\left(-' + f'{args[0]:g}' + '\\left(t+' + f"{_num_latex(-shift)}" + '\\right)\\right)'
×
922
    else:
UNCOV
923
        return '\\exp\\left(-' + f'{args[0]:g}' + 't\\right)'
×
924

925

926
def _format_DRAG(shift, *args):
9✔
UNCOV
927
    return f"DRAG(...)"
×
928

929

930
registerBaseFuncLatex(LINEAR, _format_LINEAR)
9✔
931
registerBaseFuncLatex(GAUSSIAN, _format_GAUSSIAN)
9✔
932
registerBaseFuncLatex(ERF, _format_ERF)
9✔
933
registerBaseFuncLatex(COS, _format_COSINE)
9✔
934
registerBaseFuncLatex(SINC, _format_SINC)
9✔
935
registerBaseFuncLatex(EXP, _format_EXP)
9✔
936
registerBaseFuncLatex(COSH, _format_COSH)
9✔
937
registerBaseFuncLatex(SINH, _format_SINH)
9✔
938
registerBaseFuncLatex(DRAG, _format_DRAG)
9✔
939

940

941
def D(wav):
9✔
942
    """derivative
943
    """
UNCOV
944
    return Waveform(bounds=wav.bounds, seq=tuple(_D(x) for x in wav.seq))
×
945

946

947
def convolve(a, b):
9✔
UNCOV
948
    pass
×
949

950

951
def sign():
9✔
UNCOV
952
    return Waveform(bounds=(0, +inf), seq=(_const(-1), _one))
×
953

954

955
def step(edge, type='erf'):
9✔
956
    """
957
    type: "erf", "cos", "linear"
958
    """
959
    if edge == 0:
9✔
960
        return Waveform(bounds=(0, +inf), seq=(_zero, _one))
9✔
961
    if type == 'cos':
9✔
962
        rise = add(_half,
×
963
                   mul(_half, basic_wave(COS, pi / edge, shift=0.5 * edge)))
UNCOV
964
        return Waveform(bounds=(round(-edge / 2,
×
965
                                      NDIGITS), round(edge / 2,
966
                                                      NDIGITS), +inf),
967
                        seq=(_zero, rise, _one))
968
    elif type == 'linear':
9✔
969
        rise = add(_half, mul(_const(1 / edge), basic_wave(LINEAR)))
9✔
970
        return Waveform(bounds=(round(-edge / 2,
9✔
971
                                      NDIGITS), round(edge / 2,
972
                                                      NDIGITS), +inf),
973
                        seq=(_zero, rise, _one))
974
    else:
UNCOV
975
        std_sq2 = edge / 5
×
976
        # rise = add(_half, mul(_half, basic_wave(ERF, std_sq2)))
UNCOV
977
        rise = ((((), ()), (((ERF, std_sq2, 0), ), (1, ))), (0.5, 0.5))
×
UNCOV
978
        return Waveform(bounds=(-round(edge, NDIGITS), round(edge,
×
979
                                                             NDIGITS), +inf),
980
                        seq=(_zero, rise, _one))
981

982

983
def square(width, edge=0, type='erf'):
9✔
984
    if width <= 0:
9✔
985
        return zero()
×
986
    if edge == 0:
9✔
987
        return Waveform(bounds=(round(-0.5 * width,
9✔
988
                                      NDIGITS), round(0.5 * width,
989
                                                      NDIGITS), +inf),
990
                        seq=(_zero, _one, _zero))
991
    else:
992
        return ((step(edge, type=type) << width / 2) -
9✔
993
                (step(edge, type=type) >> width / 2))
994

995

996
def gaussian(width, plateau=0.0):
9✔
997
    if width <= 0 and plateau <= 0.0:
9✔
UNCOV
998
        return zero()
×
999
    # width is two times FWHM
1000
    # std_sq2 = width / (4 * np.sqrt(np.log(2)))
1001
    std_sq2 = width / 3.3302184446307908
9✔
1002
    # std is set to give total pulse area same as a square
1003
    # std_sq2 = width/np.sqrt(np.pi)
1004
    if round(0.5 * plateau, NDIGITS) <= 0.0:
9✔
1005
        return Waveform(bounds=(round(-0.75 * width,
9✔
1006
                                      NDIGITS), round(0.75 * width,
1007
                                                      NDIGITS), +inf),
1008
                        seq=(_zero, basic_wave(GAUSSIAN, std_sq2), _zero))
1009
    else:
UNCOV
1010
        return Waveform(bounds=(round(-0.75 * width - 0.5 * plateau,
×
1011
                                      NDIGITS), round(-0.5 * plateau, NDIGITS),
1012
                                round(0.5 * plateau, NDIGITS),
1013
                                round(0.75 * width + 0.5 * plateau,
1014
                                      NDIGITS), +inf),
1015
                        seq=(_zero,
1016
                             basic_wave(GAUSSIAN,
1017
                                        std_sq2,
1018
                                        shift=-0.5 * plateau), _one,
1019
                             basic_wave(GAUSSIAN, std_sq2,
1020
                                        shift=0.5 * plateau), _zero))
1021

1022

1023
def cos(w, phi=0):
9✔
1024
    if w == 0:
9✔
UNCOV
1025
        return const(np.cos(phi))
×
1026
    if w < 0:
9✔
UNCOV
1027
        phi = -phi
×
UNCOV
1028
        w = -w
×
1029
    return Waveform(seq=(basic_wave(COS, w, shift=-phi / w), ))
9✔
1030

1031

1032
def sin(w, phi=0):
9✔
1033
    if w == 0:
9✔
UNCOV
1034
        return const(np.sin(phi))
×
1035
    if w < 0:
9✔
UNCOV
1036
        phi = -phi + pi
×
1037
        w = -w
×
1038
    return Waveform(seq=(basic_wave(COS, w, shift=(pi / 2 - phi) / w), ))
9✔
1039

1040

1041
def exp(alpha):
9✔
1042
    if isinstance(alpha, complex):
9✔
1043
        if alpha.real == 0:
9✔
1044
            return cos(alpha.imag) + 1j * sin(alpha.imag)
×
1045
        else:
1046
            return exp(alpha.real) * (cos(alpha.imag) + 1j * sin(alpha.imag))
9✔
1047
    else:
1048
        return Waveform(seq=(basic_wave(EXP, alpha), ))
9✔
1049

1050

1051
def sinc(bw):
9✔
UNCOV
1052
    if bw <= 0:
×
UNCOV
1053
        return zero()
×
1054
    width = 100 / bw
×
UNCOV
1055
    return Waveform(bounds=(round(-0.5 * width,
×
1056
                                  NDIGITS), round(0.5 * width, NDIGITS), +inf),
1057
                    seq=(_zero, basic_wave(SINC, bw), _zero))
1058

1059

1060
def cosPulse(width, plateau=0.0):
9✔
1061
    # cos = basic_wave(COS, 2*np.pi/width)
1062
    # pulse = mul(add(cos, _one), _half)
1063
    if round(0.5 * plateau, NDIGITS) > 0:
×
1064
        return square(plateau + 0.5 * width, edge=0.5 * width, type='cos')
×
1065
    if width <= 0:
×
UNCOV
1066
        return zero()
×
UNCOV
1067
    pulse = ((((), ()), (((COS, 6.283185307179586 / width, 0), ), (1, ))),
×
1068
             (0.5, 0.5))
UNCOV
1069
    return Waveform(bounds=(round(-0.5 * width,
×
1070
                                  NDIGITS), round(0.5 * width, NDIGITS), +inf),
1071
                    seq=(_zero, pulse, _zero))
1072

1073

1074
def hanning(width, plateau=0.0):
9✔
1075
    return cosPulse(width, plateau=plateau)
×
1076

1077

1078
def cosh(w):
9✔
1079
    return Waveform(seq=(basic_wave(COSH, w), ))
×
1080

1081

1082
def sinh(w):
9✔
UNCOV
1083
    return Waveform(seq=(basic_wave(SINH, w), ))
×
1084

1085

1086
def coshPulse(width, eps=1.0, plateau=0.0):
9✔
1087
    """Cosine hyperbolic pulse with the following im
1088

1089
    pulse edge shape:
1090
            cosh(eps / 2) - cosh(eps * t / T)
1091
    f(t) = -----------------------------------
1092
                  cosh(eps / 2) - 1
1093
    where T is the pulse width and eps is the pulse edge steepness.
1094
    The pulse is defined for t in [-T/2, T/2].
1095

1096
    In case of plateau > 0, the pulse is defined as:
1097
           | f(t + plateau/2)   if t in [-T/2 - plateau/2, - plateau/2]
1098
    g(t) = | 1                  if t in [-plateau/2, plateau/2]
1099
           | f(t - plateau/2)   if t in [plateau/2, T/2 + plateau/2]
1100

1101
    Parameters
1102
    ----------
1103
    width : float
1104
        Pulse width.
1105
    eps : float
1106
        Pulse edge steepness.
1107
    plateau : float
1108
        Pulse plateau.
1109
    """
UNCOV
1110
    if width <= 0 and plateau <= 0:
×
UNCOV
1111
        return zero()
×
UNCOV
1112
    w = eps / width
×
UNCOV
1113
    A = np.cosh(eps / 2)
×
1114

UNCOV
1115
    if plateau == 0.0 or round(-0.5 * plateau, NDIGITS) == round(
×
1116
            0.5 * plateau, NDIGITS):
UNCOV
1117
        pulse = ((((), ()), (((COSH, w, 0), ), (1, ))), (A / (A - 1),
×
1118
                                                         -1 / (A - 1)))
UNCOV
1119
        return Waveform(bounds=(round(-0.5 * width,
×
1120
                                      NDIGITS), round(0.5 * width,
1121
                                                      NDIGITS), +inf),
1122
                        seq=(_zero, pulse, _zero))
1123
    else:
UNCOV
1124
        raising = ((((), ()), (((COSH, w, -0.5 * plateau), ), (1, ))),
×
1125
                   (A / (A - 1), -1 / (A - 1)))
UNCOV
1126
        falling = ((((), ()), (((COSH, w, 0.5 * plateau), ), (1, ))),
×
1127
                   (A / (A - 1), -1 / (A - 1)))
UNCOV
1128
        return Waveform(bounds=(round(-0.5 * width - 0.5 * plateau,
×
1129
                                      NDIGITS), round(-0.5 * plateau, NDIGITS),
1130
                                round(0.5 * plateau, NDIGITS),
1131
                                round(0.5 * width + 0.5 * plateau,
1132
                                      NDIGITS), +inf),
1133
                        seq=(_zero, raising, _one, falling, _zero))
1134

1135

1136
def general_cosine(duration, *arg):
9✔
UNCOV
1137
    wav = zero()
×
1138
    arg = np.asarray(arg)
×
UNCOV
1139
    arg /= arg[::2].sum()
×
UNCOV
1140
    for i, a in enumerate(arg, start=1):
×
UNCOV
1141
        wav += a / 2 * (1 - (-1)**i * cos(i * 2 * pi / duration))
×
UNCOV
1142
    return wav * square(duration)
×
1143

1144

1145
def slepian(duration, *arg):
9✔
UNCOV
1146
    wav = zero()
×
1147
    arg = np.asarray(arg)
×
1148
    arg /= arg[::2].sum()
×
1149
    for i, a in enumerate(arg, start=1):
×
1150
        wav += a / 2 * (1 - (-1)**i * cos(i * 2 * pi / duration))
×
1151
    return wav * square(duration)
×
1152

1153

1154
def _poly(*a):
9✔
1155
    """
1156
    a[0] + a[1] * t + a[2] * t**2 + ...
1157
    """
1158
    t = []
9✔
1159
    amp = []
9✔
1160
    if a[0] != 0:
9✔
1161
        t.append(((), ()))
9✔
1162
        amp.append(a[0])
9✔
1163
    for n, a_ in enumerate(a[1:], start=1):
9✔
1164
        if a_ != 0:
9✔
1165
            t.append((((LINEAR, 0), ), (n, )))
9✔
1166
            amp.append(a_)
9✔
1167
    return tuple(t), tuple(a)
9✔
1168

1169

1170
def poly(a):
9✔
1171
    """
1172
    a[0] + a[1] * t + a[2] * t**2 + ...
1173
    """
1174
    return Waveform(seq=(_poly(*a), ))
9✔
1175

1176

1177
def t():
9✔
UNCOV
1178
    return Waveform(seq=((((LINEAR, 0), ), (1, )), (1, )))
×
1179

1180

1181
def drag(freq, width, plateau=0, delta=0, block_freq=None, phase=0, t0=0):
9✔
1182
    phase += pi * delta * (width + plateau)
9✔
1183
    if plateau <= 0:
9✔
1184
        return Waveform(seq=(_zero,
9✔
1185
                             basic_wave(DRAG, t0, freq, width, delta,
1186
                                        block_freq, phase), _zero),
1187
                        bounds=(round(t0, NDIGITS), round(t0 + width,
1188
                                                          NDIGITS), +inf))
UNCOV
1189
    elif width <= 0:
×
UNCOV
1190
        w = 2 * pi * (freq + delta)
×
UNCOV
1191
        return Waveform(
×
1192
            seq=(_zero,
1193
                 basic_wave(COS, w,
1194
                            shift=(phase + 2 * pi * delta * t0) / w), _zero),
1195
            bounds=(round(t0, NDIGITS), round(t0 + plateau, NDIGITS), +inf))
1196
    else:
UNCOV
1197
        w = 2 * pi * (freq + delta)
×
UNCOV
1198
        return Waveform(
×
1199
            seq=(_zero,
1200
                 basic_wave(DRAG, t0, freq, width, delta, block_freq, phase),
1201
                 basic_wave(COS, w, shift=(phase + 2 * pi * delta * t0) / w),
1202
                 basic_wave(DRAG, t0 + plateau, freq, width, delta, block_freq,
1203
                            phase - 2 * pi * delta * plateau), _zero),
1204
            bounds=(round(t0, NDIGITS), round(t0 + width / 2, NDIGITS),
1205
                    round(t0 + width / 2 + plateau,
1206
                          NDIGITS), round(t0 + width + plateau,
1207
                                          NDIGITS), +inf))
1208

1209

1210
def chirp(f0, f1, T, phi0=0, type='linear'):
9✔
1211
    """
1212
    A chirp is a signal in which the frequency increases (up-chirp)
1213
    or decreases (down-chirp) with time. In some sources, the term
1214
    chirp is used interchangeably with sweep signal.
1215

1216
    type: "linear", "exponential", "hyperbolic"
1217
    """
1218
    if f0 == f1:
9✔
UNCOV
1219
        return sin(f0, phi0)
×
1220
    if T <= 0:
9✔
UNCOV
1221
        raise ValueError('T must be positive')
×
1222

1223
    if type == 'linear':
9✔
1224
        # f(t) = f1 * (t/T) + f0 * (1 - t/T)
1225
        return Waveform(bounds=(0, round(T, NDIGITS), +inf),
9✔
1226
                        seq=(_zero, basic_wave(LINEARCHIRP, f0, f1, T,
1227
                                               phi0), _zero))
1228
    elif type in ['exp', 'exponential', 'geometric']:
9✔
1229
        # f(t) = f0 * (f1/f0) ** (t/T)
1230
        if f0 == 0:
9✔
1231
            raise ValueError('f0 must be non-zero')
×
1232
        alpha = np.log(f1 / f0) / T
9✔
1233
        return Waveform(bounds=(0, round(T, NDIGITS), +inf),
9✔
1234
                        seq=(_zero,
1235
                             basic_wave(EXPONENTIALCHIRP, f0, alpha,
1236
                                        phi0), _zero))
1237
    elif type in ['hyperbolic', 'hyp']:
9✔
1238
        # f(t) = f0 * f1 / (f0 * (t/T) + f1 * (1-t/T))
1239
        if f0 * f1 == 0:
9✔
UNCOV
1240
            return const(np.sin(phi0))
×
1241
        k = (f0 - f1) / (f1 * T)
9✔
1242
        return Waveform(bounds=(0, round(T, NDIGITS), +inf),
9✔
1243
                        seq=(_zero, basic_wave(HYPERBOLICCHIRP, f0, k,
1244
                                               phi0), _zero))
1245
    else:
UNCOV
1246
        raise ValueError(f'unknown type {type}')
×
1247

1248

1249
def interp(x, y):
9✔
1250
    seq, bounds = [_zero], [x[0]]
×
UNCOV
1251
    for x1, x2, y1, y2 in zip(x[:-1], x[1:], y[:-1], y[1:]):
×
UNCOV
1252
        if x2 == x1:
×
UNCOV
1253
            continue
×
UNCOV
1254
        seq.append(
×
1255
            add(
1256
                mul(_const((y2 - y1) / (x2 - x1)), basic_wave(LINEAR,
1257
                                                              shift=x1)),
1258
                _const(y1)))
UNCOV
1259
        bounds.append(x2)
×
1260
    bounds.append(inf)
×
1261
    seq.append(_zero)
×
1262
    return Waveform(seq=tuple(seq),
×
1263
                    bounds=tuple(round(b, NDIGITS)
1264
                                 for b in bounds)).simplify()
1265

1266

1267
def cut(wav, start=None, stop=None, head=None, tail=None, min=None, max=None):
9✔
UNCOV
1268
    offset = 0
×
1269
    if start is not None and head is not None:
×
1270
        offset = head - wav(np.array([1.0 * start]))[0]
×
1271
    elif stop is not None and tail is not None:
×
1272
        offset = tail - wav(np.array([1.0 * stop]))[0]
×
UNCOV
1273
    wav = wav + offset
×
1274

UNCOV
1275
    if start is not None:
×
UNCOV
1276
        wav = wav * (step(0) >> start)
×
UNCOV
1277
    if stop is not None:
×
1278
        wav = wav * ((1 - step(0)) >> stop)
×
1279
    if min is not None:
×
1280
        wav.min = min
×
1281
    if max is not None:
×
1282
        wav.max = max
×
1283
    return wav
×
1284

1285

1286
def function(fun, *args, start=None, stop=None):
9✔
1287
    TYPEID = registerBaseFunc(fun)
×
1288
    seq = (basic_wave(TYPEID, *args), )
×
1289
    wav = Waveform(seq=seq)
×
1290
    if start is not None:
×
1291
        wav = wav * (step(0) >> start)
×
1292
    if stop is not None:
×
1293
        wav = wav * ((1 - step(0)) >> stop)
×
UNCOV
1294
    return wav
×
1295

1296

1297
def samplingPoints(start, stop, points):
9✔
1298
    return Waveform(bounds=(round(start, NDIGITS), round(stop, NDIGITS), inf),
×
1299
                    seq=(_zero, basic_wave(INTERP, start, stop,
1300
                                           tuple(points)), _zero))
1301

1302

1303
def mixing(I,
9✔
1304
           Q=None,
1305
           *,
1306
           phase=0.0,
1307
           freq=0.0,
1308
           ratioIQ=1.0,
1309
           phaseDiff=0.0,
1310
           block_freq=None,
1311
           DRAGScaling=None):
1312
    """SSB or envelope mixing
1313
    """
UNCOV
1314
    if Q is None:
×
UNCOV
1315
        I = I
×
UNCOV
1316
        Q = zero()
×
1317

UNCOV
1318
    w = 2 * pi * freq
×
UNCOV
1319
    if freq != 0.0:
×
1320
        # SSB mixing
UNCOV
1321
        Iout = I * cos(w, -phase) + Q * sin(w, -phase)
×
UNCOV
1322
        Qout = -I * sin(w, -phase + phaseDiff) + Q * cos(w, -phase + phaseDiff)
×
1323
    else:
1324
        # envelope mixing
1325
        Iout = I * np.cos(-phase) + Q * np.sin(-phase)
×
1326
        Qout = -I * np.sin(-phase) + Q * np.cos(-phase)
×
1327

1328
    # apply DRAG
1329
    if block_freq is not None and block_freq != freq:
×
UNCOV
1330
        a = block_freq / (block_freq - freq)
×
1331
        b = 1 / (block_freq - freq)
×
1332
        I = a * Iout + b / (2 * pi) * D(Qout)
×
UNCOV
1333
        Q = a * Qout - b / (2 * pi) * D(Iout)
×
UNCOV
1334
        Iout, Qout = I, Q
×
1335
    elif DRAGScaling is not None and DRAGScaling != 0:
×
1336
        # 2 * pi * scaling * (freq - block_freq) = 1
UNCOV
1337
        I = (1 - w * DRAGScaling) * Iout - DRAGScaling * D(Qout)
×
UNCOV
1338
        Q = (1 - w * DRAGScaling) * Qout + DRAGScaling * D(Iout)
×
1339
        Iout, Qout = I, Q
×
1340

1341
    Qout = ratioIQ * Qout
×
1342

1343
    return Iout, Qout
×
1344

1345

1346
__all__ = [
9✔
1347
    'D', 'Waveform', 'chirp', 'const', 'cos', 'cosh', 'coshPulse', 'cosPulse',
1348
    'cut', 'drag', 'exp', 'function', 'gaussian', 'general_cosine', 'hanning',
1349
    'interp', 'mixing', 'one', 'poly', 'registerBaseFunc',
1350
    'registerDerivative', 'samplingPoints', 'sign', 'sin', 'sinc', 'sinh',
1351
    'square', 'step', 't', 'zero'
1352
]
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc