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

feihoo87 / waveforms / 12617451172

05 Jan 2025 07:02AM UTC coverage: 55.908% (+37.3%) from 18.563%
12617451172

push

github

feihoo87
v2.0.0

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

11 existing lines in 2 files now uncovered.

653 of 1168 relevant lines covered (55.91%)

5.03 hits per line

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

46.74
/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
    @staticmethod
9✔
131
    def _begin(bounds, seq):
9✔
132
        for i, s in enumerate(seq):
×
133
            if s is not _zero:
×
134
                if i == 0:
×
135
                    return -inf
×
136
                return bounds[i - 1]
×
137
        return inf
×
138

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

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

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

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

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

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

228
            start = stop
×
229
            start_n += chunk_size
×
230

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

250
    @staticmethod
9✔
251
    def _fromlist(l, pos=0):
9✔
252

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

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

280
        return tuple(bounds), tuple(seq), pos
9✔
281

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

293
        return self._tolist(self.bounds, self.seq, l)
9✔
294

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

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

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

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

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

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

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

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

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

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

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

387
    def __radd__(self, v):
9✔
388
        return const(v) + self
×
389

390
    def __ior__(self, other):
9✔
391
        return self | other
×
392

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

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

404
        return self._comb(other, _or)
×
405

406
    def __iand__(self, other):
9✔
407
        return self & other
×
408

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

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

420
        return self._comb(other, _and)
×
421

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

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

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

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

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

462
    def __rmul__(self, v):
9✔
463
        return const(v) * self
9✔
464

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

471
    def __neg__(self):
9✔
472
        return -1 * self
9✔
473

474
    def __sub__(self, other):
9✔
475
        return self + (-other)
9✔
476

477
    def __rsub__(self, v):
9✔
478
        return v + (-self)
×
479

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

485
    def __lshift__(self, time):
9✔
486
        return self >> (-time)
9✔
487

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

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

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

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

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

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

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

568
        CHUNK = 1024
×
569
        RATE = 48000
×
570

571
        dynamic_volume = 1.0
×
572
        amp = 2**15 * 0.999 * volume * dynamic_volume
×
573

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

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

602

603
class WaveVStack(Waveform):
9✔
604

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

616
    def __begin(self):
9✔
617
        if self.wlist:
×
618
            v = [self._begin(bounds, seq) for bounds, seq in self.wlist]
×
619
            return min(v)
×
620
        else:
621
            return -inf
×
622

623
    def __end(self):
9✔
624
        if self.wlist:
×
625
            v = [self._end(bounds, seq) for bounds, seq in self.wlist]
×
626
            return max(v)
×
627
        else:
628
            return inf
×
629

630
    @property
9✔
631
    def begin(self):
9✔
632
        if self.start is None:
×
633
            return self.__begin()
×
634
        else:
635
            return max(self.start, self.__begin())
×
636

637
    @property
9✔
638
    def end(self):
9✔
639
        if self.stop is None:
×
640
            return self.__end()
×
641
        else:
642
            return min(self.stop, self.__end())
×
643

644
    def __call__(self, x, frag=False, out=None, function_lib=None):
9✔
645
        assert frag is False, 'WaveVStack does not support frag mode'
9✔
646
        out = np.full_like(x, self.offset, dtype=complex)
9✔
647
        if self.shift != 0:
9✔
648
            x = x - self.shift
9✔
649
        if function_lib is None:
9✔
650
            if self.function_lib is None:
9✔
651
                function_lib = _baseFunc
9✔
652
            else:
653
                function_lib = self.function_lib
×
654
        for bounds, seq in self.wlist:
9✔
655
            parts, dtype = calc_parts(bounds, seq, x, function_lib)
9✔
656
            self._fill_parts(parts, out)
9✔
657
        return out.real
9✔
658

659
    def tolist(self):
9✔
660
        l = [
9✔
661
            self.start,
662
            self.stop,
663
            self.offset,
664
            self.shift,
665
            self.sample_rate,
666
        ]
667
        if self.filters is None:
9✔
668
            l.append(None)
9✔
669
        else:
670
            sos, initial = self.filters
9✔
671
            sos = list(sos.reshape(-1))
9✔
672
            l.append(len(sos))
9✔
673
            l.extend(sos)
9✔
674
            l.append(initial)
9✔
675
        l.append(len(self.wlist))
9✔
676
        for bounds, seq in self.wlist:
9✔
677
            self._tolist(bounds, seq, l)
9✔
678
        return l
9✔
679

680
    @classmethod
9✔
681
    def fromlist(cls, l):
9✔
682
        w = cls()
9✔
683
        pos = 6
9✔
684
        w.start, w.stop, w.offset, w.shift, w.sample_rate, sos_size = l[:pos]
9✔
685
        if sos_size is not None:
9✔
686
            sos = np.array(l[pos:pos + sos_size]).reshape(-1, 6)
9✔
687
            pos += sos_size
9✔
688
            initial = l[pos]
9✔
689
            pos += 1
9✔
690
            w.filters = sos, initial
9✔
691
        n = l[pos]
9✔
692
        pos += 1
9✔
693
        for _ in range(n):
9✔
694
            bounds, seq, pos = cls._fromlist(l, pos)
9✔
695
            w.wlist.append((bounds, seq))
9✔
696
        return w
9✔
697

698
    def simplify(self, eps=1e-15):
9✔
699
        if not self.wlist:
9✔
700
            return zero()
9✔
701
        bounds, seq = wave_sum(self.wlist)
9✔
702
        wav = Waveform(bounds=bounds, seq=seq)
9✔
703
        if self.offset != 0:
9✔
704
            wav += self.offset
×
705
        if self.shift != 0:
9✔
706
            wav >>= self.shift
×
707
        wav = wav.simplify(eps)
9✔
708
        wav.start = self.start
9✔
709
        wav.stop = self.stop
9✔
710
        wav.sample_rate = self.sample_rate
9✔
711
        return wav
9✔
712

713
    @staticmethod
9✔
714
    def _rshift(wlist, time):
9✔
715
        if time == 0:
×
716
            return wlist
×
717
        return [(tuple(round(bound + time, NDIGITS) for bound in bounds),
×
718
                 tuple(shift(expr, time) for expr in seq))
719
                for bounds, seq in wlist]
720

721
    def __rshift__(self, time):
9✔
722
        ret = WaveVStack()
9✔
723
        ret.wlist = self.wlist
9✔
724
        ret.sample_rate = self.sample_rate
9✔
725
        ret.start = self.start
9✔
726
        ret.stop = self.stop
9✔
727
        ret.shift = self.shift + time
9✔
728
        ret.offset = self.offset
9✔
729
        return ret
9✔
730

731
    def __add__(self, other):
9✔
732
        ret = WaveVStack()
9✔
733
        ret.wlist.extend(self.wlist)
9✔
734
        if isinstance(other, WaveVStack):
9✔
735
            if other.shift != self.shift:
×
736
                ret.wlist = self._rshift(ret.wlist, self.shift)
×
737
                ret.wlist.extend(self._rshift(other.wlist, other.shift))
×
738
            else:
739
                ret.wlist.extend(other.wlist)
×
740
            ret.offset = self.offset + other.offset
×
741
        elif isinstance(other, Waveform):
9✔
742
            other <<= self.shift
9✔
743
            ret.wlist.append((other.bounds, other.seq))
9✔
744
        else:
745
            # ret.wlist.append(((+inf, ), (_const(1.0 * other), )))
746
            ret.offset += other
9✔
747
        return ret
9✔
748

749
    def __radd__(self, v):
9✔
750
        return self + v
×
751

752
    def __mul__(self, other):
9✔
753
        if isinstance(other, Waveform):
9✔
754
            other = other.simplify() << self.shift
9✔
755
            ret = WaveVStack([Waveform(*w) * other for w in self.wlist])
9✔
756
            if self.offset != 0:
9✔
757
                w = other * self.offset
×
758
                ret.wlist.append((w.bounds, w.seq))
×
759
            return ret
9✔
760
        else:
761
            ret = WaveVStack([Waveform(*w) * other for w in self.wlist])
×
762
            ret.offset = self.offset * other
×
763
            return ret
×
764

765
    def __rmul__(self, v):
9✔
766
        return self * v
×
767

768
    def __eq__(self, other):
9✔
769
        if self.wlist:
×
770
            return False
×
771
        else:
772
            return zero() == other
×
773

774
    def _repr_latex_(self):
9✔
775
        return r"\sum_{i=1}^{" + f"{len(self.wlist)}" + r"}" + r"f_i(t)"
×
776

777
    def __getstate__(self) -> tuple:
9✔
UNCOV
778
        function_lib = self.function_lib
×
UNCOV
779
        if function_lib:
×
780
            try:
×
781
                import dill
×
782
                function_lib = dill.dumps(function_lib)
×
783
            except:
×
784
                function_lib = None
×
UNCOV
785
        return (self.wlist, self.start, self.stop, self.sample_rate,
×
786
                self.offset, self.shift, self.filters, self.label,
787
                function_lib)
788

789
    def __setstate__(self, state: tuple) -> None:
9✔
UNCOV
790
        (self.wlist, self.start, self.stop, self.sample_rate, self.offset,
×
791
         self.shift, self.filters, self.label, function_lib) = state
UNCOV
792
        if function_lib:
×
793
            try:
×
794
                import dill
×
795
                function_lib = dill.loads(function_lib)
×
796
            except:
×
797
                function_lib = None
×
UNCOV
798
        self.function_lib = function_lib
×
799

800

801
def play(data, rate=48000):
9✔
802
    import io
×
803

804
    import pyaudio
×
805

806
    CHUNK = 1024
×
807

808
    max_amp = np.max(np.abs(data))
×
809

810
    if max_amp > 1:
×
811
        data /= max_amp
×
812

813
    data = np.array(2**15 * 0.999 * data, dtype=np.int16)
×
814
    buff = io.BytesIO(data.data)
×
815
    p = pyaudio.PyAudio()
×
816

817
    try:
×
818
        stream = p.open(format=pyaudio.paInt16,
×
819
                        channels=1,
820
                        rate=rate,
821
                        output=True)
822
        try:
×
823
            while True:
×
824
                data = buff.read(CHUNK)
×
825
                if data:
×
826
                    stream.write(data)
×
827
                else:
828
                    break
×
829
        finally:
830
            stream.stop_stream()
×
831
            stream.close()
×
832
    finally:
833
        p.terminate()
×
834

835

836
_zero_waveform = Waveform()
9✔
837
_one_waveform = Waveform(seq=(_one, ))
9✔
838

839

840
def zero():
9✔
841
    return _zero_waveform
9✔
842

843

844
def one():
9✔
845
    return _one_waveform
×
846

847

848
def const(c):
9✔
849
    return Waveform(seq=(_const(1.0 * c), ))
9✔
850

851

852
# register base function
853
def _format_LINEAR(shift, *args):
9✔
854
    if shift != 0:
×
855
        shift = _num_latex(-shift)
×
856
        if shift[0] == '-':
×
857
            return f"(t{shift})"
×
858
        else:
859
            return f"(t+{shift})"
×
860
    else:
861
        return 't'
×
862

863

864
def _format_GAUSSIAN(shift, *args):
9✔
865
    sigma = _num_latex(args[0] / np.sqrt(2))
×
866
    shift = _num_latex(-shift)
×
867
    if shift != '0':
×
868
        if shift[0] != '-':
×
869
            shift = '+' + shift
×
870
        if sigma == '1':
×
871
            return ('\\exp\\left[-\\frac{\\left(t' + shift +
×
872
                    '\\right)^2}{2}\\right]')
873
        else:
874
            return ('\\exp\\left[-\\frac{1}{2}\\left(\\frac{t' + shift + '}{' +
×
875
                    sigma + '}\\right)^2\\right]')
876
    else:
877
        if sigma == '1':
×
878
            return ('\\exp\\left(-\\frac{t^2}{2}\\right)')
×
879
        else:
880
            return ('\\exp\\left[-\\frac{1}{2}\\left(\\frac{t}{' + sigma +
×
881
                    '}\\right)^2\\right]')
882

883

884
def _format_SINC(shift, *args):
9✔
885
    shift = _num_latex(-shift)
×
886
    bw = _num_latex(args[0])
×
887
    if shift != '0':
×
888
        if shift[0] != '-':
×
889
            shift = '+' + shift
×
890
        if bw == '1':
×
891
            return '\\mathrm{sinc}(t' + shift + ')'
×
892
        else:
893
            return '\\mathrm{sinc}[' + bw + '(t' + shift + ')]'
×
894
    else:
895
        if bw == '1':
×
896
            return '\\mathrm{sinc}(t)'
×
897
        else:
898
            return '\\mathrm{sinc}(' + bw + 't)'
×
899

900

901
def _format_COSINE(shift, *args):
9✔
902
    freq = args[0] / 2 / np.pi
×
903
    phase = -shift * freq
×
904
    freq = _num_latex(freq)
×
905
    if freq == '1':
×
906
        freq = ''
×
907
    phase = _num_latex(phase)
×
908
    if phase == '0':
×
909
        phase = ''
×
910
    elif phase[0] != '-':
×
911
        phase = '+' + phase
×
912
    if phase != '':
×
913
        return f'\\cos\\left[2\\pi\\left({freq}t{phase}\\right)\\right]'
×
914
    elif freq != '':
×
915
        return f'\\cos\\left(2\\pi\\times {freq}t\\right)'
×
916
    else:
917
        return '\\cos\\left(2\\pi t\\right)'
×
918

919

920
def _format_ERF(shift, *args):
9✔
921
    if shift > 0:
×
922
        return '\\mathrm{erf}(\\frac{t-' + f"{_num_latex(shift)}" + '}{' + f'{args[0]:g}' + '})'
×
923
    elif shift < 0:
×
924
        return '\\mathrm{erf}(\\frac{t+' + f"{_num_latex(-shift)}" + '}{' + f'{args[0]:g}' + '})'
×
925
    else:
926
        return '\\mathrm{erf}(\\frac{t}{' + f'{args[0]:g}' + '})'
×
927

928

929
def _format_COSH(shift, *args):
9✔
930
    if shift > 0:
×
931
        return '\\cosh(\\frac{t-' + f"{_num_latex(shift)}" + '}{' + f'{1/args[0]:g}' + '})'
×
932
    elif shift < 0:
×
933
        return '\\cosh(\\frac{t+' + f"{_num_latex(-shift)}" + '}{' + f'{1/args[0]:g}' + '})'
×
934
    else:
935
        return '\\cosh(\\frac{t}{' + f'{1/args[0]:g}' + '})'
×
936

937

938
def _format_SINH(shift, *args):
9✔
939
    if shift > 0:
×
940
        return '\\sinh(\\frac{t-' + f"{_num_latex(shift)}" + '}{' + f'{args[0]:g}' + '})'
×
941
    elif shift < 0:
×
942
        return '\\sinh(\\frac{t+' + f"{_num_latex(-shift)}" + '}{' + f'{args[0]:g}' + '})'
×
943
    else:
944
        return '\\sinh(\\frac{t}{' + f'{args[0]:g}' + '})'
×
945

946

947
def _format_EXP(shift, *args):
9✔
948
    if _num_latex(shift) and shift > 0:
×
949
        return '\\exp\\left(-' + f'{args[0]:g}' + '\\left(t-' + f"{_num_latex(shift)}" + '\\right)\\right)'
×
950
    elif _num_latex(-shift) and shift < 0:
×
951
        return '\\exp\\left(-' + f'{args[0]:g}' + '\\left(t+' + f"{_num_latex(-shift)}" + '\\right)\\right)'
×
952
    else:
953
        return '\\exp\\left(-' + f'{args[0]:g}' + 't\\right)'
×
954

955

956
def _format_DRAG(shift, *args):
9✔
957
    return f"DRAG(...)"
×
958

959

960
registerBaseFuncLatex(LINEAR, _format_LINEAR)
9✔
961
registerBaseFuncLatex(GAUSSIAN, _format_GAUSSIAN)
9✔
962
registerBaseFuncLatex(ERF, _format_ERF)
9✔
963
registerBaseFuncLatex(COS, _format_COSINE)
9✔
964
registerBaseFuncLatex(SINC, _format_SINC)
9✔
965
registerBaseFuncLatex(EXP, _format_EXP)
9✔
966
registerBaseFuncLatex(COSH, _format_COSH)
9✔
967
registerBaseFuncLatex(SINH, _format_SINH)
9✔
968
registerBaseFuncLatex(DRAG, _format_DRAG)
9✔
969

970

971
def D(wav):
9✔
972
    """derivative
973
    """
974
    return Waveform(bounds=wav.bounds, seq=tuple(_D(x) for x in wav.seq))
×
975

976

977
def convolve(a, b):
9✔
978
    pass
×
979

980

981
def sign():
9✔
982
    return Waveform(bounds=(0, +inf), seq=(_const(-1), _one))
×
983

984

985
def step(edge, type='erf'):
9✔
986
    """
987
    type: "erf", "cos", "linear"
988
    """
989
    if edge == 0:
9✔
990
        return Waveform(bounds=(0, +inf), seq=(_zero, _one))
9✔
991
    if type == 'cos':
9✔
992
        rise = add(_half,
×
993
                   mul(_half, basic_wave(COS, pi / edge, shift=0.5 * edge)))
994
        return Waveform(bounds=(round(-edge / 2,
×
995
                                      NDIGITS), round(edge / 2,
996
                                                      NDIGITS), +inf),
997
                        seq=(_zero, rise, _one))
998
    elif type == 'linear':
9✔
999
        rise = add(_half, mul(_const(1 / edge), basic_wave(LINEAR)))
9✔
1000
        return Waveform(bounds=(round(-edge / 2,
9✔
1001
                                      NDIGITS), round(edge / 2,
1002
                                                      NDIGITS), +inf),
1003
                        seq=(_zero, rise, _one))
1004
    else:
1005
        std_sq2 = edge / 5
×
1006
        # rise = add(_half, mul(_half, basic_wave(ERF, std_sq2)))
1007
        rise = ((((), ()), (((ERF, std_sq2, 0), ), (1, ))), (0.5, 0.5))
×
1008
        return Waveform(bounds=(-round(edge, NDIGITS), round(edge,
×
1009
                                                             NDIGITS), +inf),
1010
                        seq=(_zero, rise, _one))
1011

1012

1013
def square(width, edge=0, type='erf'):
9✔
1014
    if width <= 0:
9✔
1015
        return zero()
×
1016
    if edge == 0:
9✔
1017
        return Waveform(bounds=(round(-0.5 * width,
9✔
1018
                                      NDIGITS), round(0.5 * width,
1019
                                                      NDIGITS), +inf),
1020
                        seq=(_zero, _one, _zero))
1021
    else:
1022
        return ((step(edge, type=type) << width / 2) -
9✔
1023
                (step(edge, type=type) >> width / 2))
1024

1025

1026
def gaussian(width, plateau=0.0):
9✔
1027
    if width <= 0 and plateau <= 0.0:
9✔
1028
        return zero()
×
1029
    # width is two times FWHM
1030
    # std_sq2 = width / (4 * np.sqrt(np.log(2)))
1031
    std_sq2 = width / 3.3302184446307908
9✔
1032
    # std is set to give total pulse area same as a square
1033
    # std_sq2 = width/np.sqrt(np.pi)
1034
    if round(0.5 * plateau, NDIGITS) <= 0.0:
9✔
1035
        return Waveform(bounds=(round(-0.75 * width,
9✔
1036
                                      NDIGITS), round(0.75 * width,
1037
                                                      NDIGITS), +inf),
1038
                        seq=(_zero, basic_wave(GAUSSIAN, std_sq2), _zero))
1039
    else:
1040
        return Waveform(bounds=(round(-0.75 * width - 0.5 * plateau,
×
1041
                                      NDIGITS), round(-0.5 * plateau, NDIGITS),
1042
                                round(0.5 * plateau, NDIGITS),
1043
                                round(0.75 * width + 0.5 * plateau,
1044
                                      NDIGITS), +inf),
1045
                        seq=(_zero,
1046
                             basic_wave(GAUSSIAN,
1047
                                        std_sq2,
1048
                                        shift=-0.5 * plateau), _one,
1049
                             basic_wave(GAUSSIAN, std_sq2,
1050
                                        shift=0.5 * plateau), _zero))
1051

1052

1053
def cos(w, phi=0):
9✔
1054
    if w == 0:
9✔
1055
        return const(np.cos(phi))
×
1056
    if w < 0:
9✔
1057
        phi = -phi
×
1058
        w = -w
×
1059
    return Waveform(seq=(basic_wave(COS, w, shift=-phi / w), ))
9✔
1060

1061

1062
def sin(w, phi=0):
9✔
1063
    if w == 0:
9✔
1064
        return const(np.sin(phi))
×
1065
    if w < 0:
9✔
1066
        phi = -phi + pi
×
1067
        w = -w
×
1068
    return Waveform(seq=(basic_wave(COS, w, shift=(pi / 2 - phi) / w), ))
9✔
1069

1070

1071
def exp(alpha):
9✔
1072
    if isinstance(alpha, complex):
9✔
1073
        if alpha.real == 0:
9✔
1074
            return cos(alpha.imag) + 1j * sin(alpha.imag)
×
1075
        else:
1076
            return exp(alpha.real) * (cos(alpha.imag) + 1j * sin(alpha.imag))
9✔
1077
    else:
1078
        return Waveform(seq=(basic_wave(EXP, alpha), ))
9✔
1079

1080

1081
def sinc(bw):
9✔
1082
    if bw <= 0:
×
1083
        return zero()
×
1084
    width = 100 / bw
×
1085
    return Waveform(bounds=(round(-0.5 * width,
×
1086
                                  NDIGITS), round(0.5 * width, NDIGITS), +inf),
1087
                    seq=(_zero, basic_wave(SINC, bw), _zero))
1088

1089

1090
def cosPulse(width, plateau=0.0):
9✔
1091
    # cos = basic_wave(COS, 2*np.pi/width)
1092
    # pulse = mul(add(cos, _one), _half)
1093
    if round(0.5 * plateau, NDIGITS) > 0:
×
1094
        return square(plateau + 0.5 * width, edge=0.5 * width, type='cos')
×
1095
    if width <= 0:
×
1096
        return zero()
×
1097
    pulse = ((((), ()), (((COS, 6.283185307179586 / width, 0), ), (1, ))),
×
1098
             (0.5, 0.5))
1099
    return Waveform(bounds=(round(-0.5 * width,
×
1100
                                  NDIGITS), round(0.5 * width, NDIGITS), +inf),
1101
                    seq=(_zero, pulse, _zero))
1102

1103

1104
def hanning(width, plateau=0.0):
9✔
1105
    return cosPulse(width, plateau=plateau)
×
1106

1107

1108
def cosh(w):
9✔
1109
    return Waveform(seq=(basic_wave(COSH, w), ))
×
1110

1111

1112
def sinh(w):
9✔
1113
    return Waveform(seq=(basic_wave(SINH, w), ))
×
1114

1115

1116
def coshPulse(width, eps=1.0, plateau=0.0):
9✔
1117
    """Cosine hyperbolic pulse with the following im
1118

1119
    pulse edge shape:
1120
            cosh(eps / 2) - cosh(eps * t / T)
1121
    f(t) = -----------------------------------
1122
                  cosh(eps / 2) - 1
1123
    where T is the pulse width and eps is the pulse edge steepness.
1124
    The pulse is defined for t in [-T/2, T/2].
1125

1126
    In case of plateau > 0, the pulse is defined as:
1127
           | f(t + plateau/2)   if t in [-T/2 - plateau/2, - plateau/2]
1128
    g(t) = | 1                  if t in [-plateau/2, plateau/2]
1129
           | f(t - plateau/2)   if t in [plateau/2, T/2 + plateau/2]
1130

1131
    Parameters
1132
    ----------
1133
    width : float
1134
        Pulse width.
1135
    eps : float
1136
        Pulse edge steepness.
1137
    plateau : float
1138
        Pulse plateau.
1139
    """
1140
    if width <= 0 and plateau <= 0:
×
1141
        return zero()
×
1142
    w = eps / width
×
1143
    A = np.cosh(eps / 2)
×
1144

1145
    if plateau == 0.0 or round(-0.5 * plateau, NDIGITS) == round(
×
1146
            0.5 * plateau, NDIGITS):
1147
        pulse = ((((), ()), (((COSH, w, 0), ), (1, ))), (A / (A - 1),
×
1148
                                                         -1 / (A - 1)))
1149
        return Waveform(bounds=(round(-0.5 * width,
×
1150
                                      NDIGITS), round(0.5 * width,
1151
                                                      NDIGITS), +inf),
1152
                        seq=(_zero, pulse, _zero))
1153
    else:
1154
        raising = ((((), ()), (((COSH, w, -0.5 * plateau), ), (1, ))),
×
1155
                   (A / (A - 1), -1 / (A - 1)))
1156
        falling = ((((), ()), (((COSH, w, 0.5 * plateau), ), (1, ))),
×
1157
                   (A / (A - 1), -1 / (A - 1)))
1158
        return Waveform(bounds=(round(-0.5 * width - 0.5 * plateau,
×
1159
                                      NDIGITS), round(-0.5 * plateau, NDIGITS),
1160
                                round(0.5 * plateau, NDIGITS),
1161
                                round(0.5 * width + 0.5 * plateau,
1162
                                      NDIGITS), +inf),
1163
                        seq=(_zero, raising, _one, falling, _zero))
1164

1165

1166
def general_cosine(duration, *arg):
9✔
1167
    wav = zero()
×
1168
    arg = np.asarray(arg)
×
1169
    arg /= arg[::2].sum()
×
1170
    for i, a in enumerate(arg, start=1):
×
1171
        wav += a / 2 * (1 - (-1)**i * cos(i * 2 * pi / duration))
×
1172
    return wav * square(duration)
×
1173

1174

1175
def slepian(duration, *arg):
9✔
1176
    wav = zero()
×
1177
    arg = np.asarray(arg)
×
1178
    arg /= arg[::2].sum()
×
1179
    for i, a in enumerate(arg, start=1):
×
1180
        wav += a / 2 * (1 - (-1)**i * cos(i * 2 * pi / duration))
×
1181
    return wav * square(duration)
×
1182

1183

1184
def _poly(*a):
9✔
1185
    """
1186
    a[0] + a[1] * t + a[2] * t**2 + ...
1187
    """
1188
    t = []
9✔
1189
    amp = []
9✔
1190
    if a[0] != 0:
9✔
1191
        t.append(((), ()))
9✔
1192
        amp.append(a[0])
9✔
1193
    for n, a_ in enumerate(a[1:], start=1):
9✔
1194
        if a_ != 0:
9✔
1195
            t.append((((LINEAR, 0), ), (n, )))
9✔
1196
            amp.append(a_)
9✔
1197
    return tuple(t), tuple(a)
9✔
1198

1199

1200
def poly(a):
9✔
1201
    """
1202
    a[0] + a[1] * t + a[2] * t**2 + ...
1203
    """
1204
    return Waveform(seq=(_poly(*a), ))
9✔
1205

1206

1207
def t():
9✔
1208
    return Waveform(seq=((((LINEAR, 0), ), (1, )), (1, )))
×
1209

1210

1211
def drag(freq, width, plateau=0, delta=0, block_freq=None, phase=0, t0=0):
9✔
UNCOV
1212
    phase += pi * delta * (width + plateau)
×
UNCOV
1213
    if plateau <= 0:
×
UNCOV
1214
        return Waveform(seq=(_zero,
×
1215
                             basic_wave(DRAG, t0, freq, width, delta,
1216
                                        block_freq, phase), _zero),
1217
                        bounds=(round(t0, NDIGITS), round(t0 + width,
1218
                                                          NDIGITS), +inf))
1219
    elif width <= 0:
×
1220
        w = 2 * pi * (freq + delta)
×
1221
        return Waveform(
×
1222
            seq=(_zero,
1223
                 basic_wave(COS, w,
1224
                            shift=(phase + 2 * pi * delta * t0) / w), _zero),
1225
            bounds=(round(t0, NDIGITS), round(t0 + plateau, NDIGITS), +inf))
1226
    else:
1227
        w = 2 * pi * (freq + delta)
×
1228
        return Waveform(
×
1229
            seq=(_zero,
1230
                 basic_wave(DRAG, t0, freq, width, delta, block_freq, phase),
1231
                 basic_wave(COS, w, shift=(phase + 2 * pi * delta * t0) / w),
1232
                 basic_wave(DRAG, t0 + plateau, freq, width, delta, block_freq,
1233
                            phase - 2 * pi * delta * plateau), _zero),
1234
            bounds=(round(t0, NDIGITS), round(t0 + width / 2, NDIGITS),
1235
                    round(t0 + width / 2 + plateau,
1236
                          NDIGITS), round(t0 + width + plateau,
1237
                                          NDIGITS), +inf))
1238

1239

1240
def chirp(f0, f1, T, phi0=0, type='linear'):
9✔
1241
    """
1242
    A chirp is a signal in which the frequency increases (up-chirp)
1243
    or decreases (down-chirp) with time. In some sources, the term
1244
    chirp is used interchangeably with sweep signal.
1245

1246
    type: "linear", "exponential", "hyperbolic"
1247
    """
1248
    if f0 == f1:
9✔
1249
        return sin(f0, phi0)
×
1250
    if T <= 0:
9✔
1251
        raise ValueError('T must be positive')
×
1252

1253
    if type == 'linear':
9✔
1254
        # f(t) = f1 * (t/T) + f0 * (1 - t/T)
1255
        return Waveform(bounds=(0, round(T, NDIGITS), +inf),
9✔
1256
                        seq=(_zero, basic_wave(LINEARCHIRP, f0, f1, T,
1257
                                               phi0), _zero))
1258
    elif type in ['exp', 'exponential', 'geometric']:
9✔
1259
        # f(t) = f0 * (f1/f0) ** (t/T)
1260
        if f0 == 0:
9✔
1261
            raise ValueError('f0 must be non-zero')
×
1262
        alpha = np.log(f1 / f0) / T
9✔
1263
        return Waveform(bounds=(0, round(T, NDIGITS), +inf),
9✔
1264
                        seq=(_zero,
1265
                             basic_wave(EXPONENTIALCHIRP, f0, alpha,
1266
                                        phi0), _zero))
1267
    elif type in ['hyperbolic', 'hyp']:
9✔
1268
        # f(t) = f0 * f1 / (f0 * (t/T) + f1 * (1-t/T))
1269
        if f0 * f1 == 0:
9✔
1270
            return const(np.sin(phi0))
×
1271
        k = (f0 - f1) / (f1 * T)
9✔
1272
        return Waveform(bounds=(0, round(T, NDIGITS), +inf),
9✔
1273
                        seq=(_zero, basic_wave(HYPERBOLICCHIRP, f0, k,
1274
                                               phi0), _zero))
1275
    else:
1276
        raise ValueError(f'unknown type {type}')
×
1277

1278

1279
def interp(x, y):
9✔
1280
    seq, bounds = [_zero], [x[0]]
×
1281
    for x1, x2, y1, y2 in zip(x[:-1], x[1:], y[:-1], y[1:]):
×
1282
        if x2 == x1:
×
1283
            continue
×
1284
        seq.append(
×
1285
            add(
1286
                mul(_const((y2 - y1) / (x2 - x1)), basic_wave(LINEAR,
1287
                                                              shift=x1)),
1288
                _const(y1)))
1289
        bounds.append(x2)
×
1290
    bounds.append(inf)
×
1291
    seq.append(_zero)
×
1292
    return Waveform(seq=tuple(seq),
×
1293
                    bounds=tuple(round(b, NDIGITS)
1294
                                 for b in bounds)).simplify()
1295

1296

1297
def cut(wav, start=None, stop=None, head=None, tail=None, min=None, max=None):
9✔
1298
    offset = 0
×
1299
    if start is not None and head is not None:
×
1300
        offset = head - wav(np.array([1.0 * start]))[0]
×
1301
    elif stop is not None and tail is not None:
×
1302
        offset = tail - wav(np.array([1.0 * stop]))[0]
×
1303
    wav = wav + offset
×
1304

1305
    if start is not None:
×
1306
        wav = wav * (step(0) >> start)
×
1307
    if stop is not None:
×
1308
        wav = wav * ((1 - step(0)) >> stop)
×
1309
    if min is not None:
×
1310
        wav.min = min
×
1311
    if max is not None:
×
1312
        wav.max = max
×
1313
    return wav
×
1314

1315

1316
def function(fun, *args, start=None, stop=None):
9✔
1317
    TYPEID = registerBaseFunc(fun)
×
1318
    seq = (basic_wave(TYPEID, *args), )
×
1319
    wav = Waveform(seq=seq)
×
1320
    if start is not None:
×
1321
        wav = wav * (step(0) >> start)
×
1322
    if stop is not None:
×
1323
        wav = wav * ((1 - step(0)) >> stop)
×
1324
    return wav
×
1325

1326

1327
def samplingPoints(start, stop, points):
9✔
1328
    return Waveform(bounds=(round(start, NDIGITS), round(stop, NDIGITS), inf),
×
1329
                    seq=(_zero, basic_wave(INTERP, start, stop,
1330
                                           tuple(points)), _zero))
1331

1332

1333
def mixing(I,
9✔
1334
           Q=None,
1335
           *,
1336
           phase=0.0,
1337
           freq=0.0,
1338
           ratioIQ=1.0,
1339
           phaseDiff=0.0,
1340
           block_freq=None,
1341
           DRAGScaling=None):
1342
    """SSB or envelope mixing
1343
    """
1344
    if Q is None:
×
1345
        I = I
×
1346
        Q = zero()
×
1347

1348
    w = 2 * pi * freq
×
1349
    if freq != 0.0:
×
1350
        # SSB mixing
1351
        Iout = I * cos(w, -phase) + Q * sin(w, -phase)
×
1352
        Qout = -I * sin(w, -phase + phaseDiff) + Q * cos(w, -phase + phaseDiff)
×
1353
    else:
1354
        # envelope mixing
1355
        Iout = I * np.cos(-phase) + Q * np.sin(-phase)
×
1356
        Qout = -I * np.sin(-phase) + Q * np.cos(-phase)
×
1357

1358
    # apply DRAG
1359
    if block_freq is not None and block_freq != freq:
×
1360
        a = block_freq / (block_freq - freq)
×
1361
        b = 1 / (block_freq - freq)
×
1362
        I = a * Iout + b / (2 * pi) * D(Qout)
×
1363
        Q = a * Qout - b / (2 * pi) * D(Iout)
×
1364
        Iout, Qout = I, Q
×
1365
    elif DRAGScaling is not None and DRAGScaling != 0:
×
1366
        # 2 * pi * scaling * (freq - block_freq) = 1
1367
        I = (1 - w * DRAGScaling) * Iout - DRAGScaling * D(Qout)
×
1368
        Q = (1 - w * DRAGScaling) * Qout + DRAGScaling * D(Iout)
×
1369
        Iout, Qout = I, Q
×
1370

1371
    Qout = ratioIQ * Qout
×
1372

1373
    return Iout, Qout
×
1374

1375

1376
__all__ = [
9✔
1377
    'D', 'Waveform', 'chirp', 'const', 'cos', 'cosh', 'coshPulse', 'cosPulse',
1378
    'cut', 'drag', 'exp', 'function', 'gaussian', 'general_cosine', 'hanning',
1379
    'interp', 'mixing', 'one', 'poly', 'registerBaseFunc',
1380
    'registerDerivative', 'samplingPoints', 'sign', 'sin', 'sinc', 'sinh',
1381
    'square', 'step', 't', 'zero'
1382
]
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