-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsigmath.py
1533 lines (1162 loc) · 43.9 KB
/
sigmath.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
import os
import collections
import csv
import difflib
import errno
import hashlib
import itertools
import logging
import math
import numpy as np
import random
import scipy
import socket
import string
import struct
import sys
import time
from itertools import chain, repeat
from numpy.fft import fft, fftshift
# from scipy import ndimage
import numpy as np
import inspect
import matplotlib.pyplot as plt
# import pyximport;pyximport.install()
# import zmq
# from osibase import OsiBase
from filterelement import FilterElement
# from sigmathcython import *
# converts string types to complex
def raw_to_complex(str):
f1 = struct.unpack('%df' % 1, str[0:4])
f2 = struct.unpack('%df' % 1, str[4:8])
f1 = f1[0]
f2 = f2[0]
return f1 + f2*1j
def complex_to_raw(n):
s1 = struct.pack('%df' % 1, np.real(n))
s2 = struct.pack('%df' % 1, np.imag(n))
return s1 + s2
# converts complex number to a pair of int16's, called ishort in gnuradio
def complex_to_ishort(c):
short = 2**15-1
re = struct.pack("h", np.real(c)*short)
im = struct.pack("h", np.imag(c)*short)
return re+im
# i first, q second
def complex_to_ishort_multi(floats, endian=""):
rr = np.real(floats)
ii = np.imag(floats)
zz = np.array((rr,ii)).transpose()
zzz = zz.reshape(len(floats)*2) * (2**15-1)
bytes = struct.pack(endian+"%sh" % len(zzz), *zzz)
return bytes
# q first, i second
def complex_to_ishort_multi_rev(floats, endian=""):
rr = np.real(floats)
ii = np.imag(floats)
zz = np.array((ii,rr)).transpose()
zzz = zz.reshape(len(floats)*2) * (2**15-1)
bytes = struct.pack(endian+"%sh" % len(zzz), *zzz)
return bytes
# i first, q second
def ishort_to_complex_multi(ishort_bytes, endian=""):
packed = struct.unpack(endian+"%dh" % int(len(ishort_bytes)/2), ishort_bytes)
rere = sig_everyn(packed, 2, 0)
imim = sig_everyn(packed, 2, 1)
floats_recovered = list(itertools.imap(np.complex, rere, imim))
return floats_recovered
# q first, i second
def ishort_to_complex_multi_rev(ishort_bytes, endian=""):
packed = struct.unpack(endian+"%dh" % int(len(ishort_bytes)/2), ishort_bytes)
rere = sig_everyn(packed, 2, 1)
imim = sig_everyn(packed, 2, 0)
floats_recovered = list(itertools.imap(np.complex, rere, imim))
return floats_recovered
def complex_to_raw_multi(floats, endian=""):
rr = np.real(floats)
ii = np.imag(floats)
zz = np.array((rr,ii)).transpose()
zzz = zz.reshape(len(floats)*2)
bytes = struct.pack(endian+"%sf" % len(zzz), *zzz)
return bytes
def raw_to_complex_multi(raw_bytes):
packed = struct.unpack("%df" % int(len(raw_bytes)/4), raw_bytes)
rere = sig_everyn(packed, 2, 0)
imim = sig_everyn(packed, 2, 1)
floats_recovered = list(itertools.imap(np.complex, rere, imim))
return floats_recovered
# a pretty-print for hex strings
# def get_rose(data):
# try:
# ret = ' '.join("{:02x}".format(ord(c)) for c in data)
# except TypeError, e:
# ret = str(data)
# return ret
# def print_rose(data):
# print get_rose(data)
# def get_rose_int(data):
# # adding int values
# try:
# ret = ' '.join("{:02}".format(ord(c)) for c in data)
# except TypeError, e:
# ret = str(data)
# return ret
# if you want to go from the pretty print version back to a string (this would not be used in production)
def reverse_rose(input):
orig2 = ''.join(input.split(' '))
orig = str(bytearray.fromhex(orig2))
return orig
# this is meant to replace print comma like functionality for ben being lazy
def s_(*args):
out = ''
for arg in args:
out += str(arg)+' '
out = out[:-1]
return out
def print_hex(str, ascii = False):
print('hex:')
tag = ''
for b in str:
if ascii:
if b in string.printable:
tag = b
else:
tag = '?'
print (' ', format(ord(b), '02x'), tag)
def print_dec(str):
print('hex:')
for b in str:
print (' ', ord(b))
# http://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def str_to_bits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return result
def bits_to_str(bits):
chars = []
for b in range(len(bits) / 8):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
def all_to_ascii(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(all_to_ascii, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(all_to_ascii, data))
else:
return data
def floats_to_bytes(rf):
return ''.join([complex_to_ishort(x) for x in rf])
def bytes_to_floats(rxbytes):
packed = struct.unpack("%dh" % int(len(rxbytes)/2), rxbytes)
rere = sig_everyn(packed, 2, 0)
imim = sig_everyn(packed, 2, 1)
assert len(rere) == len(imim)
rx = list(itertools.imap(np.complex, rere, imim))
def drange(start, end=None, inc=None):
"""A range function, that does accept float increments..."""
import math
if end == None:
end = start + 0.0
start = 0.0
else: start += 0.0 # force it to be a float
if inc == None:
inc = 1.0
count = int(math.ceil((end - start) / inc))
L = [None,] * count
L[0] = start
for i in range(1,count):
L[i] = L[i-1] + inc
return L
def unroll_angle(input):
thresh = np.pi
adjust = 0
sz = len(input)
output = [None]*sz
output[0] = input[0]
for index in range(1,sz):
samp = input[index]
prev = input[index-1]
if(abs(samp-prev) > thresh):
direction = 1
if( samp > prev ):
direction = -1
adjust = adjust + 2*np.pi*direction
output[index] = input[index] + adjust
return output
def bits_cpm_range(bits):
bits = [(b*2)-1 for b in bits] # convert to -1,1
return bits
def bits_binary_range(bits):
bits = [int((b+1)/2) for b in bits] # convert to ints with range of 0,1
return bits
def ip_to_str(address):
return socket.inet_ntop(socket.AF_INET, address)
# def nonblock_read(sock, size):
# try:
# buf = sock.read()
# except IOError, e:
# err = e.args[0]
# if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
# return None # No data available
# else:
# # a "real" error occurred
# print e
# sys.exit(1)
# else:
# if len(buf) == 0:
# return None
# return buf
# returns None if socket doesn't have any data, otherwise returns a list of bytes
# you need to set os.O_NONBLOCK on the socket at creation in order for this function to work
# fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
# def nonblock_socket(sock, size):
# # this try block is the non blocking way to grab UDP bytes
# try:
# buf = sock.recv(size)
# except socket.error, e:
# err = e.args[0]
# if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
# return None # No data available
# else:
# # a "real" error occurred
# print e
# sys.exit(1)
# else:
# # got data
# return buf
# def nonblock_socket_from(sock, size):
# # this try block is the non blocking way to grab UDP bytes
# try:
# buf, addr = sock.recvfrom(size)
# except socket.error, e:
# err = e.args[0]
# if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
# return None, None # No data available
# else:
# # a "real" error occurred
# print e
# sys.exit(1)
# else:
# # got data
# return buf, addr
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i+n]
def save_rf_grc(filename, data):
dumpfile = open(filename, 'w')
for s in data:
dumpfile.write(complex_to_raw(s))
dumpfile.close()
def read_rf_grc(filename, max_samples=None):
file = open(filename, 'r')
piece_size = 8
dout = []
sample_count = 0
while True:
bytes = file.read(piece_size)
if bytes == "":
break # end of file
dout.append(raw_to_complex(bytes))
sample_count += 1
if max_samples is not None and sample_count >= max_samples:
break
return dout
# write rf to a csv file
# to read file from matlab
# k = csvread('Y:\home\ubuntu\python-osi\qam4.csv');
# kc = k(:,1) + k(:,2)*1j;
def save_rf(filename, data):
dumpfile = open(filename, 'w')
for s in data:
print >> dumpfile, np.real(s), ',', np.imag(s)
dumpfile.close()
# read rf from a csv file
# if your file is dc in matlab, run this:
# dcs = [real(dc) imag(dc)];
# csvwrite('filename.csv',dcs);
# csvwrite('h3packetshift.csv', [real(dc) imag(dc)]);
def read_rf(filename):
# read a CSV file
file = open(filename, 'r')
reader = csv.reader(file, delimiter=',', quotechar='|')
data = []
for row in reader:
data.append(float(row[0]) + float(row[1])*1j)
file.close()
return data
def read_rf_hack(filename):
# read a CSV file
file = open(filename, 'r')
reader = csv.reader(file, delimiter=',', quotechar='|')
data = []
for row in reader:
data.append(float(row[0]))
data.append(float(row[1]))
file.close()
return data
# basic logging setup
def setup_logger(that, name, prefix=None):
if prefix is None:
prefix = name
that.log = logging.getLogger(name)
that.log.setLevel(logging.INFO)
# create console handler and set level to debug
lch = logging.StreamHandler()
lch.setLevel(logging.INFO)
lfmt = logging.Formatter(prefix+': %(message)s')
# add formatter to channel
lch.setFormatter(lfmt)
# add ch to logger
that.log.addHandler(lch)
# convert a list of bits to an unsigned int
# h is the number of bits we are expecting in the list
def bit_list_unsigned_int(lin, h):
sym = 0
for j in range(h):
try:
sym += lin[j]*2**(h-j-1)
except IndexError:
sym += 0
return sym
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return (idx,array[idx])
def tone_gen(samples, fs, hz):
assert type(samples) == type(0)
assert type(fs) in (int, long)
inc = 1.0/fs * 2 * np.pi * hz
if hz == 0:
args = np.array([0] * samples)
else:
args = np.linspace(0, (samples-1) * inc, samples) * np.array([1j] * samples)
return np.exp(args)
## pass in raw rf data first, and your ideal search wave second
# pass show to nplot the result
# pass everything to return all data, defaults to false
def typical_xcorr(data, search, show=False,everything=False):
xcr = np.correlate(data, search, 'full')
absxcr = abs(xcr) # save absolute value
xcrscore, xcridx = sig_max(absxcr) # find the max of the abs (score), and the index of that
peakxcr = xcr[xcridx] # apply the index to the non abs xcr, to get a sample we can take the angle of
sampleangle = np.angle(peakxcr)
if show:
nplot(absxcr, "abs of xcorr output")
if everything:
return xcridx, peakxcr, sampleangle, xcrscore, xcr
else:
return xcridx, peakxcr, sampleangle
#fixme, get lags out
def mat_nicename(H):
return "Matrix (h,w) %d %d"%(H.shape[0],H.shape[1])
# inplace modifies H
def mat_switch_rows(H, ida, idb):
t = np.copy(H[ida,:])
H[ida,:] = H[idb,:]
H[idb,:] = t
return None
# inplace
def mat_switch_cols(H, ida, idb):
t = np.copy(H[:,ida])
H[:,ida] = H[:,idb]
H[:,idb] = t
return None
def o_map_psk(din):
res = []
pairwise = zip(din[::2], din[1::2])
for cut in pairwise:
if cut == (0,0):
res.append(2)
elif cut == (0,1):
res.append(1)
elif cut == (1,0):
res.append(3)
elif cut == (1,1):
res.append(0)
return res
# Returns baked output from the matlab command:
# rrcFilter = rcosdesign(rolloff, span, sps);
# if a new set of params is passed, this returns None
def o_rrc_filter_lookup(rolloff, span, sps):
rrcFilter = None
if rolloff == 0.25 and span == 6 and sps == 4:
rrcFilter = [-0.0187733440045221, 0.003013558666422, 0.0326772345462546, 0.0470935833402524, 0.0265495177022908, -0.0275222240300177, -0.0852248750170832, -0.0994474359919262, -0.0321472673983147, 0.119037148179254, 0.311176411555479, 0.472003895565433, 0.534632070178156, 0.472003895565433, 0.311176411555479, 0.119037148179254, -0.0321472673983147, -0.0994474359919262, -0.0852248750170832, -0.0275222240300177, 0.0265495177022908, 0.0470935833402524, 0.0326772345462546, 0.003013558666422, -0.0187733440045221]
elif rolloff == 0.25 and span == 8 and sps == 6:
rrcFilter = [0.00866532792410113, 0.00658252680452728, 0.000689062625426406, -0.0074712343335428, -0.0149894394106519, -0.0184751723085405, -0.0153182803408426, -0.00491214847998965, 0.0106347206341242, 0.0266632859560034, 0.0371116854587008, 0.0364198115321213, 0.0216633198102528, -0.00577076737254631, -0.0396028976063981, -0.069540009878394, -0.083558519268118, -0.0710847620356398, -0.0262308544541024, 0.0498600699425154, 0.148327139837451, 0.253907215811741, 0.348041615194585, 0.413040313779774, 0.436237887518672, 0.413040313779774, 0.348041615194585, 0.253907215811741, 0.148327139837451, 0.0498600699425154, -0.0262308544541024, -0.0710847620356398, -0.083558519268118, -0.069540009878394, -0.0396028976063981, -0.00577076737254631, 0.0216633198102528, 0.0364198115321213, 0.0371116854587008, 0.0266632859560034, 0.0106347206341242, -0.00491214847998965, -0.0153182803408426, -0.0184751723085405, -0.0149894394106519, -0.0074712343335428, 0.000689062625426406, 0.00658252680452728, 0.00866532792410113]
elif rolloff == 0.25 and span == 10 and sps == 8:
rrcFilter = [-0.00265291895695268, -0.0038367285758387, -0.00404178046649392, -0.00307918477864112, -0.00103711397846142, 0.00170441339943213, 0.0045271711482077, 0.00669247991307441, 0.00750358793759834, 0.00648076379403586, 0.00351054324124175, -0.00106825247595824, -0.00646958364590197, -0.0115675402132076, -0.0150962227680158, -0.0159112035315436, -0.0132645947847634, -0.0070368939631878, 0.0021292761993053, 0.0128349930785245, 0.0230886023735744, 0.0306157954214996, 0.0332746952178824, 0.0295092014286344, 0.0187589698439958, 0.00174365601293929, -0.0194462504520092, -0.0414910755739182, -0.0602169454952409, -0.0711634708322952, -0.0702661145770751, -0.0545489915088333, -0.0227141459386971, 0.0244771507857901, 0.0841075268503736, 0.151324993567835, 0.219866476897559, 0.282817489474821, 0.333501607917967, 0.366369319357036, 0.37775250739262, 0.366369319357036, 0.333501607917967, 0.282817489474821, 0.219866476897559, 0.151324993567835, 0.0841075268503736, 0.0244771507857901, -0.0227141459386971, -0.0545489915088333, -0.0702661145770751, -0.0711634708322952, -0.0602169454952409, -0.0414910755739182, -0.0194462504520092, 0.00174365601293929, 0.0187589698439958, 0.0295092014286344, 0.0332746952178824, 0.0306157954214996, 0.0230886023735744, 0.0128349930785245, 0.0021292761993053, -0.0070368939631878, -0.0132645947847634, -0.0159112035315436, -0.0150962227680158, -0.0115675402132076, -0.00646958364590197, -0.00106825247595824, 0.00351054324124175, 0.00648076379403586, 0.00750358793759834, 0.00669247991307441, 0.0045271711482077, 0.00170441339943213, -0.00103711397846142, -0.00307918477864112, -0.00404178046649392, -0.0038367285758387, -0.00265291895695268]
elif rolloff == 0.5 and span == 10 and sps == 8:
rrcFilter = [-0.000227360782730039200000,0.001088738429480835300000,0.002084746204746209700000,0.002371375200663914500000,0.001768451863687256400000,0.000392002682105138340000,-0.001351170708598336100000,-0.002870096591219498600000,-0.003572812300043569700000,-0.003072796427970129000000,-0.001351170708598331300000,0.001186149711456712000000,0.003789539707901269900000,0.005576181317467936900000,0.005816879270585570100000,0.004213430128940225500000,0.001071843690013067400000,-0.002702793301169967200000,-0.005816879270585570900000,-0.006968996504726427200000,-0.005305355591061771000000,-0.000815566309429241660000,0.005469024296707546000000,0.011574239347020513000000,0.015005811660182994000000,0.013431057725172559000000,0.005469024296707539000000,-0.008615925345214449000000,-0.026526777955308903000000,-0.044010343226686024000000,-0.055454249046249099000000,-0.054933726077336487000000,-0.037514529150457464000000,-0.000532406049215232180000,0.055454249046249134000000,0.126292748642899940000000,0.204584829987635860000000,0.280739008412446870000000,0.344548530692574790000000,0.386989294703540040000000,0.401870228675680950000000,0.386989294703540040000000,0.344548530692574790000000,0.280739008412446870000000,0.204584829987635860000000,0.126292748642899940000000,0.055454249046249134000000,-0.000532406049215232180000,-0.037514529150457464000000,-0.054933726077336487000000,-0.055454249046249099000000,-0.044010343226686024000000,-0.026526777955308903000000,-0.008615925345214449000000,0.005469024296707539000000,0.013431057725172559000000,0.015005811660182994000000,0.011574239347020513000000,0.005469024296707546000000,-0.000815566309429241660000,-0.005305355591061771000000,-0.006968996504726427200000,-0.005816879270585570900000,-0.002702793301169967200000,0.001071843690013067400000,0.004213430128940225500000,0.005816879270585570100000,0.005576181317467936900000,0.003789539707901269900000,0.001186149711456712000000,-0.001351170708598331300000,-0.003072796427970129000000,-0.003572812300043569700000,-0.002870096591219498600000,-0.001351170708598336100000,0.000392002682105138340000,0.001768451863687256400000,0.002371375200663914500000,0.002084746204746209700000,0.001088738429480835300000,-0.000227360782730039200000]
return rrcFilter
# pass in any sparse, this will convert to bsr sparse and save
def fancy_save_sparse(filename, H):
Hsparse = scipy.sparse.bsr_matrix(H, dtype=np.int16)
save_sparse_csr(filename, Hsparse)
# def fancy_load_sparse(filename):
# loader = np.load(filename)
# bsr = scipy.sparse.bsr_matrix(( loader['data'], loader['indices'], loader['indptr']), shape = loader['shape'])
# only pass type of bsr
def save_sparse_csr(filename, array):
assert type(array) == scipy.sparse.bsr.bsr_matrix
np.savez(filename, data=array.data, indices=array.indices, indptr=array.indptr, shape=array.shape )
def load_sparse_csr(filename):
loader = np.load(filename)
return scipy.sparse.bsr_matrix(( loader['data'], loader['indices'], loader['indptr']), shape = loader['shape'])
def runningMean(x, N):
y = np.zeros((len(x),))
for ctr in range(len(x)):
y[ctr] = np.sum(x[ctr:(ctr+N)])
return y/N
# ---------------- Beginning of matplotlib
##
# @defgroup nplot Plotting related helper functions
# @{
#
_nplot_figure = 0
##
# Plot the sparsity pattern of 2-D array
# @param A the 2-D array
# @param title The plot title (string)
def nplotspy(A, title=""):
fig = nplotfigure()
plt.title(title)
plt.spy(A, precision=0.01, markersize=3)
return fig
def ncplot(rf, title=None, newfig=True):
fig = None
if newfig:
fig = nplotfigure()
if title is not None:
plt.title(title)
plt.plot(np.real(rf))
plt.plot(np.imag(rf), 'r')
return fig
def nplot(rf, title=None, newfig=True):
fig = None
if newfig:
fig = nplotfigure()
if title is not None:
plt.title(title)
plt.plot(np.real(rf))
return fig
def nplotdots(rf, title="", hold=False):
fig = None
if hold:
plt.hold(True)
else:
fig = nplotfigure()
plt.title(title)
plt.plot(range(len(rf)), np.real(rf), '-ko')
return fig
def nplotqam(rf, title="", newfig=True):
fig = None
if newfig:
fig = nplotfigure()
if title is not None:
plt.title(title)
plt.plot(np.real(rf), np.imag(rf), '.b', alpha=0.6)
return fig
def nplotfftold(rf, title="", hold=False):
fig = None
if hold:
plt.hold(True)
else:
fig = nplotfigure()
plt.title(title)
plt.plot(abs(fftshift(fft(rf))))
return fig
def sig_peaks(bins, hz, num = 1, peaksHzSeparation = 1):
binsabs = np.abs(bins)
llen = len(bins)
# approx method, assumes all bins are evenly spaces (they better be)
binstep = hz[1] - hz[0]
hzsepinbins = np.ceil(peaksHzSeparation / binstep)
res = []
for i in range(num):
maxval,peakidx = sig_max(binsabs)
res.append(peakidx)
lowbin = int(np.max([0,peakidx-hzsepinbins]))
highbin = int(np.min([llen,peakidx+hzsepinbins]))
binsabs[lowbin:highbin] = 0.
return res
def nplotfft(rf, fs = 1, title=None, newfig=True, peaks=False, peaksHzSeparation=1, peaksFloat=1.1):
fig = None
if newfig is True:
fig = nplotfigure()
if title is not None:
plt.title(title)
N = len(rf)
X = fftshift(fft(rf)/N)
absbins = 2*np.abs(X)
df = fs/N
f = np.linspace(-fs/2, fs/2-df, N)
plt.plot(f, absbins)
plt.xlabel('Frequency (in hertz)')
plt.ylabel('Magnitude Response')
if peaks:
peaksres = sig_peaks(X, f, peaks, peaksHzSeparation)
if type(newfig) is type(True):
ax = fig.add_subplot(111)
else:
ax = newfig
for pk in peaksres:
maxidx = pk
maxval = absbins[pk]
lbl = s_('hz:', f[maxidx])
ax.annotate(lbl, xy=(f[maxidx], maxval), xytext=(f[maxidx], maxval * peaksFloat),
arrowprops=dict(facecolor='black'),
)
return fig
def nplothist(x, title = "", bins = False):
fig = nplotfigure()
plt.title(title)
# more options
# n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
if bins is not False:
plt.hist(x, bins)
else:
plt.hist(x)
# plt.xlabel('x')
# plt.ylabel('y')
# plt.axis([40, 160, 0, 0.03])
plt.grid(True)
return fig
def nplotber(bers, ebn0, titles, title = ""):
assert(len(bers) == len(ebn0) == len(titles))
fig = nplotfigure()
maintitle = "BER of ("
for i in range(len(bers)):
# check if any values are positive
if any(k > 0 for k in bers[i]):
# if so plot normally
plt.semilogy(ebn0[i], bers[i], '-s', linewidth=2)
maintitle += titles[i] + ', '
else:
# if all values are zero, don't plot (doing so forever prevents this plot window from drawing new lines)
maintitle += 'ValueError: Data has no positive values, and therefore can not be log-scaled.' + ', '
maintitle += ")"
gridcolor = '#B0B0B0'
plt.grid(b=True, which='major', color=gridcolor, linestyle='-')
plt.grid(b=True, which='minor', color=gridcolor, linestyle='dotted')
plt.legend(titles)
plt.xlabel('Eb/No (dB)')
plt.ylabel('BER')
if title == "":
plt.title(maintitle)
else:
plt.title(title)
return fig
def nplotmulti(xVals, yVals, legends, xLabel ='x', yLabel ='y', title ='', semilog = False, newfig=True, style='-s'):
assert(len(yVals) == len(xVals) == len(legends))
fig = None
if newfig:
fig = nplotfigure()
plt.title(title)
for i in range(len(yVals)):
if semilog == True:
plt.semilogy(xVals[i], yVals[i], style, linewidth=2)
elif semilog == False:
plt.plot(xVals[i], yVals[i], style, linewidth=2)
gridcolor = '#B0B0B0'
plt.grid(b=True, which='major', color=gridcolor, linestyle='-')
plt.grid(b=True, which='minor', color=gridcolor, linestyle='dotted')
plt.legend(legends)
plt.xlabel(xLabel)
plt.ylabel(yLabel)
return fig
def nplotangle(angle, title = None, newfig=True):
global _nplot_figure
fig = None
if newfig:
fig = plt.figure(_nplot_figure, figsize=(7.,6.))
_nplot_figure += 1
res = 100
cir = np.exp(1j*np.array(range(res+1))/(res/np.pi/2))
cir = np.concatenate(([0],cir))
cir = cir * np.exp(1j*angle)
plt.plot(np.real(cir), np.imag(cir), 'b', alpha=0.6, linewidth=3.0)
if title is not None:
plt.title(title)
else:
plt.title(s_("angle:", angle))
return fig
def nplotshow():
plt.show()
def nplotfigure():
global _nplot_figure
fig = plt.figure(_nplot_figure)
_nplot_figure += 1
return fig
def nplotresponselinear(b, a, cutoff, fs):
w, h = scipy.signal.freqz(b, a, worN=8000)
nplotfigure()
plt.plot(0.5 * fs * w / np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5 * np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5 * fs)
plt.title("Linear Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
## Plots frequency response of digital filter
# @param b b coefficients
# @param a a coefficients
# @param mode set mode 'frequency' and also pass in fs to display units in hz, or set mode 'radians'
# @param title graph title
# @param fs fs of filter in 'frequency' mode
# @param cutoff draw a vertial line at the filters cutoff if you know it
def nplotresponse(b, a, mode='frequency', title='', fs=0, cutoff=None):
w, h = scipy.signal.freqz(b, a)
fig = nplotfigure()
plt.title(title)
ax1 = fig.add_subplot(111)
if mode == 'frequency':
wplot = 0.5 * fs * w / np.pi
xlab = 'Frequency [Hz]'
elif mode == 'radians':
wplot = w
xlab = 'Frequency [rad/sample]'
else:
assert 0
plt.plot(wplot, 20 * np.log10(abs(h)), 'b')
plt.ylabel('Amplitude [dB]', color='b')
plt.xlabel(xlab)
ax2 = ax1.twinx()
angles = np.unwrap(np.angle(h))
plt.plot(wplot, angles, 'g')
plt.ylabel('Angle (radians)', color='g')
plt.grid()
plt.axis('tight')
if cutoff is not None:
plt.axvline(cutoff, color='k')
return fig
def nplottext(str, newfig=True):
fig = None
if newfig == True:
fig = nplotfigure()
plt.title('txt')
ax = fig.add_subplot(111)
else:
ax = newfig
ax.set_aspect(1)
bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
ax.text(0, 0, str, ha="center", va="center", size=14,
bbox=bbox_props)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
return fig
##
# @}
#
def rand_string_ascii(len):
return ''.join(random.choice(string.ascii_letters) for _ in range(len))
def sigflatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
def sigdup(listt, count=2):
# return list(flatten([y for y in repeat([y for y in listt], count)]))
return list(sigflatten([repeat(x, count) for x in listt]))
## wrapper around numpy's built in FFT that returns frequency of each bin
# note that this function returns data that has already been fftshift'd
# @param data data to fft
# @param fs samples per second to be used for bin calculation
# @returns (fft_data, bins)
def sig_fft(data, fs):
dt = 1 / fs # % seconds per sample
N = len(data)
# Fourier Transform:
X = fftshift(fft(data)/N)
# %% Frequency specifications:
dF = float(fs) / N # % hertz
# f = -Fs/2:dF:Fs/2-dF;# % hertz
bins = drange(-fs / 2, fs / 2, dF)
return X, bins
# %% Plot the spectrum:
# figure;
# plot(f,2*abs(X));
# xlabel('Frequency (in hertz)');
# title('Magnitude Response');
# disp('Each bin is ');
# disp(dF);
def sig_rms(x):
return np.sqrt(np.mean(x * np.conj(x)))
# returns the FIRST occurrence of the maximum
# this is the fastest by FAR, but it requires that data be an ndarray
# behaves like matlab max() do not pass in complex values and assume that this works
def sig_max(data):
idx = np.argmax(data)
m = data[idx]
return (m, idx)
def sig_max2(data):
m = max(data)
idx = [i for i, j in enumerate(data) if j == m]
idx = idx[0]
return (m, idx)
def sig_max3(data):
m = max(data)
idx = data.index(m)
return (m, idx)
def sig_max4(data):
m = max(data)
idx = data.index(m)
return (m, idx)
def sig_everyn(data, n, phase=0):
l = len(data)
assert phase < n, "Phase must be less than n"
assert n <= l, "n must be less than or equal length of data"
# subtract the phase from length, and then grab that many elements from the end of data
# this is the same as removing 'phase' elements from the beginning
if phase != 0:
phaseapplied = data[-1*(l-phase):]
# after applying phase, return every nth element from that
return phaseapplied[::n]
else:
return data[::n]
# http://stackoverflow.com/questions/17904097/python-difference-between-two-strings/17904977#17904977
# def sig_diff(a,b,max=False):
# at = time.time()
# count = 0
# # print('{} => {}'.format(a,b))
# for i,s in enumerate(difflib.ndiff(a, b)):
# if s[0]==' ': continue
# elif s[0]=='-':
# try:
# c = u'{}'.format(s[-1])
# except:
# c = ' '
# print(u'Delete "{}" from position {}'.format(c,i))
# elif s[0]=='+':
# print(u'Add "{}" to position {}'.format(s[-1],i))
# count += 1
# if max and count >= max:
# print "stopping after", count, "differences"
# break
# print()
# bt = time.time()
# print "sig_diff() ran in ", bt-at
# def sig_diff2(a, b, unused=False):
# lmin = min(len(a),len(b))
# lmax = max(len(a),len(b))
#
# errors = 0
# for i in range(lmin):
# if a[i] != b[i]:
# errors += 1
#
# errors += lmax-lmin
# if lmax != lmin:
# print "Strings were", errors, "different with additional", lmax-lmin, "due to length differences"
# else:
# print "Strings were", errors, "different"