Skip to content

Commit

Permalink
FIX: Codestyle
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoVogt committed Nov 4, 2024
1 parent 881856c commit 5665e54
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 90 deletions.
98 changes: 48 additions & 50 deletions basil/HL/tdl_tdc.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ class tdl_tdc(RegisterHardwareLayer):

GHZ_S_FREQ = 0.48
CLK_DIV = 3
word_type_codes = {0 : 'TRIGGERED',
1 : 'RISING',
2 : 'FALLING',
3 : 'TIMESTAMP',
4 : 'CALIB',
5 : 'MISS',
6 : 'RST'}
word_type_codes = {0: 'TRIGGERED',
1: 'RISING',
2: 'FALLING',
3: 'TIMESTAMP',
4: 'CALIB',
5: 'MISS',
6: 'RST'}

_registers = {'RESET': {'descr': {'addr': 0, 'size': 7, 'offset': 1, 'properties': ['writeonly']}},
'VERSION': {'descr': {'addr': 0, 'size': 8, 'properties': ['ro']}},
Expand All @@ -35,7 +35,7 @@ class tdl_tdc(RegisterHardwareLayer):
'EN_INVERT_TRIGGER': {'descr': {'addr': 1, 'size': 1, 'offset': 7}},
'EVENT_COUNTER': {'descr': {'addr': 2, 'size': 32, 'properties': ['ro']}},
'LOST_DATA_COUNTER': {'descr': {'addr': 6, 'size': 8, 'properties': ['ro']}},
'TDL_MISS_COUNTER' : {'descr' : {'addr': 7, 'size': 8, 'porperties' :['ro']}},
'TDL_MISS_COUNTER': {'descr': {'addr': 7, 'size': 8, 'porperties': ['ro']}},
'EN_CALIBRATION_MODE': {'descr': {'addr': 8, 'size': 1, 'offset': 0}}}

_require_version = "==2"
Expand All @@ -49,86 +49,85 @@ def __init__(self, intf, conf):
def get_tdc_value(self, word):
# The last 7 bit are tdl data, the first 7 bits are word type and source, so 18 bits are counter information
# Of these, the last two bist are timing wrt. the fast clock and the first 16 to rhe slow clock
return self.CLK_DIV*((word >> 9) & 0x0FFFF) + (((word >> 7) & 0x3))
return self.CLK_DIV * ((word >> 9) & 0x0FFFF) + (((word >> 7) & 0x3))

def get_word_type(self, word):
return (word >> (32 - 7) & 0b111)
return (word >> (32 - 7) & 0b111)

def is_calib_word(self, word):
return self.get_word_type(word) == 4

def is_time_word(self, word):
if isinstance(word, np.ndarray) :
if isinstance(word, np.ndarray):
return [(self.word_type_codes[t] in ['TRIGGERED', 'RISING', 'FALLING']) for t in self.get_word_type(word)]
else :
else:
return self.word_type_codes[self.get_word_type(word)] in ['TRIGGERED', 'RISING', 'FALLING']

def get_raw_tdl_values(self, word):
return word & 0b1111111

def tdl_to_time(self, tdl_value) :
sample_proportion = self.calib_vector[tdl_value]
return sample_proportion * 1/self.GHZ_S_FREQ
def tdl_to_time(self, tdl_value):
sample_proportion = self.calib_vector[tdl_value]
return sample_proportion * 1 / self.GHZ_S_FREQ

def set_calib_values(self, calib_values) :
#calib_values = np.append(calib_values)
data_sort, value_counts = np.unique(calib_values % 128, return_counts = True)
def set_calib_values(self, calib_values):
# calib_values = np.append(calib_values)
data_sort, value_counts = np.unique(calib_values % 128, return_counts=True)
self.calib_vector = np.zeros(100)
for i, zero in enumerate(self.calib_vector):
bins_lt_i = (data_sort <= i)
self.calib_vector[i] = np.sum(value_counts[bins_lt_i])
self.calib_sum = np.sum(value_counts)
self.calib_vector = self.calib_vector/self.calib_sum
def plot_calib_values(self, data) :
self.calib_vector = self.calib_vector / self.calib_sum

def plot_calib_values(self, data):
import matplotlib.pyplot as plt
# This if is a safeguard: If data with a large range of values is given to the below
# the code takes forever to return.
if max(data) - min(data) < 1000:
d = 1
left_of_first_bin = data.min() - float(d)/2
right_of_last_bin = data.max() + float(d)/2
_ = plt.hist(data, np.arange(left_of_first_bin,right_of_last_bin + d, d))
left_of_first_bin = data.min() - float(d) / 2
right_of_last_bin = data.max() + float(d) / 2
_ = plt.hist(data, np.arange(left_of_first_bin, right_of_last_bin + d, d))
else:
#data = np.random.choice(data,,replace=False)
# data = np.random.choice(data,,replace=False)
_ = plt.hist(data, 1000)
plt.title("Histogram of TDL code density")
plt.show()

def tdc_word_to_time(self, word) :
if isinstance(word, dict) :
def tdc_word_to_time(self, word):
if isinstance(word, dict):
word = word['raw_word']
if isinstance(word, np.ndarray) :
if isinstance(word, np.ndarray):
if not all(self.is_time_word(word)):
raise ValueError('can not convert tdc word of given types to time')
else :
if (not self.is_time_word(word)) :
else:
if (not self.is_time_word(word)):
word_type = self.word_type_codes[self.get_word_type(word)]
raise ValueError('can not convert tdc word of type %s to time' % word_type )
raise ValueError('can not convert tdc word of type %s to time' % word_type)
tdc_value = self.get_tdc_value(word)
tdc_time = 1/self.GHZ_S_FREQ * tdc_value
tdc_time = 1 / self.GHZ_S_FREQ * tdc_value
return tdc_time - self.tdl_to_time(self.get_raw_tdl_values(word))

def disassemble_tdc_word(self, word):
# Shift away the 32 - 7 data bits and grab 3 bit word type
word_type = self.word_type_codes[self.get_word_type(word)]
if word_type in ['CALIB', 'TRIGGERED', 'RISING', 'FALLING'] :
return {'source_id' : (word >> (32 - 4)),
'word_type' : word_type,
'tdl_value' : word & 0b1111111,
'fine_clk_value' : self.get_tdc_value(word),
'raw_word' : word}
elif word_type in ['TIMESTAMP', 'RST'] :
return {'source_id' : (word >> (32 - 4)),
'word_type' : word_type,
'timestamp' : (word >> 9) & 0xFFFF,
'raw_word' : word}
else :
return {'source_id' : (word >> (32 - 4)),
'word_type' : word_type,
'raw_word' : word}


if word_type in ['CALIB', 'TRIGGERED', 'RISING', 'FALLING']:
return {'source_id': (word >> (32 - 4)),
'word_type': word_type,
'tdl_value': word & 0b1111111,
'fine_clk_value': self.get_tdc_value(word),
'raw_word': word}
elif word_type in ['TIMESTAMP', 'RST']:
return {'source_id': (word >> (32 - 4)),
'word_type': word_type,
'timestamp': (word >> 9) & 0xFFFF,
'raw_word': word}
else:
return {'source_id': (word >> (32 - 4)),
'word_type': word_type,
'raw_word': word}

def reset(self):
self.RESET = 0

Expand Down Expand Up @@ -164,4 +163,3 @@ def get_write_timestamp(self):

def get_event_counter(self):
return self.EVENT_COUNTER

66 changes: 30 additions & 36 deletions examples/tdc_bdaq/tdc_bdaq.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@


def disassemble_tdc_word(word):
word_type_codes = {0 : 'TRIGGERED',
1 : 'RISING',
2 : 'FALLING',
3 : 'TIMESTAMP',
4 : 'OVFLOW',
5 : 'CALIB',
6 : 'MISS',
7 : 'RST'}
word_type_codes = {0: 'TRIGGERED',
1: 'RISING',
2: 'FALLING',
3: 'TIMESTAMP',
4: 'OVFLOW',
5: 'CALIB',
6: 'MISS',
7: 'RST'}
# Shift away the 32 - 7 data bits and grab 3 bit word type
return {'source_id' : (word >> (32 - 4)),
'word_type' : word_type_codes[(word >> (32 - 7)) & 0b111],
'tdl_value' : word & 0b1111111,
'fine_value' : (word >> 7) & 0b11,
'corse_value' : (word >> 9) & 0xFFFF}
return {'source_id': (word >> (32 - 4)),
'word_type': word_type_codes[(word >> (32 - 7)) & 0b111],
'tdl_value': word & 0b1111111,
'fine_value': (word >> 7) & 0b11,
'corse_value': (word >> 9) & 0xFFFF}


chip = Dut("tdc_bdaq.yaml")
Expand All @@ -55,11 +55,11 @@ def disassemble_tdc_word(word):
chip['CONTROL']['EN'] = 1
chip['CONTROL'].write()

chip['TDL_TDC'].RESET =1
chip['TDL_TDC'].RESET = 1

chip['TDL_TDC'].EN_TRIGGER_DIST = 0
chip['TDL_TDC'].ENABLE = 1
chip['TDL_TDC'].RESET=0
chip['TDL_TDC'].RESET = 0
chip['TDL_TDC'].EN_TRIGGER_DIST = 1

collected_data = np.empty(0, dtype=np.uint32)
Expand All @@ -73,12 +73,12 @@ def disassemble_tdc_word(word):

fifo_data = chip['FIFO'].get_data()
data_size = len(fifo_data)
collected_data = np.concatenate((collected_data,fifo_data), dtype=np.uint32)
collected_data = np.concatenate((collected_data, fifo_data), dtype=np.uint32)


chip['TDL_TDC'].EN_CALIBRATION_MODE = 0

chip['TDL_TDC'].RESET=1
chip['TDL_TDC'].RESET = 1
chip['FIFO'].get_data()

chip['CONTROL']['EN'] = 0 # stop data source
Expand All @@ -88,33 +88,30 @@ def disassemble_tdc_word(word):
print(calib_data_indices)


if any(calib_data_indices) :
if any(calib_data_indices):
calib_values = chip['TDL_TDC'].get_raw_tdl_values(np.array(collected_data[calib_data_indices]))
print(calib_values[-20:])
chip['TDL_TDC'].set_calib_values(calib_values)
#chip['TDL_TDC'].plot_calib_values(calib_values)
# chip['TDL_TDC'].plot_calib_values(calib_values)
logging.info("Calibration set using %s samples" % len(calib_values))







collected_rising = []
collected_falling = []
chip['CONTROL']['EN'] = 1 # start data source
chip['CONTROL'].write()
chip['FIFO'].get_data()

chip['TDL_TDC'].RESET=1
chip['TDL_TDC'].RESET = 1
time.sleep(0.1)
chip['FIFO'].get_data()
logging.info("Ready for measurements")
chip['TDL_TDC'].EN_TRIGGER_DIST = 1
chip['TDL_TDC'].EN_WRITE_TIMESTAMP = 0

delta_t = 0


def reject_outliers(data, m=2):
return data[abs(data - np.median(data)) < m]

Expand All @@ -129,14 +126,14 @@ def load_and_start_trig_seq(trig_dis_cycles):
need_kilo_cycles = 1
remain_trig_cycles = trig_dis_cycles % 1000

trig_total = remain_trig_cycles + need_kilo_cycles*1000
trig_total = remain_trig_cycles + need_kilo_cycles * 1000

chip['SEQ'].reset()
while not chip['SEQ'].is_ready:
pass
chip['SEQ'].SIZE = sig_cycles + trig_total + 1
chip['SEQ']['TDC_IN'][:] = False
chip['SEQ']['TDC_IN'][trig_total:sig_cycles + trig_total ] = True
chip['SEQ']['TDC_IN'][trig_total:sig_cycles + trig_total] = True
chip['SEQ']['TDC_TRIGGER_IN'][0:20] = True
chip['SEQ'].write(sig_cycles + trig_total + 1)

Expand All @@ -146,10 +143,11 @@ def load_and_start_trig_seq(trig_dis_cycles):
# be ignored by the TDC implementation.
chip['SEQ'].NESTED_START = 0
chip['SEQ'].NESTED_STOP = 1000
chip['SEQ'].NESTED_REPEAT = kilo_trig_cycles
chip['SEQ'].NESTED_REPEAT = kilo_trig_cycles

chip['SEQ'].START


seq_clk_GHZ = 0.15625
N_measure = 500
current_measurements = np.zeros(N_measure)
Expand All @@ -164,17 +162,17 @@ def load_and_start_trig_seq(trig_dis_cycles):
time.sleep(0.0001)
pass
fifo_size = chip['FIFO']._intf._get_tcp_data_size()
fifo_int_size = int((fifo_size - (fifo_size % 4)) / 4)
fifo_int_size = int((fifo_size - (fifo_size % 4)) / 4)
while fifo_int_size < 2:
time.sleep(0.0001)
fifo_size = chip['FIFO']._intf._get_tcp_data_size()
fifo_int_size = int((fifo_size - (fifo_size % 4)) / 4)
fifo_int_size = int((fifo_size - (fifo_size % 4)) / 4)
fifo_data = chip['FIFO'].get_data()
times = chip['TDL_TDC'].tdc_word_to_time(fifo_data)
current_measurements[j] = times[1] - times[0]
actual.append(i/seq_clk_GHZ)
actual.append(i / seq_clk_GHZ)
std = np.std(current_measurements)
print('Actual time: %5.3f Measured time: %5.3f Difference: %.3f Std %.3f' % (i/seq_clk_GHZ, times[1] - times[0], times[1] - times[0] - i/seq_clk_GHZ, std))
print('Actual time: %5.3f Measured time: %5.3f Difference: %.3f Std %.3f' % (i / seq_clk_GHZ, times[1] - times[0], times[1] - times[0] - i / seq_clk_GHZ, std))
measured.append(np.mean(current_measurements))
stds.append(std)
print()
Expand All @@ -191,7 +189,3 @@ def load_and_start_trig_seq(trig_dis_cycles):

plt.plot(actual, stds)
plt.show()




7 changes: 3 additions & 4 deletions tests/test_SimTdl_Tdc.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,12 @@ def setUp(self):

def test_tdc(self):
self.chip['TDC0'].ENABLE = 1
slef.chip['TDC0'].EN_TRIGGER_DIST = 1
self.chip['TDC0'].EN_TRIGGER_DIST = 1
self.chip['SEQ'].REPEAT = 1

for write_timestamp in range(0,1):
for write_timestamp in range(0, 1):
for index, i in enumerate(range(1045, 1047)):
trigger_dis = 50
trigger_dis = 50
length = i + 1 + trigger_dis
self.chip['SEQ'].SIZE = length + 1
self.chip['SEQ']['TDC_IN'][trigger_dis:length + trigger_dis] = True
Expand All @@ -120,7 +120,6 @@ def test_tdc(self):
self.assertEqual(data[3]['word_type'], 'TIMESTAMP')
self.asserEqual(data[3]['timestamp'], 42)


# def test_broadcasting(self):
# self.chip['TDC0'].ENABLE = 1
# self.chip['TDC1'].ENABLE = 1
Expand Down

0 comments on commit 5665e54

Please sign in to comment.