forked from rtmrtmrtmrtm/weakmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jt65.py
executable file
·1859 lines (1576 loc) · 57.8 KB
/
jt65.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 JT65
#
# inspired by the QEX May/June 2016 article by K9AN and K1JT
# about soft-decision JT65 decoding.
#
# much information and code from the WSJT-X source distribution.
#
# uses Phil Karn's Reed-Solomon software.
#
# Robert Morris, AB1HL
#
import numpy
import wave
import weakaudio
import weakutil
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
import multiprocessing
from scipy.signal import lfilter
import ctypes
from ctypes import c_int, byref, cdll
import resource
import collections
import gc
#
# performance tuning parameters.
#
budget = 9 # CPU seconds (9)
noffs = 4 # look for sync every jblock/noffs (2)
off_scores = 1 # consider off_scores*noffs starts per freq bin (3, 4)
pass1_frac = 0.2 # fraction budget to spend before subtracting (0.5, 0.9, 0.5)
hetero_thresh = 6 # zero out bin that wins too many times (9, 5, 7)
soft_iters = 75 # try r-s soft decode this many times (35, 125, 75)
subslop = 0.01 # search in this window to match subtraction symbols
subgap = 1.3 # extra subtract()s this many hz on either side of main bin
# information about one decoded signal.
class Decode:
def __init__(self,
hza,
nerrs,
msg,
snr,
minute,
start,
twelve,
decode_time):
self.hza = hza
self.nerrs = nerrs
self.msg = msg
self.snr = snr
self.minute = minute
self.start = start
self.dt = 0.0 # XXX
self.twelve = twelve
self.decode_time = decode_time
def hz(self):
return numpy.mean(self.hza)
# Phil Karn's Reed-Solomon decoder.
# copied from wsjt-x, along with wrapkarn.c.
librs = cdll.LoadLibrary("librs/librs.so")
# the JT65 sync pattern
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
]
# start of special 28-bit callsigns, e.g. CQ.
NBASE = 37*36*10*27*27*27
# start of special grid locators for sig strength &c.
NGBASE = 180*180
# does this decoded message contain text that's generated
# mistakenly from noise by the reed-solomon decoder?
def broken_msg(msg):
bads = [ "OL6MWK", "1S9LND", "9M3QHC", "TIKK+", "J87FOE", "000AAA",
"TG7HQQ", "475IVR", "L16RAH", "XO2QLH", "5E8HML", "HF7VBA",
"F11XTN", "7T4EUZ", "EF5KYD", "A80CCM", "HF7VBA",
"VV3EZD", "DT8ZBT", "8Z9RTD", "7U0NNP", "6P8CGY", "WH9ASY",
"V96TCU", "BF3AUF", "7B5JDP", "1HFXR1", "28NTV",
"388PNI", "TN2CQQ", "Y99CGR", "R21KIC", "X26DPX", "QG4YMT",
"Y99CGR", "0L6MWK", "KG0EEY", "777SZP", "JU3SJO", "J76LH4XC5EO20",
"A7FVFZOQH3", "GI5OF44MGO", "LN3CWS", "QTJNYSW6", "1FHXR1",
"RG9CP6Z", "HIKGWR", "U5A9R7", "MF0ZG3", "9OOATN", "SVUW5S",
"7MD2HY", "D5F2Q4Y", "L9HTT", "51FLJM", "6ZNDRN", "HTTROP",
"ED0Z9O", "CDP7W2", "Q0TZ20VS", "TYKFVKV", "12VPKMR", "XNC34V",
"GO950IZ", "MU6BNL", "302KDY", " CM5 K ", "892X722B8CSC",
"8+YL.D0E-MUR.", "W7LH./", "HHW7LH.",
]
for bad in bads:
if bad in msg:
return True
return False
# weighted choice, to pick symbols to ignore in soft decode.
# a[i] = [ value, weight ]
def wchoice(a, n):
total = 0.0
for e in a:
total += e[1]
ret = [ ]
got = [ False ] * len(a)
while len(ret) < n:
x = random.random() * total
for ai in range(0, len(a)):
if got[ai] == False:
e = a[ai]
if x <= e[1]:
ret.append(e[0])
total -= e[1]
got[ai] = True
break
x -= e[1]
return ret
def wchoice_test():
a = [ [ "a", .1 ], [ "b", .1 ], [ "c", .4 ], [ "d", .3 ], [ "e", .1 ] ]
counts = { }
for iter in range(0, 500):
x = wchoice(a, 2)
assert len(x) == 2
for e in x:
counts[e] = counts.get(e, 0) + 1
print(counts)
very_first_time = True
class JT65:
debug = False
offset = 0
def __init__(self):
self.done = False
self.msgs_lock = threading.Lock()
self.msgs = [ ]
self.verbose = False
self.enabled = True # True -> run process(); False -> don't
self.jrate = int(11025/2) # sample rate for processing (FFT &c)
self.jblock = int(4096/2) # samples per symbol
weakutil.init_freq_from_fft(self.jblock)
# set self.start_time to the UNIX time of the start
# of a UTC minute.
now = int(time.time())
gm = time.gmtime(now)
self.start_time = now - gm.tm_sec
# seconds per cycle
def cycle_seconds(self):
return 60
# return the minute number for t, a UNIX time in seconds.
# truncates down, so best to pass a time mid-way through a minute.
def minute(self, t):
dt = t - self.start_time
dt /= 60.0
return int(dt)
# convert cycle number to UNIX time.
def minute2time(self, m):
return (m * 60) + self.start_time
def second(self, t):
dt = t - self.start_time
dt /= 60.0
m = int(dt)
return 60.0 * (dt - m)
def seconds_left(self, t):
return 60 - self.second(t)
# 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(1024)
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 = [ ]
n = 0
while True:
buf = self.readwav(chan)
if buf.size < 1:
break
bufbuf.append(buf)
n += len(buf)
if n >= 60*self.cardrate:
samples = numpy.concatenate(bufbuf)
self.process(samples[0:60*self.cardrate], 0)
bufbuf = [ samples[60*self.cardrate:] ]
n = len(bufbuf[0])
if n >= 49*self.cardrate:
samples = numpy.concatenate(bufbuf)
bufbuf = None
self.process(samples, 0)
def opencard(self, desc):
# self.cardrate = 11025 # XXX
self.cardrate = int(11025 / 2) # XXX jrate
self.audio = weakaudio.new(desc, self.cardrate)
def gocard(self):
samples_time = time.time()
bufbuf = [ ]
nsamples = 0
while self.done == False:
sec = self.second(samples_time)
if sec < 48 or nsamples < 48*self.cardrate:
# give lower-level audio a chance to use
# bigger batches, may help resampler() quality.
time.sleep(1.0)
else:
time.sleep(0.2)
[ buf, buf_time ] = self.audio.read()
if len(buf) > 0:
bufbuf.append(buf)
nsamples += len(buf)
samples_time = buf_time
if numpy.max(buf) > 30000 or numpy.min(buf) < -30000:
sys.stderr.write("!")
# wait until we have enough samples through 49th second of minute.
# we want to start on the minute (i.e. a second before nominal
# start time), and end a second after nominal end time.
# thus through 46.75 + 2 = 48.75.
sec = self.second(samples_time)
if sec >= 49 and nsamples >= 49*self.cardrate:
# we have >= 49 seconds of samples, and second of minute is >= 49.
samples = numpy.concatenate(bufbuf)
bufbuf = [ ]
# sample # of start of minute.
i0 = len(samples) - self.cardrate * self.second(samples_time)
i0 = int(i0)
t = samples_time - (len(samples)-i0) * (1.0/self.cardrate)
self.process(samples[i0:], t)
samples = None
nsamples = 0
def close(self):
# ask gocard() thread to stop.
self.done = True
# received a message, add it to the list.
# dec is a Decode.
def got_msg(self, dec):
self.msgs_lock.acquire()
# already in msgs with worse nerrs?
found = False
for i in range(max(0, len(self.msgs)-40), len(self.msgs)):
xm = self.msgs[i]
if xm.minute == dec.minute and abs(xm.hz() - dec.hz()) < 10 and xm.msg == dec.msg:
# we already have this msg
found = True
if dec.nerrs < xm.nerrs:
self.msgs[i] = dec
if found == False:
self.msgs.append(dec)
self.msgs_lock.release()
# return a list of all messages received
# since the last call to get_msgs().
# each msg is a Decode.
def get_msgs(self):
self.msgs_lock.acquire()
a = self.msgs
self.msgs = [ ]
self.msgs_lock.release()
return a
# fork the real work, to try to get more multi-core parallelism.
def process(self, samples, samples_time):
global budget
global very_first_time
if very_first_time:
# warm things up.
very_first_time = False
thunk = (lambda dec : self.got_msg(dec))
self.process0(samples, samples_time, thunk, 0, 2580)
return
sys.stdout.flush()
# parallelize the work by audio frequency: one thread
# gets the low half, the other thread gets the high half.
# the ranges have to overlap so each can decode
# overlapping (interfering) transmissions.
rca = [ ] # connections on which we'll receive
pra = [ ] # child processes
tha = [ ] # a thread to read from each child
txa = [ ]
npr = 2
for pi in range(0, npr):
min_hz = pi * int(2580 / npr)
min_hz = max(min_hz - 50, 0)
max_hz = (pi + 1) * int(2580 / npr)
max_hz = min(max_hz + 175, 2580)
txa.append(time.time())
recv_conn, send_conn = multiprocessing.Pipe(False)
p = multiprocessing.Process(target=self.process00,
args=[samples, samples_time, send_conn,
min_hz, max_hz])
p.start()
send_conn.close()
pra.append(p)
rca.append(recv_conn)
th = threading.Thread(target=lambda c=recv_conn: self.readchild(c))
th.start()
tha.append(th)
for pi in range(0, len(rca)):
t0 = time.time()
pra[pi].join(budget+2.0)
if pra[pi].is_alive():
print("\n%s child process still alive, enabled=%s\n" % (self.ts(time.time()),
self.enabled))
pra[pi].terminate()
pra[pi].join(2.0)
t1 = time.time()
tha[pi].join(2.0)
if tha[pi].isAlive():
t2 = time.time()
print("\n%s reader thread still alive, enabled=%s, %.1f %.1f %.1f\n" % (self.ts(t2),
self.enabled,
t0-txa[pi],
t1-t0,
t2-t1))
rca[pi].close()
def readchild(self, recv_conn):
while True:
try:
dec = recv_conn.recv()
# x is a Decode
self.got_msg(dec)
except:
break
# in child process.
def process00(self, samples, samples_time, send_conn, min_hz, max_hz):
gc.disable() # no point since will exit soon
thunk = (lambda dec : send_conn.send(dec))
self.process0(samples, samples_time, thunk, min_hz, max_hz)
send_conn.close()
# for each decode, call thunk(Decode).
# only look at sync tones from min_hz .. max_hz.
def process0(self, samples, samples_time, thunk, min_hz, max_hz):
global budget, noffs, off_scores, pass1_frac, subgap
if self.enabled == False:
return
if self.verbose:
print("len %d %.1f, type %s, rates %.1f %.1f" % (len(samples),
len(samples) / float(self.cardrate),
type(samples[0]),
self.cardrate,
self.jrate))
sys.stdout.flush()
# for budget.
t0 = time.time()
# samples_time is UNIX time that samples[0] was
# sampled by the sound card.
samples_minute = self.minute(samples_time + 30)
if self.cardrate != self.jrate:
# reduce rate from self.cardrate to self.jrate.
assert self.jrate >= 2 * 2500
if False:
filter = weakutil.butter_lowpass(2500.0, self.cardrate, order=10)
samples = scipy.signal.lfilter(filter[0],
filter[1],
samples)
samples = weakutil.resample(samples, self.cardrate, self.jrate)
else:
# resample in pieces so that we can preserve float32,
# since lfilter insists on float64.
rs = weakutil.Resampler(self.cardrate, self.jrate)
resampleblock = self.cardrate # exactly one second works best
si = 0
ba = [ ]
while si < len(samples):
block = samples[si:si+resampleblock]
nblock = rs.resample(block)
nblock = nblock.astype(numpy.float32)
ba.append(nblock)
si += resampleblock
samples = numpy.concatenate(ba)
# assume samples[0] is at the start of the minute, so that
# signals ought to start one second into samples[].
# pad so that there two seconds before the start of
# the minute, and a few seconds after 0:49.
pad0 = 2 # add two seconds to start
endsec = 49 + 4 # aim to have padded samples end on 0:53
sm = numpy.mean(abs(samples[2000:5000]))
r0 = (numpy.random.random(self.jrate*pad0) - 0.5) * sm * 2
r0 = r0.astype(numpy.float32)
if len(samples) >= endsec*self.jrate:
# trim at end
samples = numpy.concatenate([ r0, samples[0:endsec*self.jrate] ])
else:
# pad at end
needed = endsec*self.jrate - len(samples)
r1 = (numpy.random.random(needed) - 0.5) * sm * 2
r1 = r1.astype(numpy.float32)
samples = numpy.concatenate([ r0, samples, r1 ])
[ noise, scores ] = self.scores(samples, min_hz, max_hz)
# scores[i] = [ bin, correlation, valid, start ]
bin_hz = self.jrate / float(self.jblock)
ssamples = numpy.copy(samples) # for subtraction
already = { } # suppress duplicate msgs
subalready = { }
decodes = 0
# first without subtraction.
# don't blow the whole budget, to ensure there's time
# to start decoding on subtracted signals.
i = 0
while i < len(scores) and ((decodes < 1 and (time.time() - t0) < budget) or
(decodes > 0 and (time.time() - t0) < budget * pass1_frac)):
hz = scores[i][0] * (self.jrate / float(self.jblock))
dec = self.process1(samples, hz, noise, scores[i][3], already)
if dec != None:
decodes += 1
dec.minute = samples_minute
thunk(dec)
if not dec.msg in subalready:
ssamples = self.subtract_v4(ssamples, dec.hza,
dec.start, dec.twelve)
ssamples = self.subtract_v4(ssamples, numpy.add(dec.hza, subgap),
dec.start, dec.twelve)
ssamples = self.subtract_v4(ssamples, numpy.add(dec.hza, -subgap),
dec.start, dec.twelve)
subalready[dec.msg] = True
i += 1
nfirst = i
# re-score subtracted samples.
[ junk_noise, scores ] = self.scores(ssamples, min_hz, max_hz)
# now try again, on subtracted signal.
# we do a complete new pass since a strong signal might have
# been unreadable due to another signal at a somewhat higher
# frequency.
i = 0
while i < len(scores) and (time.time() - t0) < budget:
hz = scores[i][0] * (self.jrate / float(self.jblock))
dec = self.process1(ssamples, hz, noise, scores[i][3], already)
if dec != None:
decodes += 1
dec.minute = samples_minute
thunk(dec)
# this subtract() is important for performance.
if not dec.msg in subalready:
ssamples = self.subtract_v4(ssamples, dec.hza,
dec.start, dec.twelve)
ssamples = self.subtract_v4(ssamples, numpy.add(dec.hza, subgap),
dec.start, dec.twelve)
ssamples = self.subtract_v4(ssamples, numpy.add(dec.hza, -subgap),
dec.start, dec.twelve)
subalready[dec.msg] = True
i += 1
if self.verbose:
print("%d..%d, did %d of %d, %d hits, maxrss %.1f MB" % (
min_hz,
max_hz,
nfirst+i,
len(scores),
decodes,
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / (1024.0*1024.0)))
# assign a score to each frequency bin,
# according to how similar it seems to a sync tone pattern.
# samples should have already been padded.
# returns [ noise, scores ]
# noise is for SNR.
# scores[i] is [ sync_bin, score, True, start ]
def scores(self, samples, min_hz, max_hz):
bin_hz = self.jrate / float(self.jblock)
minbin = max(5, int(min_hz / bin_hz))
maxbin = int(max_hz / bin_hz)
offs = [ int((x*self.jblock)/noffs) for x in range(0, noffs) ]
m = []
noises = numpy.zeros(self.jblock//2 + 1) # for SNR
nnoises = 0
for oi in range(0, len(offs)):
m.append([])
si = offs[oi]
while si + self.jblock <= len(samples):
block = samples[si:si+self.jblock]
# block = block * scipy.signal.blackmanharris(len(block))
# a = numpy.fft.rfft(block)
# a = abs(a)
a = weakutil.arfft(block)
m[oi].append(a)
noises = numpy.add(noises, a)
nnoises += 1
si += self.jblock
noises /= nnoises
# calculate noise for snr, mimicing wsjtx wsprd.c.
# first average in freq domain over 7-bin window.
# then noise from 30th percentile.
nn = numpy.convolve(noises, [ 1, 1, 1, 1, 1, 1, 1 ])
nn = nn / 7.0
nn = nn[6:]
nns = sorted(nn[minbin:maxbin])
noise = nns[int(0.3*len(nns))]
# scores[i] = [ bin, correlation, valid, start ]
scores = [ ]
# for each frequency bin, strength of correlation with sync pattern.
# searches (w/ correlation) for best match to sync pattern.
# tries different offsets in time (from offs[]).
for j in range(minbin, maxbin):
for oi in range(0, len(offs)):
v = [ ]
for mx in m[oi]:
v.append(mx[j])
cc = numpy.correlate(v, pattern)
indices = list(range(0, len(cc)))
indices = sorted(indices, key=lambda i : -cc[i])
indices = indices[0:off_scores]
for ii in indices:
scores.append([ j, cc[ii], True, offs[oi] + ii*self.jblock ])
# highest scores first.
scores = sorted(scores, key=lambda sc : -sc[1])
return [ noise, scores ]
# subtract a decoded signal (hz/start/twelve) from the samples,
# to that we can then decode weaker signals underneath it.
# i.e. interference cancellation.
# generates the right tone for each symbol, finds the best
# offset w/ correlation, finds the amplitude, subtracts in the time domain.
def subtract_v4(self, osamples, hza, start, twelve):
global subslop
sender = JT65Send()
bin_hz = self.jrate / float(self.jblock)
# the 126 symbols, each 0..66
symbols = sender.symbols(twelve)
samples = numpy.copy(osamples)
if start < 0:
samples = numpy.append([0.0]*(-start), samples)
else:
samples = samples[start:]
bigslop = int(self.jblock * subslop)
#bigslop = int((self.jblock / hza[0]) / 2.0) + 1
#bigslop = int(self.jblock / hza[0]) + 1
# find amplitude of each symbol.
amps = [ ]
offs = [ ]
tones = [ ]
i = 0
while i < 126:
nb = 1
while i+nb < 126 and symbols[i+nb] == symbols[i]:
nb += 1
sync_hz = self.sync_hz(hza, i)
hz = sync_hz + symbols[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
if start < 0:
nsamples = samples[(-start):]
else:
nsamples = numpy.append(osamples[0:start], samples)
return nsamples
# this doesn't work, probably because phase is not
# coherent over the message.
def subtract_v5(self, osamples, hza, start, twelve):
sender = JT65Send()
samples = numpy.copy(osamples)
assert start >= 0
symbols = sender.symbols(twelve)
bin_hz = self.jrate / float(self.jblock)
msg = sender.fsk(symbols, hza, bin_hz, self.jrate, self.jblock)
slop = int((self.jblock / hza[0]) / 2.0) + 1
i0 = start - slop
i1 = start + len(msg) + slop
cc = numpy.correlate(samples[i0:i1], msg)
mm = numpy.argmax(cc) # thus msg starts at 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(msg * msg)
a = cx / c1
samples[i0+mm:i0+mm+len(msg)] -= msg * a
return samples
# a signal begins near samples[start0], at frequency hza[0]..hza[1].
# return a better guess at the start.
def guess_start(self, samples, hza, start0):
bin_hz = self.jrate / float(self.jblock)
offs = [ ]
slop = self.jblock // noffs
i = 0
while i < 126:
nb = 0
while i+nb < 126 and pattern[nb+i] == 1:
nb += 1
if nb > 0:
hz = self.sync_hz(hza, i)
tone = weakutil.costone(self.jrate, hz, self.jblock*nb)
i0 = start0 + i * self.jblock
i1 = i0 + nb*self.jblock
cc = numpy.correlate(samples[i0-slop:i1+slop], tone)
mm = numpy.argmax(cc)
offs.append(i0-slop+mm - i0)
i += nb
else:
i += 1
medoff = numpy.median(offs)
start = int(start0 + medoff)
return start
# the sync tone is believed to be hz to within one fft bin.
# return hz with higher resolution.
# returns a two-element array of hz at start, hz at end.
def guess_freq(self, samples, hz):
bin_hz = self.jrate / float(self.jblock)
bin = int(round(hz / bin_hz))
freqs = [ ]
for i in range(0, len(pattern)):
if pattern[i] == 1:
sx = samples[i*self.jblock:(i+1)*self.jblock]
ff = weakutil.freq_from_fft(sx, self.jrate,
bin_hz * (bin - 1),
bin_hz * (bin + 2))
if ff != None and not numpy.isnan(ff):
freqs.append(ff)
if len(freqs) < 1:
return None
# nhz = numpy.median(freqs)
# nhz = numpy.mean(freqs)
# return nhz
# frequencies at 1/4 and 3/4 way through samples.
n = len(freqs)
m1 = numpy.median(freqs[0:n//2])
m2 = numpy.median(freqs[n//2:])
# frequencies at start and end.
m0 = m1 - (m2 - m1) / 2.0
m3 = m2 + (m2 - m1) / 2.0
hza = [ m0, m3 ]
return hza
# given hza[hz0,hzn] from guess_freq(),
# and a symbol number (0..126),
# return the sync bin.
# the point is to correct for frequency drift.
def sync_bin(self, hza, sym):
hz = self.sync_hz(hza, sym)
bin_hz = self.jrate / float(self.jblock) # FFT bin size, in Hz
bin = int(round(hz / bin_hz))
return bin
def sync_hz(self, hza, sym):
hz = hza[0] + (hza[1] - hza[0]) * (sym / 126.0)
return hz
# xhz is the sync tone frequency.
# returns None or a Decode
def process1(self, samples, xhz, noise, start, already):
if len(samples) < 126*self.jblock:
return None
bin_hz = self.jrate / float(self.jblock) # FFT bin size, in Hz
dec = self.process1a(samples, xhz, start, noise, already)
return dec
# returns a Decode, or None
def process1a(self, samples, xhz, start, noise, already):
global hetero_thresh
bin_hz = self.jrate / float(self.jblock) # FFT bin size, in Hz
assert start >= 0
#if start < 0:
# samples = numpy.append([0.0]*(-start), samples)
#else:
# samples = samples[start:]
if len(samples) - start < 126*self.jblock:
return None
hza = self.guess_freq(samples[start:], xhz)
if hza == None:
return None
if self.sync_bin(hza, 0) < 5:
return None
if self.sync_bin(hza, 125) < 5:
return None
if self.sync_bin(hza, 0) + 2+64 > self.jblock/2:
return None
if self.sync_bin(hza, 125) + 2+64 > self.jblock/2:
return None
start = self.guess_start(samples, hza, start)
if start < 0:
return None
if len(samples) - start < 126*self.jblock:
return None
samples = samples[start:]
m = [ ]
for i in range(0, 126):
# block = block * scipy.signal.blackmanharris(len(block))
sync_bin = self.sync_bin(hza, i)
sync_hz = self.sync_hz(hza, i)
freq_off = sync_hz - (sync_bin * bin_hz)
block = samples[i*self.jblock:(i+1)*self.jblock]
# block = weakutil.freq_shift(block, -freq_off, 1.0/self.jrate)
# a = numpy.fft.rfft(block)
a = weakutil.fft_of_shift(block, -freq_off, self.jrate)
a = abs(a)
m.append(a)
# look for bins that win too often, perhaps b/c they are
# syncs from higher-frequency JT65 transmissions.
wins = [ 0 ] * 66
for pi in range(0,126):
if pattern[pi] == -1:
bestj = None
bestv = None
sync_bin = self.sync_bin(hza, pi)
for j in range(sync_bin+2, sync_bin+2+64):
if j < len(m[pi]) and (bestj == None or m[pi][j] > bestv):
bestj = j
bestv = m[pi][j]
if bestj != None:
wins[bestj-sync_bin] += 1
# zero out bins that win too often. a given symbol
# (bin) should only appear two or three times in
# a transmission.
for j in range(2, 66):
if wins[j] >= hetero_thresh:
# zero bin j
for pi in range(0,126):
sync_bin = self.sync_bin(hza, pi)
m[pi][sync_bin+j] = 0
# for each non-sync time slot, decide which tone is strongest,
# which yields the channel symbol.
sa = [ ]
strength = [ ] # symbol signal / mean of bins in same time slot
sigs = [ ] # for SNR
for pi in range(0,126):
if pattern[pi] == -1:
sync_bin = self.sync_bin(hza, pi)
a = sorted(list(range(0,64)), key=lambda bin: -m[pi][sync_bin+2+bin])
sa.append(a[0])
b0 = sync_bin+2+a[0] # bucket w/ strongest signal
s0 = m[pi][b0] # level of strongest symbol
sigs.append(s0)
if False:
# bucket w/ 2nd-strongest signal
b1 = sync_bin+2+a[1]
s1 = m[pi][b1] # second-best bin power
if s1 != 0.0:
strength.append(s0 / s1)
else:
strength.append(0.0)
if True:
# mean of bins in same time slot
s1 = numpy.mean(m[pi][sync_bin+2:sync_bin+2+64])
if s1 != 0.0:
strength.append(s0 / s1)
else:
strength.append(0.0)
if False:
# median of bins in same time slot
s1 = numpy.median(m[pi][sync_bin+2:sync_bin+2+64])
if s1 != 0.0:
strength.append(s0 / s1)
else:
strength.append(0.0)
[ nerrs, msg, twelve ] = self.process2(sa, strength)
if nerrs < 0 or broken_msg(msg):
return None
# SNR
sig = numpy.mean(sigs)
# power rather than voltage.
rawsnr = (sig*sig) / (noise*noise)
# the "-1" turns (s+n)/n into s/n
rawsnr -= 1
if rawsnr < 0.1:
rawsnr = 0.1
rawsnr /= (2500.0 / 2.7) # 2.7 hz noise b/w -> 2500 hz b/w
snr = 10 * math.log10(rawsnr)
snr = snr - 63 # empirical, to match wsjt-x 1.7
if self.verbose and not (msg in already):
print("%6.1f %5d: %2d %3.0f %s" % ((hza[0]+hza[1])/2.0, start, nerrs, snr, msg))
already[msg] = True
return Decode(hza, nerrs, msg, snr, None,
start, twelve, time.time())
# sa[] is 63 channel symbols, each 0..63.
# it needs to be un-gray-coded, un-interleaved,
# un-reed-solomoned, &c.
# strength[] indicates how sure we are about each symbol
# (ratio of winning FFT bin to second-best bin).
def process2(self, sa, strength):
global soft_iters
# un-gray-code
for i in range(0, len(sa)):
sa[i] = weakutil.gray2bin(sa[i], 6)
# un-interleave
un = [ 0 ] * 63
un_strength = [ 0 ] * 63
for c in range(0, 7):
for r in range(0, 9):
un[(r*7)+c] = sa[(c*9)+r]
un_strength[(r*7)+c] = strength[(c*9)+r]
sa = un
strength = un_strength
[nerrs,twelve] = self.rs_decode(sa, [])
if nerrs >= 0:
# successful decode.
sym0 = twelve[0]
if numpy.array_equal(twelve, [sym0]*12):
# a JT69 signal...
return [-1, "???", None]
msg = self.unpack(twelve)
if not broken_msg(msg):
#self.analyze1(sa, strength, twelve)
return [nerrs, msg, twelve]
if True:
# attempt soft decode
# at this point we know there must be at least 25
# errors, since otherwise Reed-Solomon would have
# decoded.
# map from strength to probability of incorrectness,
# from analyze1() and analyze1.py < analyze1
# this are for strength = sym / (mean of other sym bins in this time slot)
sm = [ 1.0, 1.0, 0.837, 0.549, 0.318, 0.276, 0.215, 0.171,