def handlerG(self, pdu): # To save the gain series in file: if pmt.to_float(pdu) != 999 and pmt.to_float( pdu) != 1 and pmt.to_float(pdu) != 0: self.count = self.count + 1 # RANDOM GAIN: if self.rGain: nGain = numpy.random.randint(0, 89) # RANDOM gain self.uhd_usrp_sink.set_gain(nGain) #This sets the RANDOM gain ganho = self.uhd_usrp_sink.get_gain( ) # This verifies the gain value on USRP #print "Ganho no USRP: %d" %(int(ganho)) self.serieGain.append(ganho) #print "Ganho TX %d" % (ganho) # arql = open(self.fn, "a") # arql.write(str(ganho)+'\n') elif pmt.to_float( pdu) == 999: # Sinaliza fim de arquivo e fila no mac vazia if self.cont999 == 1: self.cont999 = 2 elif self.cont999 == 2: #faz com que somente no segundo 999 (do buffer) eh que haja a chamada do stat self.statSummary()
def msg_handler_analyzed_data_in(self, msg): print("in msg_handler_analyzed_data_in") self.lock() gate_params = pmt.vector_ref(msg, 0) gate_type_PMT = pmt.dict_ref( gate_params, pmt.from_float( quantum_gate_param_type.quantum_gate_param_type.GATE_TYPE), pmt.PMT_NIL) if (pmt.eq(gate_type_PMT, pmt.PMT_NIL)): return gate_type = pmt.to_float(gate_type_PMT) print("gate_params.gate_type=" + str(gate_type)) qubit_id_PMT = pmt.dict_ref( gate_params, pmt.from_float( quantum_gate_param_type.quantum_gate_param_type.QUBIT_ID), pmt.PMT_NIL) if (pmt.eq(qubit_id_PMT, pmt.PMT_NIL)): return qubit_id = pmt.to_float(qubit_id_PMT) print("gate_params.qubit_id=" + str(qubit_id)) if (gate_type == quantum_gate_type.quantum_gate_type.X): print("in msg_handler_analyzed_data_in X gate") #回路を作る RO_STATE = self._qubit_stat_map[qubit_id] if (float(RO_STATE.angle) == 0.0): RO_STATE.angle = 180.0 else: RO_STATE.angle = 0.0 self._qubit_stat_map[qubit_id] = RO_STATE elif (gate_type == quantum_gate_type.quantum_gate_type.RO): print("in msg_handler_analyzed_data_in RO") #回路を実行する RO_STATE = self._qubit_stat_map[qubit_id] SIM_msg = pmt.make_dict() SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ID), pmt.from_float(qubit_id)) SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ANGLE), pmt.from_float(float(RO_STATE.angle))) SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.STATE), pmt.from_float(quantum_qubit_RO_state_type. quantum_qubit_RO_state_type.START)) self.message_port_pub(pmt.intern('simulated_data'), SIM_msg) RO_STATE.state = quantum_qubit_RO_state_type.quantum_qubit_RO_state_type.START self._qubit_stat_map[qubit_id] = RO_STATE self.unlock()
def msg_handler_QOBJ_in(self, msg): print("in msg_handler_QOBJ_in") self.lock() qubit_id_PMT = pmt.dict_ref( msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ID), pmt.PMT_NIL) if (pmt.eq(qubit_id_PMT, pmt.PMT_NIL)): return qubit_id = pmt.to_float(qubit_id_PMT) print("quantum_qubit_param_type.qubit_id=" + str(qubit_id)) if (this._qubit_id != qubit_id): return qubit_angle_PMT = pmt.dict_ref( msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ANGLE), pmt.PMT_NIL) if (pmt.eq(qubit_angle_PMT, pmt.PMT_NIL)): return qubit_angle = pmt.to_float(qubit_angle_PMT) print("quantum_qubit_param_type.qubit_angle=" + str(qubit_angle)) qubit_pole_PMT = pmt.dict_ref( msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.POLE), pmt.PMT_NIL) if (pmt.eq(qubit_pole_PMT, pmt.PMT_NIL)): return qubit_pole = pmt.to_float(qubit_pole_PMT) print("quantum_qubit_param_type.qubit_pole=" + str(qubit_pole)) e_ops = [sigmax(), sigmay(), sigmaz()] if (qubit_pole == 1.0): Z = sigmaz() else: Z = -sigmaz() if (qubit_angle == 0.0): Q = Z elif (qubit_angle > 0.0): Q = sigmax() * self.angle_converter(qubit_angle) Q = Q + Z elif (): Q = sigmax() * self.angle_converter(-qubit_angle) Q = Q + (-Z) # self._block_view.clear() self._block_view.add_vectors(expect(Q.unit(), e_ops)) self._block_view.make_sphere() self._block_view.show()
def dict_from_pdu(self, pdu): # build a simple dictionary out of burst metadata meta = pmt.car(pdu) burst_dict = {} burst_id = -1 try: burst_id = pmt.to_uint64(pmt.dict_ref(meta, self.pmt_burst_id, pmt.PMT_NIL)) burst_dict["start"] = pmt.to_uint64(pmt.dict_ref(meta, self.pmt_start_offset, pmt.PMT_NIL)) burst_dict["end"] = pmt.to_uint64(pmt.dict_ref(meta, self.pmt_end_offset, pmt.PMT_NIL)) burst_dict["rel_cf"] = pmt.to_float(pmt.dict_ref(meta, self.pmt_relative_frequency, pmt.PMT_NIL)) burst_dict["bw"] = pmt.to_float(pmt.dict_ref(meta, self.pmt_bandwidth, pmt.PMT_NIL)) except Exception as e: print(f"malformed burst (red) in the jpeg_convertor, {e}") return None, {} return burst_id, burst_dict
def test02(self): const = 123765 x_pmt = pmt.from_double(const) x_int = pmt.to_double(x_pmt) x_float = pmt.to_float(x_pmt) self.assertEqual(x_int, const) self.assertEqual(x_float, const)
def test_003_snr(self): nframes = 30 timeslots = 5 subcarriers = 1024 active_subcarriers = 936 overlap = 2 cp_len = subcarriers // 2 ramp_len = cp_len // 2 active_ratio = subcarriers / active_subcarriers subcarrier_map = get_subcarrier_map(subcarriers, active_subcarriers, dc_free=True) preambles = mapped_preamble(self.seed, self.filtertype, self.filteralpha, active_subcarriers, subcarriers, subcarrier_map, overlap, cp_len, ramp_len) core_preamble = preambles[1] sigenergy = calculate_energy(core_preamble) data = np.copy(core_preamble) snrs = np.arange(3, 3 * nframes, 3, dtype=np.float) snrs_lin = 10. ** (snrs / 10.) expected_snrs_lin = np.concatenate(((np.inf,), snrs_lin)) for i, snr_lin in enumerate(snrs_lin): nscale = calculate_noise_scale( snr_lin, sigenergy, active_ratio, core_preamble.size) noise = get_noise_vector(core_preamble.size, nscale) d = core_preamble + noise data = np.concatenate((data, d)) dut = gfdm.channel_estimator_cc( timeslots, subcarriers, active_subcarriers, True, 1, core_preamble) src = blocks.vector_source_c(data) snk = blocks.vector_sink_c() self.tb.connect(src, dut, snk) self.tb.run() res = np.array(snk.data()) self.assertEqual(res.size, nframes * timeslots * subcarriers) tags = snk.tags() snr_tags = [t for t in tags if pmt.eq(t.key, pmt.mp("snr_lin"))] for i, t in enumerate(snr_tags): self.assertEqual(t.offset, i * timeslots * subcarriers) res_lin = pmt.to_float(t.value) res_db = 10. * np.log10(res_lin) ref_db = 10. * np.log10(expected_snrs_lin[i]) # print(f"Reference: {ref_db:6.3f}dB\t{res_db:6.3f}dB") if np.isfinite(ref_db): self.assertTrue(np.abs(res_db - ref_db) < 1.)
def handler(self, pdu): estimativa = pmt.to_float(pdu) #Estimativa entre 0,0 e 1,0 # print "Estimativa: --- %6.2f" % (estimativa) newGain = 44.0 * ( 1 - estimativa ) + 45 #Normalização 89 - 45 = 44 --- 45 foi o minimo gain para tx # newGain = 0 # usado para fixar o valor durante a calibração # print "Ganho de Tx: --- %6.2f" % (newGain) # https://www.analog.com/media/en/technical-documentation/data-sheets/AD9361.pdf self.uhd_usrp_sink.set_gain(newGain) #This sets the gain
def test_001_t(self): # set up fg fft_len = 256 cp_len = 32 samp_rate = 32000 data = np.random.choice([-1, 1], [100, fft_len]) timefreq = np.fft.ifft(data, axis=0) #add cp timefreq = np.hstack((timefreq[:, -cp_len:], timefreq)) tx = np.reshape(timefreq, (1, -1)) # GR time! src = blocks.vector_source_c(tx[0].tolist(), True, 1, []) analyzer = ofdm_param_estim.ofdm_param_estimation_c( samp_rate, 0, 7000, [128, 256, 512, 1024], [8, 16, 32, 64]) snk = blocks.message_debug() # connect self.tb.connect(src, analyzer) self.tb.msg_connect((analyzer, 'ofdm_out'), (snk, 'store')) self.tb.start() time.sleep(0.25) self.tb.stop() self.tb.wait() # check data result = snk.get_message(0) fft_result = pmt.to_float(pmt.tuple_ref(pmt.tuple_ref(result, 4), 1)) cp_result = pmt.to_float(pmt.tuple_ref(pmt.tuple_ref(result, 5), 1)) self.assertAlmostEqual(fft_len, fft_result) self.assertAlmostEqual(cp_len, cp_result)
def test_001_t (self): # set up fg fft_len = 256 cp_len = 32 samp_rate = 32000 data = np.random.choice([-1, 1], [100, fft_len]) timefreq = np.fft.ifft(data, axis=0) #add cp timefreq = np.hstack((timefreq[:, -cp_len:], timefreq)) tx = np.reshape(timefreq, (1, -1)) # GR time! src = blocks.vector_source_c(tx[0].tolist(), True, 1, []) analyzer = inspector.ofdm_zkf_c(samp_rate, 0, 7000, [128, 256, 512, 1024], [8, 16, 32, 64]) snk = blocks.message_debug() # connect self.tb.connect(src, analyzer) self.tb.msg_connect((analyzer, 'ofdm_out'), (snk, 'store')) self.tb.start() time.sleep(0.25) self.tb.stop() self.tb.wait() # check data result = snk.get_message(0) fft_result = pmt.to_float(pmt.tuple_ref(pmt.tuple_ref(result, 4), 1)) cp_result = pmt.to_float(pmt.tuple_ref(pmt.tuple_ref(result, 5), 1)) self.assertAlmostEqual(fft_len, fft_result) self.assertAlmostEqual(cp_len, cp_result)
def test21_absolute_serialization_nums(self): # uint64 SERDES in_num = 9999876 in_str = b'\x0b\x00\x00\x00\x00\x00\x98\x96\x04' out_str = pmt.serialize_str(pmt.from_uint64(in_num)) self.assertEqual(out_str, in_str) in_str = b'\x0b\xff\xff\xff\xff\xff\xff\xff\xff' in_num = 0xffffffffffffffff out_num = pmt.to_uint64(pmt.deserialize_str(in_str)) self.assertEqual(out_num, in_num) # long int SERDES in_num = 2432141 in_str = b'\x03\x00%\x1c\x8d' out_str = pmt.serialize_str(pmt.from_long(in_num)) self.assertEqual(out_str, in_str) in_str = b'\x03\xfdy\xe4\xb7' in_num = -42343241 out_num = pmt.to_long(pmt.deserialize_str(in_str)) self.assertEqual(out_num, in_num) # float SERDES in_num = -1.11 in_str = b'\x04\xbf\xf1\xc2\x8f`\x00\x00\x00' out_str = pmt.serialize_str(pmt.from_float(in_num)) self.assertEqual(out_str, in_str) in_str = b'\x04@\x8e\xdd;`\x00\x00\x00' in_num = 987.6539916992188 out_num = pmt.to_float(pmt.deserialize_str(in_str)) self.assertEqual(out_num, in_num) # double SERDES in_num = 987654.321 in_str = b'\x04A.$\x0c\xa4Z\x1c\xac' out_str = pmt.serialize_str(pmt.from_double(in_num)) self.assertEqual(out_str, in_str) in_str = b'\x04\xbf\xdb\x19\x84@A\r\xbc' in_num = -.42343241 out_num = pmt.to_double(pmt.deserialize_str(in_str)) self.assertEqual(out_num, in_num)
def met_in9(self, msg): self.met9.append(pmt.to_float(msg))
def msg_handler_analyzed_data_in_circuit(self, msg): print("in msg_handler_analyzed_data_in") self.lock() gate_params = pmt.vector_ref(msg, 0) gate_type_PMT = pmt.dict_ref( gate_params, pmt.from_float( quantum_gate_param_type.quantum_gate_param_type.GATE_TYPE), pmt.PMT_NIL) if (pmt.eq(gate_type_PMT, pmt.PMT_NIL)): return gate_type = pmt.to_float(gate_type_PMT) print("gate_params.gate_type=" + str(gate_type)) qubit_id_PMT = pmt.dict_ref( gate_params, pmt.from_float( quantum_gate_param_type.quantum_gate_param_type.QUBIT_ID), pmt.PMT_NIL) if (pmt.eq(qubit_id_PMT, pmt.PMT_NIL)): return qubit_id = pmt.to_float(qubit_id_PMT) print("gate_params.qubit_id=" + str(qubit_id)) if (gate_type == quantum_gate_type.quantum_gate_type.X): print("in msg_handler_analyzed_data_in X gate") self._qubit_circuit.add_gate("RX", targets=qubit_id, arg_value=pi, index=this._qcircuit_index_cnt) elif (gate_type == quantum_gate_type.quantum_gate_type.Y): print("in msg_handler_analyzed_data_in Y gate") self._qubit_circuit.add_gate("RY", targets=qubit_id, arg_value=pi, index=this._qcircuit_index_cnt) elif (gate_type == quantum_gate_type.quantum_gate_type.Z): print("in msg_handler_analyzed_data_in Z gate") self._qubit_circuit.add_gate("RZ", targets=qubit_id, arg_value=pi, index=this._qcircuit_index_cnt) elif (gate_type == quantum_gate_type.quantum_gate_type.H): print("in msg_handler_analyzed_data_in H gate") self._qubit_circuit.add_gate("hadamard_transform", targets=qubit_id, index=this._qcircuit_index_cnt) elif (gate_type == quantum_gate_type.quantum_gate_type.S): print("in msg_handler_analyzed_data_in S gate") self._qubit_circuit.add_gate("RZ", targets=qubit_id, arg_value=pi / 2, index=this._qcircuit_index_cnt) elif (gate_type == quantum_gate_type.quantum_gate_type.T): print("in msg_handler_analyzed_data_in T gate") self._qubit_circuit.add_gate("RZ", targets=qubit_id, arg_value=pi / 4, index=this._qcircuit_index_cnt) elif (gate_type == quantum_gate_type.quantum_gate_type.INIT): print("in msg_handler_analyzed_data_in INIT gate") pass elif (gate_type == quantum_gate_type.quantum_gate_type.CNOT): print("in msg_handler_analyzed_data_in CNOT gate") self._qubit_circuit.add_gate("CNOT", controls=[0], targets=[1]) elif (gate_type == quantum_gate_type.quantum_gate_type.JUNC): print("in msg_handler_analyzed_data_in JUNC gate") pass elif (gate_type == quantum_gate_type.quantum_gate_type.RO): print("in msg_handler_analyzed_data_in RO") #回路を実行する RO_STATE = self._qubit_stat_map[qubit_id] SIM_msg = pmt.make_dict() SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ID), pmt.from_float(qubit_id)) SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ANGLE), pmt.from_float(float(RO_STATE.angle))) SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.STATE), pmt.from_float(quantum_qubit_RO_state_type. quantum_qubit_RO_state_type.START)) self.message_port_pub(pmt.intern('simulated_data'), SIM_msg) RO_STATE.state = quantum_qubit_RO_state_type.quantum_qubit_RO_state_type.START self._qubit_stat_map[qubit_id] = RO_STATE self.unlock()
def met_in0(self, msg): self.met0.append(pmt.to_float(msg))
def met_in2(self, msg): self.met2.append(pmt.to_float(msg))
def met_in1(self, msg): self.met1.append(pmt.to_float(msg))
def met_in4(self, msg): self.met4.append(pmt.to_float(msg))
def met_in3(self, msg): self.met3.append(pmt.to_float(msg))
def gr2fits(filename, merge=True, verbose=False): try: handle = open(filename, 'rb') except: raise IOError('File %s does not exist' % filename) nheaders = 0 nread = 0 baseband = [] fitsout = fits.HDUList() while (True): """ /opt/local/bin/gr_read_file_metadata note that there can be > 1 metadata blocks I think they can come every 1e6 items """ # read out next header bytes hdr_start = handle.tell() header_str = handle.read(parse_file_metadata.HEADER_LENGTH) if (len(header_str) == 0): break # Convert from string to PMT (should be a dictionary) try: header = pmt.deserialize_str(header_str) except RuntimeError: raise IOError( "Could not deserialize header: invalid or corrupt data file.\n" ) if verbose: print("HEADER {0}".format(nheaders)) info = parse_file_metadata.parse_header(header, verbose) if (info["extra_len"] > 0): extra_str = handle.read(info["extra_len"]) if (len(extra_str) == 0): break try: extra = pmt.deserialize_str(extra_str) except RuntimeError: sys.stderr.write( "Could not deserialize extras: invalid or corrupt data file.\n" ) break if verbose: print("\nExtra Header:") extra_info = parse_file_metadata.parse_extra_dict( extra, info, verbose) nheaders += 1 nread += parse_file_metadata.HEADER_LENGTH + info["extra_len"] handle.seek(nread, 0) h = extra_info if h['size'] == 8 and h['cplx']: dtype = scipy.complex64 d = scipy.fromfile(handle, dtype=dtype, count=h['nitems']) t0 = np.arange(2 * len(d)) / h['rx_rate'] / 2 t = np.arange(len(d)) / h['rx_rate'] nread += info['nbytes'] handle.seek(nread, 0) fitsout.append(fits.ImageHDU(data=np.c_[d.real, d.imag])) fitsout[-1].header['NITEMS'] = (h['nitems'], 'Number of complex samples') fitsout[-1].header['RATE'] = (h['rx_rate'], '[Hz] sample rate') fitsout[-1].header['RX_FREQ'] = (pmt.to_float(h['rx_freq']) / 1e6, '[MHz] Radio frequency') fitsout[-1].header['RX_TIME'] = (h['rx_time'], '[s] Time of start of block') if merge: totallen = 0 for i in xrange(0, len(fitsout)): totallen += fitsout[i].header['NAXIS2'] d = np.zeros((totallen, 2), dtype=fitsout[1].data.dtype) nmax = 0 for i in xrange(0, len(fitsout)): d[nmax:nmax + fitsout[i].header['NAXIS2']] = fitsout[i].data nmax += fitsout[i].header['NAXIS2'] newfitsout = fits.HDUList() newfitsout.append(fits.PrimaryHDU(data=d)) newfitsout[0].header = fitsout[1].header newfitsout[0].header['NITEMS'] = totallen newfitsout[0].header['EXPTIME'] = (d.shape[0] / newfitsout[0].header['RATE'], '[s] Duration of file') fitsout = newfitsout fitsout.verify('silentfix') if os.path.exists(filename + '.fits'): os.remove(filename + '.fits') fitsout.writeto(filename + '.fits') print('Wrote %s.fits' % filename) return fitsout
def met_in5(self, msg): self.met5.append(pmt.to_float(msg))
def met_in6(self, msg): self.met6.append(pmt.to_float(msg))
def met_in7(self, msg): self.met7.append(pmt.to_float(msg))
def __init__(self, fname='', add_metadata=False, metadata_format='', data_type='uint8', precision=0): gr.sync_block.__init__(self, name="csv_writer", in_sig=None, out_sig=None) self.fname = fname self.add_metadata = add_metadata self.metadata_format = metadata_format self.data_type = data_type self.precision = precision self.fid = None # setup logger logger_name = 'gr_log.' + self.to_basic_block().alias() if logger_name in gr.logger_get_names(): self.log = gr.logger(logger_name) else: self.log = gr.logger('log') # metadata field mappings self.metadata_mappings = { 'string': lambda x: pmt.symbol_to_string(x), 'bool': lambda x: pmt.to_bool(x), 'long': lambda x: pmt.to_long(x), 'uint64': lambda x: pmt.to_uint64(x), 'float': lambda x: pmt.to_float(x), 'double': lambda x: pmt.to_double(x), 'complex': lambda x: pmt.to_complex(x), 'time': lambda x: float(pmt.to_uint64(pmt.car(x))) + pmt.to_double( pmt.cdr(x)), 'time_tuple': lambda x: float(pmt.to_uint64(pmt.tuple_ref(x, 0))) + pmt. to_double(pmt.tuple_ref(x, 1)) } # data type parsers self.data_type_mappings = { 'uint8': lambda x: pmt.u8vector_elements(x), 'int8': lambda x: pmt.s8vector_elements(x), 'uint16': lambda x: pmt.u16vector_elements(x), 'int16': lambda x: pmt.s16vector_elements(x), 'uint32': lambda x: pmt.u32vector_elements(x), 'int32': lambda x: pmt.s32vector_elements(x), 'float': lambda x: pmt.f32vector_elements(x), 'complex float': lambda x: pmt.c32vector_elements(x), 'double': lambda x: pmt.f64vector_elements(x), 'complex double': lambda x: pmt.c64vector_elements(x) } # check data type if data_type not in self.data_type_mappings.keys(): raise ValueError('Invalid data type') self.find_metadata = False self.header = [] if self.add_metadata: if self.metadata_format == '': # set flag to load metadata on first message received self.find_metadata = True else: self.parse_header_format() # register message handler self.message_port_name = pmt.intern('in') self.message_port_register_in(self.message_port_name) self.set_msg_handler(self.message_port_name, self.message_handler)
def FER_in(self,msg): # Envia mensaje: FERv=pmt.cdr(msg) FER=pmt.to_float(FERv) self.d_FER=np.float64(FER)
def met_in8(self, msg): self.met8.append(pmt.to_float(msg))