forked from rtmrtmrtmrtm/weakmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wspr.py
executable file
·1638 lines (1407 loc) · 52.2 KB
/
wspr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/bin/python
#
# decode WSPR
#
# info from wsjt-x manual, wsjt-x source, and
# http://physics.princeton.edu/pulsar/k1jt/WSPR_3.0_User.pdf
# http://www.g4jnt.com/Coding/WSPR_Coding_Process.pdf
#
# uses Phil Karn's Fano convolutional decoder.
#
# Robert Morris, AB1HL
#
import numpy
import wave
import scipy
import scipy.signal
import sys
import os
import math
import time
import copy
import calendar
import subprocess
import threading
import re
import random
from scipy.signal import lfilter
import ctypes
import weakaudio
import weakutil
#
# WSPR tuning parameters.
#
budget = 9 # max seconds of CPU time, per file or two-minute interval (50).
step_frac = 2.5 # fraction of FFT bin for frequency search (4).
#ngoff = 3 # look at this many of guess_offset()'s results (6, 4).
goff_step = 64 # guess_offset search interval.
fano_limit = 30000 # how hard fano will work (10000).
fano_delta = 17
fano_bias = 0.5
fano_floor = 0.005
fano_scale = 4.5
statruns = 3
driftmax = 1.0 # look at drifts from -driftmax to +driftmax (2).
ndrift = 3 # number of drifts to try (including drift=0)
coarse_steps = 4 # coarse() search for start offset at this many points per symbol time.
coarse_hzsteps = 4 # look for signals at this many freq offsets per bin.
coarse_top1 = 2
coarse_top2 = 5
phase0_budget = 0.4 # fraction of remaining budget for pre-subtraction
subslop = 0.01 # granularity (in symbols) of subtraction phase search
start_slop = 4.0 # pad to this many seconds before 0:01
end_slop = 5.0 # pad this many seconds after end of nominal end time
band_order = 6 # order of bandpass filter
subgap = 0.4 # extra subtract()s this many hz on either side of main bin
ignore_thresh = -30 # ignore decodes with lower SNR than this
# information about one decoded signal.
class Decode:
def __init__(self,
hza,
msg,
snr,
msgbits):
self.hza = hza
self.msg = msg
self.snr = snr
self.msgbits = msgbits # output of Fano decode
self.minute = None
self.start = None # sample number
self.dt = None # dt in seconds
self.decode_time = None # unix time of decode
self.phase0 = False
self.phase1 = False
self.drift = self.hz() - hza[0] # Hz per minute
def hz(self):
return numpy.mean(self.hza)
# the WSPR sync pattern. each of the 162 2-bit symbols includes one bit of
# sync in the low bit.
pattern = [
1, 1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1,
-1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1,
1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1,
1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1,
-1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1,
1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1,
]
# Phil Karn's Fano convolutional decoder.
from ctypes import c_ubyte, c_int, byref, cdll
libfano = cdll.LoadLibrary("libfano/libfano.so") # both OSX and FreeBSD
# returns an array of 0/1 bits,
# 2x as many as in_bits.
def fano_encode(in_bits):
# fano_encode(unsigned char in_bits[], int n_in, unsigned char out_bits[])
in_array_type = c_ubyte * len(in_bits)
in_array = in_array_type()
for i in range(0, len(in_bits)):
in_array[i] = in_bits[i]
out_array_type = c_ubyte * (2*len(in_bits))
out_array = out_array_type()
n_in = c_int()
n_in.value = len(in_bits)
libfano.fano_encode(in_array, n_in, out_array)
a = []
for i in range(0, 2*len(in_bits)):
a.append(out_array[i])
return a
# in0[i] is log of probability that the i'th symbol is 0.
# returns an array of 0/1 bits, half as many as in0[].
# returns None on error.
def nfano_decode(in0, in1):
global fano_limit, fano_delta
#for i in range(0, len(in0)):
# print "%d %d %d" % (i, in0[i], in1[i])
#sys.exit(1)
in_array_type = c_int * len(in0)
xin0 = in_array_type()
xin1 = in_array_type()
for i in range(0, len(in0)):
xin0[i] = in0[i]
xin1[i] = in1[i]
out_array_type = c_ubyte * (len(in0) / 2)
out_array = out_array_type()
n_out = c_int()
n_out.value = len(in0) / 2
metric_out_type = c_int * 1
metric_out = metric_out_type()
limit = c_int()
limit = fano_limit
delta = c_int()
delta = fano_delta
ok = libfano.nfano_decode(xin0, xin1, n_out, out_array, limit, metric_out, delta)
if ok != 1:
return [ None, None ]
a = []
for i in range(0, len(in0) / 2):
a.append(out_array[i])
metric = metric_out[0]
return [ a, metric ]
def ntest_fano():
in_bits = [ 1, 0 ] * 36 # 76 bits, like JT9
padded = in_bits + ([0] * 31)
out_bits = fano_encode(padded)
in0 = [ ]
in1 = [ ]
for b in out_bits:
if b == 1:
in1.append(1)
in0.append(-10)
else:
in0.append(1)
in1.append(-10)
[ dec, metric ] = nfano_decode(in0, in1)
assert in_bits == dec[0:len(in_bits)]
if False:
ntest_fano()
sys.exit(0)
# Normal function integrated from -Inf to x. Range: 0-1.
# x in units of std dev.
# mean is zero.
def normal(x):
y = 0.5 + 0.5*math.erf(x / 1.414213)
return y
# how much of the distribution is < x?
def problt(x, mean, std):
y = normal((x - mean) / std)
return y
# how much of the distribution is > x?
def probgt(x, mean, std):
y = 1.0 - normal((x - mean) / std)
return y
def bit_reverse(x, width):
y = 0
for i in range(0, width):
z = (x >> i) & 1
y <<= 1
y |= z
return y
# turn an array of bits into a number.
# most significant bit first.
def bits2num(bits):
assert len(bits) < 32
n = 0
for i in range(0, len(bits)):
n *= 2
n += bits[i]
return n
# gadget that returns FFT buckets of a fixed set of
# original samples, with required (inter-bucket)
# frequency, drift, and offset.
class FFTCache:
def __init__(self, samples, jrate, jblock):
self.jrate = jrate
self.jblock = jblock
self.samples = samples
self.memo = { }
self.granule = int(self.jblock / 8)
# internal.
def fft2(self, index, quarter):
key = str(index) + "-" + str(quarter)
if key in self.memo:
return self.memo[key]
# caller wants a frequency a bit higher than bin,
# so shift *down* by the indicated number of quarter bins.
block = self.samples[index:index+self.jblock]
if quarter != 0:
bin_hz = self.jrate / float(self.jblock)
freq_off = quarter * (bin_hz / 4.0)
block = weakutil.freq_shift(block, -freq_off, 1.0/self.jrate)
a = numpy.fft.rfft(block)
a = abs(a)
self.memo[key] = a
return a
# internal.
# offset is index into samples[].
# return [ bin, full FFT at offset ].
def fft1(self, index, hza):
bin_hz = self.jrate / float(self.jblock)
hz = hza[0] + (index / float(len(self.samples))) * (hza[1] - hza[0])
bin = int(hz / bin_hz)
binfrac = (hz - (bin * bin_hz)) / bin_hz
# which of four quarter-bin increments?
if binfrac < 0.25:
quarter = 0
elif binfrac < 0.5:
quarter = 1
elif binfrac < 0.75:
quarter = 2
else:
quarter = 3
a = self.fft2(index, quarter)
return [ bin, a ]
# hza is [ hz0, hzN ] -- at start and end.
# offset is 0..self.jblock.
# return buckets[0..162ish][4] -- i.e. a mini-FFT per symbol.
def get(self, hza, offset):
return self.getmore(hza, offset, 0)
# hza is [ hz0, hzN ] -- at start and end.
# offset is 0..self.jblock.
# return buckets[0..162ish][4 +/- more] -- i.e. a mini-FFT per symbol.
# ordinarily more is 0. it's 1 for guess_freq().
def getmore(self, hza, offset, more):
# round offset to 1/8th of self.jblock.
offset = int(offset / self.granule) * self.granule
bin_hz = self.jrate / float(self.jblock)
nsyms = (len(self.samples) - offset) // self.jblock
out = numpy.zeros((nsyms, 4+more+more))
for i in range(0, nsyms):
ioff = i * self.jblock + offset
[ bin, m ] = self.fft1(ioff, hza)
assert bin - more >= 0
assert bin+4+more <= len(m)
m = m[bin-more:bin+4+more]
out[i] = m
return out
def len(self):
return len(self.samples)
class WSPR:
debug = False
offset = 0
def __init__(self):
self.msgs_lock = threading.Lock()
self.msgs = [ ]
self.verbose = False
self.downhz = 1300 # shift this down to zero hz.
self.lowhz = 1400 - self.downhz # WSPR signals start here
self.jrate = 750 # sample rate for processing (FFT &c)
self.jblock = 512 # samples per symbol
# set self.start_time to the UNIX time of the start
# of the last even UTC minute.
now = int(time.time())
gm = time.gmtime(now)
self.start_time = now - gm.tm_sec
if (gm.tm_min % 2) == 1:
self.start_time -= 60
def close(self):
pass
# return the minute number for t, a UNIX time in seconds.
# truncates down, so best to pass a time mid-way through a minute.
# returns only even minutes.
def minute(self, t):
dt = t - self.start_time
mins = 2 * int(dt / 120.0)
return mins
# seconds since minute(), 0..119
def second(self, t):
dt = t - self.start_time
m = 120 * int(dt / 120.0)
return dt - m
# printable UTC timestamp, e.g. "07/07/15 16:31:00"
# dd/mm/yy hh:mm:ss
# t is unix time.
def ts(self, t):
gm = time.gmtime(t)
return "%02d/%02d/%02d %02d:%02d:%02d" % (gm.tm_mday,
gm.tm_mon,
gm.tm_year - 2000,
gm.tm_hour,
gm.tm_min,
gm.tm_sec)
def openwav(self, filename):
self.wav = wave.open(filename)
self.wav_channels = self.wav.getnchannels()
self.wav_width = self.wav.getsampwidth()
self.cardrate = self.wav.getframerate()
def readwav(self, chan):
z = self.wav.readframes(8192)
if self.wav_width == 1:
zz = numpy.fromstring(z, numpy.int8)
elif self.wav_width == 2:
if (len(z) % 2) == 1:
return numpy.array([])
zz = numpy.fromstring(z, numpy.int16)
else:
sys.stderr.write("oops wave_width %d" % (self.wav_width))
sys.exit(1)
if self.wav_channels == 1:
return zz
elif self.wav_channels == 2:
return zz[chan::2] # chan 0/1 => left/right
else:
sys.stderr.write("oops wav_channels %d" % (self.wav_channels))
sys.exit(1)
def gowav(self, filename, chan):
self.openwav(filename)
bufbuf = [ ]
while True:
buf = self.readwav(chan)
if buf.size < 1:
break
bufbuf.append(buf)
samples = numpy.concatenate(bufbuf)
self.process(samples, 0)
def opencard(self, desc):
self.cardrate = 12000
self.audio = weakaudio.new(desc, self.cardrate)
def gocard(self):
bufbuf = [ ]
nsamples = 0
while True:
[ buf, buf_time ] = self.audio.read()
bufbuf.append(buf)
nsamples += len(buf)
samples_time = buf_time
if len(buf) > 0:
mx = numpy.max(numpy.abs(buf))
if mx > 30000:
sys.stderr.write("!")
if len(buf) == 0:
time.sleep(0.2)
# a WSPR frame starts on second 1, and takes 110.5 seconds, so
# should end with the 112th second.
# wait until we have enough samples through 113th second of minute.
# 162 symbols, 0.682 sec/symbol, 110.5 seconds total.
sec = self.second(samples_time)
if sec >= 113 and nsamples >= 113*self.cardrate:
# we have >= 113 seconds of samples, and second of minute is >= 113.
samples = numpy.concatenate(bufbuf)
# sample # of one second before start of two-minute interval.
i0 = len(samples) - self.cardrate * self.second(samples_time)
i0 -= self.cardrate # process() expects samples starting at 0:59
i0 = int(i0)
i0 = max(i0, 0)
t = samples_time - (len(samples)-i0) * (1.0/self.cardrate)
self.process(samples[i0:], t)
bufbuf = [ ]
nsamples = 0
# received a message, add it to the list.
# offset in seconds.
# drift in hz/minute.
def got_msg(self, dec):
if self.verbose:
drift = dec.hza[1] - dec.hz()
print("%6.1f %.1f %.1f %d %s" % (dec.hz(), dec.dt, drift, dec.snr, dec.msg))
dec.decode_time = time.time()
self.msgs_lock.acquire()
self.msgs.append(dec)
self.msgs_lock.release()
# someone wants a list of all messages received,
# as array of Decode.
def get_msgs(self):
self.msgs_lock.acquire()
a = copy.copy(self.msgs)
self.msgs_lock.release()
return a
def process(self, samples, samples_time):
global budget, step_frac, goff_step, fano_limit, driftmax, ndrift
# samples_time is UNIX time that samples[0] was
# sampled by the sound card.
samples_minute = self.minute(samples_time + 60)
t0 = time.time()
# trim trailing zeroes that wsjt-x adds
i = len(samples)
while i > 1000 and numpy.max(samples[i-1:]) == 0.0:
if numpy.max(samples[i-1000:]) == 0.0:
i -= 1000
elif numpy.max(samples[i-100:]) == 0.0:
i -= 100
elif numpy.max(samples[i-10:]) == 0.0:
i -= 10
else:
i -= 1
samples = samples[0:i]
# bandpass filter around 1400..1600.
# down-convert by 1200 Hz (i.e. 1400-1600 -> 200->400),
# and reduce sampling rate to 1500.
assert self.cardrate == 12000 and self.jrate == 750
filter = weakutil.butter_bandpass(1380, 1620, self.cardrate, band_order)
samples = lfilter(filter[0], filter[1], samples)
# down-convert from 1400 to 100.
samples = weakutil.freq_shift(samples, -self.downhz, 1.0/self.cardrate)
# down-sample.
samples = samples[0::16]
#
# pad at start+end b/c transmission might have started early or late.
# I've observed dt's from -2.8 to +3.4.
# there's already two seconds of slop at start b/c xmission starts
# at xx:01 but file seems to start at xx:59.
# and we're going to trim a second either side after AGC.
#
sm = numpy.mean(samples) # pad with plausible signal levels
sd = numpy.std(samples)
assert start_slop >= 2.0
startpad = int((start_slop - 2.0) * self.jrate) # samples
samples = numpy.append(numpy.random.normal(sm, sd, startpad), samples)
endpad = int((start_slop*self.jrate + 162.0*self.jblock + end_slop*self.jrate) - len(samples))
if endpad > 0:
samples = numpy.append(samples, numpy.random.normal(sm, sd, endpad))
elif endpad < 0:
samples = samples[0:endpad]
bin_hz = self.jrate / float(self.jblock)
# store each message just once, to suppress duplicates.
# indexed by message text; value is [ samples_minute, hz, msg, snr, offset, drift ]
msgs = { }
ssamples = numpy.copy(samples) # for subtraction
# phase 0: decode and subtract, but don't use the subtraction.
# phase 1: decode from subtracted samples.
phase0_start = time.time()
phase1_end = t0 + budget
for phase in range(0, 2):
if phase == 0:
phasesamples = samples
else:
phasesamples = ssamples # samples with phase0 decodes subtracted
[ fine_rank, noise ] = self.coarse(phasesamples)
xf = FFTCache(phasesamples, self.jrate, self.jblock)
already = { }
for rr in fine_rank:
# rr is [ drift, hz, offset, strength ]
if phase == 0 and len(msgs) > 0:
if time.time() - phase0_start >= phase0_budget*(phase1_end-phase0_start):
break
else:
if time.time() - t0 >= budget:
break
drift = rr[0]
hz = rr[1]
offset = rr[2]
#if int(hz / bin_hz) in already:
# continue
hza = [ hz - drift, hz + drift ]
offset = self.guess_start(xf, hza, offset)
hza = self.guess_freq(xf, hza, offset)
ss = xf.get(hza, offset)
# ss has one element per symbol time.
# ss[i] is a 4-element FFT.
# first symbol is in ss[0]
# return is [ hza, msg, snr ]
assert len(ss[0]) >= 4
dec = self.process1(samples_minute, ss[0:162], hza, noise)
if False:
if dec != None:
print("%.1f %d %.1f %.1f %s -- %s" % (hz, phase, drift, numpy.mean(hza), rr, dec.msg))
else:
print("%.1f %d %.1f %.1f %s" % (hz, phase, drift, numpy.mean(hza), rr))
if dec != None:
dec.minute = samples_minute
dec.start = offset
if not (dec.msg in msgs):
already[int(hz / bin_hz)] = True
dec.phase0 = (phase == 0)
dec.phase1 = (phase == 1)
msgs[dec.msg] = dec
if phase == 0:
ssamples = self.subtract(ssamples, dec, numpy.add(dec.hza, 0.0))
if subgap > 0.0001:
ssamples = self.subtract(ssamples, dec, numpy.add(dec.hza, subgap))
ssamples = self.subtract(ssamples, dec, numpy.add(dec.hza, -subgap))
#elif dec.snr > msgs[dec.msg].snr:
# # we have a higher SNR.
# msgs[dec.msg] = dec
sys.stdout.flush()
for txt in msgs:
dec = msgs[txt]
dec.hza[0] += self.downhz
dec.hza[1] += self.downhz
dec.dt = (dec.start / float(self.jrate)) - 2.0 # convert to seconds
self.got_msg(dec)
def subtract(self, osamples, dec, hza):
padded = dec.msgbits + ([0] * 31)
encbits = fano_encode(padded)
# len(encbits) is 162, each element 0 or 1.
# interleave encbits, by bit-reversal of index.
ibits = numpy.zeros(162, dtype=numpy.int32)
p = 0
for i in range(0, 256):
j = bit_reverse(i, 8)
if j < 162:
ibits[j] = encbits[p]
p += 1
# combine with sync pattern to generate 162 symbols of 0..4.
four = numpy.multiply(ibits, 2)
four = numpy.add(four, numpy.divide(numpy.add(pattern, 1), 2))
bin_hz = self.jrate / float(self.jblock)
samples = numpy.copy(osamples)
assert dec.start >= 0
samples = samples[dec.start:]
bigslop = int(self.jblock * subslop)
# find amplitude of each symbol.
amps = [ ]
offs = [ ]
tones = [ ]
i = 0
while i < len(four):
nb = 1
while i+nb < len(four) and four[i+nb] == four[i]:
nb += 1
hz0 = hza[0] + (i / float(len(four))) * (hza[1] - hza[0])
hz = hz0 + four[i] * bin_hz
tone = weakutil.costone(self.jrate, hz, self.jblock*nb)
# nominal start of symbol in samples[]
i0 = i * self.jblock
i1 = i0 + nb*self.jblock
# search +/- slop.
# we search separately for each symbol b/c the
# phase may drift over the minute, and we
# want the tone to match exactly.
i0 = max(0, i0 - bigslop)
i1 = min(len(samples), i1 + bigslop)
cc = numpy.correlate(samples[i0:i1], tone)
mm = numpy.argmax(cc) # thus samples[i0+mm]
# what is the amplitude?
# if actual signal had a peak of 1.0, then
# correlation would be sum(tone*tone).
cx = cc[mm]
c1 = numpy.sum(tone * tone)
a = cx / c1
amps.append(a)
offs.append(i0+mm)
tones.append(tone)
i += nb
ai = 0
while ai < len(amps):
a = amps[ai]
off = offs[ai]
tone = tones[ai]
samples[off:off+len(tone)] -= tone * a
ai += 1
nsamples = numpy.append(osamples[0:dec.start], samples)
return nsamples
def hz0(self, hza, sym):
hz = hza[0] + (hza[1] - hza[0]) * (sym / float(len(pattern)))
return hz
# since there have been so many bugs in guess_offset().
def test_guess_offset(self):
mo = 0
bin_hz = self.jrate / float(self.jblock)
n = 0
sumabs = 0.0
sum = 0.0
cpu = 0.0
justone = False
starttime = time.time()
while time.time() < starttime + 10:
hz = 80 + random.random() * 240
if justone:
nstart = 0
else:
nstart = int(random.random() * 3000)
nend = 2000 + int(random.random() * 5000)
symbols = [ ]
for p in pattern:
if justone:
sym = 0
else:
sym = 2 * random.randint(0, 1)
if p > 0:
sym += 1
symbols.append(sym)
samples = numpy.random.normal(0, 0.5, nstart)
samples = numpy.append(samples, weakutil.fsk(symbols, [ hz, hz ], bin_hz, self.jrate, self.jblock))
samples = numpy.append(samples, numpy.random.normal(0, 0.5, nend))
if justone == False:
samples = samples * 1000
xf = FFTCache(samples, self.jrate, self.jblock)
self.guess_offset(xf, [hz+4*bin_hz,hz+4*bin_hz]) # prime the cache, for timing
t0 = time.time()
xa = self.guess_offset(xf, [hz,hz])
t1 = time.time()
x0start = xa[0][0]
x0abs = abs(nstart - x0start)
#print("%.1f %d: %d %d" % (hz, nstart, x0start, x0abs))
if abs(xa[1][0] - nstart) < x0abs:
print("%.1f %d: %d %d -- %d" % (hz, nstart, x0start, x0abs, xa[1][0]))
mo = max(mo, x0abs)
sumabs += x0abs
sum += x0start - nstart
cpu += t1 - t0
n += 1
if justone:
sys.exit(1)
# jul 18 2016 -- max diff was 53.
# jun 16 2017 -- max diff was 77 (but with different hz range).
# jun 16 2017 -- max diff 52, avg abs diff 17, avg diff -1
# jun 16 2017 -- max diff 33, avg abs diff 16, avg diff 0 (using tone, not bandpass filter)
# jul 8 2017 -- max diff 33, avg abs diff 16, avg diff 0, avg CPU 0.022
# jul 8 2017 -- max diff 32, avg abs diff 15, avg diff 0, avg CPU 0.114
# but this one uses FFTCache...
# jul 9 2017 -- max diff 32, avg abs diff 17, avg diff -2, avg CPU 0.006
print("max diff %d, avg abs diff %d, avg diff %d, avg CPU %.3f" % (mo, sumabs/n, sum/n, cpu / n))
# a signal starts at roughly offset=start,
# to within self.jblock/coarse_steps.
# return a better start.
def guess_start(self, xf, hza, start):
candidates = [ ]
step = int(self.jblock / coarse_steps)
start0 = start - step // 2
start0 = max(start0, 0)
start1 = start + step // 2
# the "/ 8" here is the FFTCache granule.
for start in range(start0, start1, self.jblock // 8):
# tones[0..162][0..4]
if start + len(pattern)*self.jblock > xf.len():
continue
tones = xf.get(hza, start)
tones = tones[0:162,:]
tone0 = tones[:,0]
tone1 = tones[:,1]
tone2 = tones[:,2]
tone3 = tones[:,3]
# we just care about sync vs no sync,
# so combine tones 0 and 2, and 1 and 3
syncs0 = numpy.maximum(tone0, tone2)
syncs1 = numpy.maximum(tone1, tone3)
# now syncs1 - syncs0.
# yields +/- that should match pattern.
tt = numpy.subtract(syncs1, syncs0)
strength = numpy.sum(numpy.multiply(tt, pattern))
candidates.append([ start, strength ])
candidates = sorted(candidates, key = lambda e : -e[1])
return candidates[0][0]
# returns an array of [ offset, strength ], sorted
# by strength, most-plausible first.
# xf is an FFTCache.
def guess_offset(self, xf, hza):
ret = [ ]
for off in range(0, self.jblock, goff_step):
# tones[0..162][0..4]
tones = xf.get(hza, off)
tone0 = tones[:,0]
tone1 = tones[:,1]
tone2 = tones[:,2]
tone3 = tones[:,3]
# we just care about sync vs no sync,
# so combine tones 0 and 2, and 1 and 3
syncs0 = numpy.maximum(tone0, tone2)
syncs1 = numpy.maximum(tone1, tone3)
# now syncs1 - syncs0.
# yields +/- that should match pattern.
tt = numpy.subtract(syncs1, syncs0)
cc = numpy.correlate(tt, pattern)
indices = list(range(0, len(cc)))
indices = sorted(indices, key=lambda i : -cc[i])
indices = indices[0:ngoff]
offsets = numpy.multiply(indices, self.jblock)
offsets = offsets + off
both = [ [ offsets[i], cc[indices[i]] ] for i in range(0, len(offsets)) ]
ret += both
ret = sorted(ret, key = lambda e : -e[1])
return ret
# returns an array of [ offset, strength ], sorted
# by strength, most-plausible first.
# oy: this version is the same quality as guess_offset(),
# but noticeably slower.
def fft_guess_offset(self, samples, hz):
bin_hz = self.jrate / float(self.jblock)
bin = int(round(hz / bin_hz))
# shift freq so hz in the middle of a bin
#samples = weakutil.freq_shift(samples,
# bin * bin_hz - hz,
# 1.0/self.jrate)
tones = [ [], [], [], [] ]
for off in range(0, len(samples), goff_step):
if off + self.jblock > len(samples):
break
a = numpy.fft.rfft(samples[off:off+self.jblock])
a = a[bin:bin+4]
a = abs(a)
tones[0].append(a[0])
tones[1].append(a[1])
tones[2].append(a[2])
tones[3].append(a[3])
if False:
for ti in range(0, 4):
for i in range(8, 24):
sys.stdout.write("%.0f " % (tones[ti][i]))
sys.stdout.write("\n")
# we just care about sync vs no sync,
# so combine tones 0 and 2, and 1 and 3
syncs0 = numpy.maximum(tones[0], tones[2])
syncs1 = numpy.maximum(tones[1], tones[3])
# now syncs1 - syncs0.
# yields +/- that should match pattern.
tt = numpy.subtract(syncs1, syncs0)
if False:
for i in range(0, 24):
sys.stdout.write("%.0f " % (tt[i]))
if (i % 8) == 7:
sys.stdout.write("| ")
sys.stdout.write("\n")
#z = numpy.repeat(pattern, int(self.jblock / goff_step))
z = [ ]
nfill = int(self.jblock / goff_step) - 1
for x in pattern:
z.append(x)
z = z + [0]*nfill
cc = numpy.correlate(tt, z)
if False:
for i in range(0, min(len(cc), 24)):
sys.stdout.write("%.0f " % (cc[i]))
if (i % 8) == 7:
sys.stdout.write("| ")
sys.stdout.write("\n")
indices = list(range(0, len(cc)))
indices = sorted(indices, key=lambda i : -cc[i])
offsets = numpy.multiply(indices, goff_step)
#offsets = numpy.subtract(offsets, ntaps / 2)
both = [ [ offsets[i], cc[indices[i]] ] for i in range(0, len(offsets)) ]
return both
# returns an array of [ offset, strength ], sorted
# by strength, most-plausible first.
def convolve_guess_offset(self, samples, hz):
bin_hz = self.jrate / float(self.jblock)
ntaps = self.jblock
# average y down to a much lower rate to make the
# correlate() go faster. 64 works well.
# filter each of the four tones
tones = [ ]
for tone in range(0, 4):
thz = hz + tone*bin_hz
taps = weakutil.costone(self.jrate, thz, ntaps)
# yx = lfilter(taps, 1.0, samples)
# yx = numpy.convolve(samples, taps, mode='valid')
# yx = scipy.signal.convolve(samples, taps, mode='valid')
yx = scipy.signal.fftconvolve(samples, taps, mode='valid')
# hack to match size of lfilter() output
yx = numpy.append(numpy.zeros(ntaps-1), yx)
yx = abs(yx)
# scipy.signal.resample(yx, len(yx) / goff_step) works, but too slow.
# re = weakutil.Resampler(goff_step*64, 64)
# yx = re.resample(yx)
yx = weakutil.moving_average(yx, goff_step)
yx = yx[0::goff_step]
tones.append(yx)
# we just care about sync vs no sync,
# so combine tones 0 and 2, and 1 and 3
#tones[0] = numpy.add(tones[0], tones[2])
#tones[1] = numpy.add(tones[1], tones[3])
tones[0] = numpy.maximum(tones[0], tones[2])
tones[1] = numpy.maximum(tones[1], tones[3])
# now tone1 - tone0.
# yields +/- that should match pattern.
tt = numpy.subtract(tones[1], tones[0])
z = numpy.repeat(pattern, int(self.jblock / goff_step))
cc = numpy.correlate(tt, z)
indices = list(range(0, len(cc)))
indices = sorted(indices, key=lambda i : -cc[i])
offsets = numpy.multiply(indices, goff_step)
offsets = numpy.subtract(offsets, ntaps / 2)
both = [ [ offsets[i], cc[indices[i]] ] for i in range(0, len(offsets)) ]
return both
# given hza[hz0,hz1], return a new hza adjusted to
# give stronger tones.
# start is offset in samples[].
def guess_freq(self, xf, hza, start):
more = 1
ss = xf.getmore(hza, start, more)
# ss has one element per symbol time.
# ss[i] is a 6-element FFT, with ss[i][1] as lowest tone.
# first symbol is in ss[0]
bin_hz = self.jrate / float(self.jblock)
diffs = [ ]
for pi in range(0, len(pattern)):
if pattern[pi] > 0:
sync = 1
else:
sync = 0
fft = ss[pi]
sig0 = fft[sync+more]
sig1 = fft[2+sync+more]
if sig0 > sig1:
bin = sync+more
else:
bin = 2+sync+more
if fft[bin] > fft[bin-1] and fft[bin] > fft[bin+1]:
xp = weakutil.parabolic(numpy.log(fft), bin) # interpolate
# xp[0] is a better bin number (with fractional bin)
diff = (xp[0] - bin) * bin_hz
if diff > bin_hz / 2:
diff = bin_hz / 2
elif diff < -bin_hz / 2:
diff = -bin_hz / 2
else:
diff = 0.0
diffs.append(diff)
nhza = [
hza[0] + numpy.mean(diffs[0:80]),
hza[1] + numpy.mean(diffs[81:162])
]
return nhza
# do a coarse pass over the band, looking for
# possible signals.
# bud is budget in seconds.
# returns [ fine_rank, noise ]
def coarse(self, samples):
bin_hz = self.jrate / float(self.jblock)
# WSPR signals officially lie between 1400 and 1600 Hz.
# we've down-converted to 100 - 300 Hz.
# search a bit wider than that.
min_hz = self.lowhz-20
max_hz = self.lowhz+200+20
# generate a few copies of samples corrected for various amounts of drift.
if ndrift <= 1:
drifts = [ 0.0 ]
else:
drifts = [ ]
driftstart = -driftmax
driftend = driftmax+0.001
driftinc = 2.0*driftmax / (ndrift - 1)
for drift in numpy.arange(driftstart, driftend, driftinc):