sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def get_hit_rate_correction(gdacs, calibration_gdacs, cluster_size_histogram):
'''Calculates a correction factor for single hit clusters at the given GDACs from the cluster_size_histogram via cubic interpolation.
Parameters
----------
gdacs : array like
The GDAC settings where the threshold sho... | Calculates a correction factor for single hit clusters at the given GDACs from the cluster_size_histogram via cubic interpolation.
Parameters
----------
gdacs : array like
The GDAC settings where the threshold should be determined from the calibration
calibration_gdacs : array like
GDAC... | entailment |
def get_mean_threshold_from_calibration(gdac, mean_threshold_calibration):
'''Calculates the mean threshold from the threshold calibration at the given gdac settings. If the given gdac value was not used during caluibration
the value is determined by interpolation.
Parameters
----------
gdacs : arr... | Calculates the mean threshold from the threshold calibration at the given gdac settings. If the given gdac value was not used during caluibration
the value is determined by interpolation.
Parameters
----------
gdacs : array like
The GDAC settings where the threshold should be determined from th... | entailment |
def get_pixel_thresholds_from_calibration_array(gdacs, calibration_gdacs, threshold_calibration_array, bounds_error=True):
'''Calculates the threshold for all pixels in threshold_calibration_array at the given GDAC settings via linear interpolation. The GDAC settings used during calibration have to be given.
P... | Calculates the threshold for all pixels in threshold_calibration_array at the given GDAC settings via linear interpolation. The GDAC settings used during calibration have to be given.
Parameters
----------
gdacs : array like
The GDAC settings where the threshold should be determined from the calibr... | entailment |
def get_n_cluster_per_event_hist(cluster_table):
'''Calculates the number of cluster in every event.
Parameters
----------
cluster_table : pytables.table
Returns
-------
numpy.Histogram
'''
logging.info("Histogram number of cluster per event")
cluster_in_events = analysis_utils... | Calculates the number of cluster in every event.
Parameters
----------
cluster_table : pytables.table
Returns
-------
numpy.Histogram | entailment |
def get_data_statistics(interpreted_files):
'''Quick and dirty function to give as redmine compatible iverview table
'''
print '| *File Name* | *File Size* | *Times Stamp* | *Events* | *Bad Events* | *Measurement time* | *# SR* | *Hits* |' # Mean Tot | Mean rel. BCID'
for interpreted_file in interprete... | Quick and dirty function to give as redmine compatible iverview table | entailment |
def contiguous_regions(condition):
"""Finds contiguous True regions of the boolean array "condition". Returns
a 2D array where the first column is the start index of the region and the
second column is the end index.
http://stackoverflow.com/questions/4494404/find-large-number-of-consecutive-values-fulf... | Finds contiguous True regions of the boolean array "condition". Returns
a 2D array where the first column is the start index of the region and the
second column is the end index.
http://stackoverflow.com/questions/4494404/find-large-number-of-consecutive-values-fulfilling-condition-in-a-numpy-array | entailment |
def check_bad_data(raw_data, prepend_data_headers=None, trig_count=None):
"""Checking FEI4 raw data array for corrupted data.
"""
consecutive_triggers = 16 if trig_count == 0 else trig_count
is_fe_data_header = logical_and(is_fe_word, is_data_header)
trigger_idx = np.where(is_trigger_word(raw_data) ... | Checking FEI4 raw data array for corrupted data. | entailment |
def consecutive(data, stepsize=1):
"""Converts array into chunks with consecutive elements of given step size.
http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy
"""
return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1) | Converts array into chunks with consecutive elements of given step size.
http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy | entailment |
def print_raw_data_file(input_file, start_index=0, limit=200, flavor='fei4b', select=None, tdc_trig_dist=False, trigger_data_mode=0, meta_data_v2=True):
"""Printing FEI4 data from raw data file for debugging.
"""
with tb.open_file(input_file + '.h5', mode="r") as file_h5:
if meta_data_v2:
... | Printing FEI4 data from raw data file for debugging. | entailment |
def print_raw_data(raw_data, start_index=0, limit=200, flavor='fei4b', index_offset=0, select=None, tdc_trig_dist=False, trigger_data_mode=0):
"""Printing FEI4 raw data array for debugging.
"""
if not select:
select = ['DH', 'TW', "AR", "VR", "SR", "DR", 'TDC', 'UNKNOWN FE WORD', 'UNKNOWN WORD']
... | Printing FEI4 raw data array for debugging. | entailment |
def update(self, pbar):
'Updates the widget to show the ETA or total time when finished.'
self.n_refresh += 1
if pbar.currval == 0:
return 'ETA: --:--:--'
elif pbar.finished:
return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
else:
ela... | Updates the widget to show the ETA or total time when finished. | entailment |
def plot_result(x_p, y_p, y_p_e, smoothed_data, smoothed_data_diff, filename=None):
''' Fit spline to the profile histogramed data, differentiate, determine MPV and plot.
Parameters
----------
x_p, y_p : array like
data points (x,y)
y_p_e : array like
error bars in y... | Fit spline to the profile histogramed data, differentiate, determine MPV and plot.
Parameters
----------
x_p, y_p : array like
data points (x,y)
y_p_e : array like
error bars in y | entailment |
def create_hitor_calibration(output_filename, plot_pixel_calibrations=False):
'''Generating HitOr calibration file (_calibration.h5) from raw data file and plotting of calibration data.
Parameters
----------
output_filename : string
Input raw data file name.
plot_pixel_calibrations :... | Generating HitOr calibration file (_calibration.h5) from raw data file and plotting of calibration data.
Parameters
----------
output_filename : string
Input raw data file name.
plot_pixel_calibrations : bool, iterable
If True, genearating additional pixel calibration plots. If l... | entailment |
def interval_timed(interval):
'''Interval timer decorator.
Taken from: http://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds/12435256
'''
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
stopped = Event()
def... | Interval timer decorator.
Taken from: http://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds/12435256 | entailment |
def interval_timer(interval, func, *args, **kwargs):
'''Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
'''
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is after interval
... | Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708 | entailment |
def send_mail(subject, body, smtp_server, user, password, from_addr, to_addrs):
''' Sends a run status mail with the traceback to a specified E-Mail address if a run crashes.
'''
logging.info('Send status E-Mail (' + subject + ')')
content = string.join((
"From: %s" % from_addr,
"To: %s"... | Sends a run status mail with the traceback to a specified E-Mail address if a run crashes. | entailment |
def _parse_module_cfgs(self):
''' Extracts the configuration of the modules.
'''
# Adding here default run config parameters.
if "dut" not in self._conf or self._conf["dut"] is None:
raise ValueError('Parameter "dut" not defined.')
if "dut_configuration" not in self._... | Extracts the configuration of the modules. | entailment |
def _set_default_cfg(self):
''' Sets the default parameters if they are not specified.
'''
# adding special conf for accessing all DUT drivers
self._module_cfgs[None] = {
'flavor': None,
'chip_address': None,
'FIFO': list(set([self._module_cfgs[module_... | Sets the default parameters if they are not specified. | entailment |
def init_modules(self):
''' Initialize all modules consecutively'''
for module_id, module_cfg in self._module_cfgs.items():
if module_id in self._modules or module_id in self._tx_module_groups:
if module_id in self._modules:
module_id_str = "module " + mod... | Initialize all modules consecutively | entailment |
def do_run(self):
''' Start runs on all modules sequentially.
Sets properties to access current module properties.
'''
if self.broadcast_commands: # Broadcast FE commands
if self.threaded_scan:
with ExitStack() as restore_config_stack:
# ... | Start runs on all modules sequentially.
Sets properties to access current module properties. | entailment |
def close(self):
'''Releasing hardware resources.
'''
try:
self.dut.close()
except Exception:
logging.warning('Closing DUT was not successful')
else:
logging.debug('Closed DUT') | Releasing hardware resources. | entailment |
def handle_data(self, data, new_file=False, flush=True):
'''Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int))
'''
for i, module_id in enumerate(self._s... | Handling of the data.
Parameters
----------
data : list, tuple
Data tuple of the format (data (np.array), last_time (float), curr_time (float), status (int)) | entailment |
def handle_err(self, exc):
'''Handling of Exceptions.
Parameters
----------
exc : list, tuple
Information of the exception of the format (type, value, traceback).
Uses the return value of sys.exc_info().
'''
if self.reset_rx_on_error and isinstanc... | Handling of Exceptions.
Parameters
----------
exc : list, tuple
Information of the exception of the format (type, value, traceback).
Uses the return value of sys.exc_info(). | entailment |
def get_configuration(self, module_id, run_number=None):
''' Returns the configuration for a given module ID.
The working directory is searched for a file matching the module_id with the
given run number. If no run number is defined the last successfull run defines
the run number.
... | Returns the configuration for a given module ID.
The working directory is searched for a file matching the module_id with the
given run number. If no run number is defined the last successfull run defines
the run number. | entailment |
def select_module(self, module_id):
''' Select module and give access to the module.
'''
if not isinstance(module_id, basestring) and isinstance(module_id, Iterable) and set(module_id) - set(self._modules):
raise ValueError('Module IDs invalid:' % ", ".join(set(module_id) - set(self.... | Select module and give access to the module. | entailment |
def deselect_module(self):
''' Deselect module and cleanup.
'''
self._enabled_fe_channels = [] # ignore any RX sync errors
self._readout_fifos = []
self._filter = []
self._converter = []
self.dut['TX']['OUTPUT_ENABLE'] = 0
self._current_module_handle = No... | Deselect module and cleanup. | entailment |
def enter_sync(self):
''' Waiting for all threads to appear, then continue.
'''
if self._scan_threads and self.current_module_handle not in [t.name for t in self._scan_threads]:
raise RuntimeError('Thread name "%s" is not valid.')
if self._scan_threads and self.current_module... | Waiting for all threads to appear, then continue. | entailment |
def exit_sync(self):
''' Waiting for all threads to appear, then continue.
'''
if self._scan_threads and self.current_module_handle not in [t.name for t in self._scan_threads]:
raise RuntimeError('Thread name "%s" is not valid.')
if self._scan_threads and self.current_module_... | Waiting for all threads to appear, then continue. | entailment |
def readout(self, *args, **kwargs):
''' Running the FIFO readout while executing other statements.
Starting and stopping of the FIFO readout is synchronized between the threads.
'''
timeout = kwargs.pop('timeout', 10.0)
self.start_readout(*args, **kwargs)
try:
... | Running the FIFO readout while executing other statements.
Starting and stopping of the FIFO readout is synchronized between the threads. | entailment |
def start_readout(self, *args, **kwargs):
''' Starting the FIFO readout.
Starting of the FIFO readout is executed only once by a random thread.
Starting of the FIFO readout is synchronized between all threads reading out the FIFO.
'''
# Pop parameters for fifo_readout.start
... | Starting the FIFO readout.
Starting of the FIFO readout is executed only once by a random thread.
Starting of the FIFO readout is synchronized between all threads reading out the FIFO. | entailment |
def stop_readout(self, timeout=10.0):
''' Stopping the FIFO readout.
Stopping of the FIFO readout is executed only once by a random thread.
Stopping of the FIFO readout is synchronized between all threads reading out the FIFO.
'''
if self._scan_threads and self.current_module_ha... | Stopping the FIFO readout.
Stopping of the FIFO readout is executed only once by a random thread.
Stopping of the FIFO readout is synchronized between all threads reading out the FIFO. | entailment |
def get_charge(max_tdc, tdc_calibration_values, tdc_pixel_calibration): # Return the charge from calibration
''' Interpolatet the TDC calibration for each pixel from 0 to max_tdc'''
charge_calibration = np.zeros(shape=(80, 336, max_tdc))
for column in range(80):
for row in range(336):
a... | Interpolatet the TDC calibration for each pixel from 0 to max_tdc | entailment |
def get_charge_calibration(calibation_file, max_tdc):
''' Open the hit or calibration file and return the calibration per pixel'''
with tb.open_file(calibation_file, mode="r") as in_file_calibration_h5:
tdc_calibration = in_file_calibration_h5.root.HitOrCalibration[:, :, :, 1]
tdc_calibration_va... | Open the hit or calibration file and return the calibration per pixel | entailment |
def addEntry(self):
"""Add the `Plot pyBAR data`. entry to `Dataset` menu.
"""
export_icon = QtGui.QIcon()
pixmap = QtGui.QPixmap(os.path.join(PLUGINSDIR,
'csv/icons/document-export.png'))
export_icon.addPixmap(pixmap, QtGui.QIcon.Norma... | Add the `Plot pyBAR data`. entry to `Dataset` menu. | entailment |
def updateDatasetMenu(self):
"""Update the `export` QAction when the Dataset menu is pulled down.
This method is a slot. See class ctor for details.
"""
enabled = True
current = self.vtgui.dbs_tree_view.currentIndex()
if current:
leaf = self.vtgui.dbs_tree_mo... | Update the `export` QAction when the Dataset menu is pulled down.
This method is a slot. See class ctor for details. | entailment |
def plot(self):
"""Export a given dataset to a `CSV` file.
This method is a slot connected to the `export` QAction. See the
:meth:`addEntry` method for details.
"""
# The PyTables node tied to the current leaf of the databases tree
current = self.vtgui.dbs_tree_view.curr... | Export a given dataset to a `CSV` file.
This method is a slot connected to the `export` QAction. See the
:meth:`addEntry` method for details. | entailment |
def helpAbout(self):
"""Brief description of the plugin.
"""
# Text to be displayed
about_text = translate('pyBarPlugin',
"""<qt>
<p>Data plotting plug-in for pyBAR.
</qt>""",
'About')
descr =... | Brief description of the plugin. | entailment |
def send_meta_data(socket, conf, name):
'''Sends the config via ZeroMQ to a specified socket. Is called at the beginning of a run and when the config changes. Conf can be any config dictionary.
'''
meta_data = dict(
name=name,
conf=conf
)
try:
socket.send_json(meta_data, flag... | Sends the config via ZeroMQ to a specified socket. Is called at the beginning of a run and when the config changes. Conf can be any config dictionary. | entailment |
def send_data(socket, data, scan_parameters={}, name='ReadoutData'):
'''Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket
'''
if not scan_parameters:
scan_parameters = {}
data_meta_data = dict(
name=name,
dtype=str(data[0].dtype),
... | Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket | entailment |
def open_raw_data_file(filename, mode="w", title="", scan_parameters=None, socket_address=None):
'''Mimics pytables.open_file() and stores the configuration and run configuration
Returns:
RawDataFile Object
Examples:
with open_raw_data_file(filename = self.scan_data_filename, title=self.scan_id, s... | Mimics pytables.open_file() and stores the configuration and run configuration
Returns:
RawDataFile Object
Examples:
with open_raw_data_file(filename = self.scan_data_filename, title=self.scan_id, scan_parameters=[scan_parameter]) as raw_data_file:
# do something here
raw_data_file.app... | entailment |
def save_raw_data_from_data_queue(data_queue, filename, mode='a', title='', scan_parameters=None): # mode="r+" to append data, raw_data_file_h5 must exist, "w" to overwrite raw_data_file_h5, "a" to append data, if raw_data_file_h5 does not exist it is created
'''Writing raw data file from data queue
If you ne... | Writing raw data file from data queue
If you need to write raw data once in a while this function may make it easy for you. | entailment |
def scan(self):
'''Metascript that calls other scripts to tune the FE.
Parameters
----------
cfg_name : string
Name of the config to be created. This config holds the tuning results.
target_threshold : int
The target threshold value in PlsrDAC.
... | Metascript that calls other scripts to tune the FE.
Parameters
----------
cfg_name : string
Name of the config to be created. This config holds the tuning results.
target_threshold : int
The target threshold value in PlsrDAC.
target_charge : int
... | entailment |
def plot_linear_relation(x, y, x_err=None, y_err=None, title=None, point_label=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, y_2_label=None, log_x=False, log_y=False, size=None, filename=None):
''' Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation ... | Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.
Parameters
----------
x, y, x_err, y_err: iterable
filename: string, PdfPages object or None
PdfPages file object: plot is appended to the pdf
stri... | entailment |
def plot_profile_histogram(x, y, n_bins=100, title=None, x_label=None, y_label=None, log_y=False, filename=None):
'''Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
the y mean for every bin at the bin center and gives the y mean error as error bars.
... | Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
the y mean for every bin at the bin center and gives the y mean error as error bars.
Parameters
----------
x : array like
data x positions
y : array like
data y positions... | entailment |
def round_to_multiple(number, multiple):
'''Rounding up to the nearest multiple of any positive integer
Parameters
----------
number : int, float
Input number.
multiple : int
Round up to multiple of multiple. Will be converted to int. Must not be equal zero.
Returns
... | Rounding up to the nearest multiple of any positive integer
Parameters
----------
number : int, float
Input number.
multiple : int
Round up to multiple of multiple. Will be converted to int. Must not be equal zero.
Returns
-------
ceil_mod_number : int
Rou... | entailment |
def hist_quantiles(hist, prob=(0.05, 0.95), return_indices=False, copy=True):
'''Calculate quantiles from histograms, cuts off hist below and above given quantile. This function will not cut off more than the given values.
Parameters
----------
hist : array_like, iterable
Input histogram ... | Calculate quantiles from histograms, cuts off hist below and above given quantile. This function will not cut off more than the given values.
Parameters
----------
hist : array_like, iterable
Input histogram with dimension at most 1.
prob : float, list, tuple
List of quantiles to... | entailment |
def hist_last_nonzero(hist, return_index=False, copy=True):
'''Find the last nonzero index and mask the remaining entries.
Parameters
----------
hist : array_like, iterable
Input histogram with dimension at most 1.
return_index : bool, optional
If true, return the index.
... | Find the last nonzero index and mask the remaining entries.
Parameters
----------
hist : array_like, iterable
Input histogram with dimension at most 1.
return_index : bool, optional
If true, return the index.
copy : bool, optional
Whether to copy the input data (Tru... | entailment |
def readout(self, fifo, no_data_timeout=None):
'''Readout thread continuously reading FIFO.
Readout thread, which uses read_raw_data_from_fifo() and appends data to self._fifo_data_deque (collection.deque).
'''
logging.info('Starting readout thread for %s', fifo)
time_last... | Readout thread continuously reading FIFO.
Readout thread, which uses read_raw_data_from_fifo() and appends data to self._fifo_data_deque (collection.deque). | entailment |
def worker(self, fifo):
'''Worker thread continuously filtering and converting data when data becomes available.
'''
logging.debug('Starting worker thread for %s', fifo)
self._fifo_conditions[fifo].acquire()
while True:
try:
data_tuple = self._f... | Worker thread continuously filtering and converting data when data becomes available. | entailment |
def writer(self, index, no_data_timeout=None):
'''Writer thread continuously calling callback function for writing data when data becomes available.
'''
is_fe_data_header = logical_and(is_fe_word, is_data_header)
logging.debug('Starting writer thread with index %d', index)
s... | Writer thread continuously calling callback function for writing data when data becomes available. | entailment |
def get_data_from_buffer(self, filter_func=None, converter_func=None):
'''Reads local data buffer and returns data and meta data list.
Returns
-------
data : list
List of data and meta data dicts.
'''
if self._is_running:
raise RuntimeErr... | Reads local data buffer and returns data and meta data list.
Returns
-------
data : list
List of data and meta data dicts. | entailment |
def get_raw_data_from_buffer(self, filter_func=None, converter_func=None):
'''Reads local data buffer and returns raw data array.
Returns
-------
data : np.array
An array containing data words from the local data buffer.
'''
if self._is_running:
... | Reads local data buffer and returns raw data array.
Returns
-------
data : np.array
An array containing data words from the local data buffer. | entailment |
def read_raw_data_from_fifo(self, fifo, filter_func=None, converter_func=None):
'''Reads FIFO data and returns raw data array.
Returns
-------
data : np.array
An array containing FIFO data words.
'''
return convert_data_array(self.dut[fifo].get_data()... | Reads FIFO data and returns raw data array.
Returns
-------
data : np.array
An array containing FIFO data words. | entailment |
def get_item_from_queue(Q, timeout=0.01):
""" Attempts to retrieve an item from the queue Q. If Q is
empty, None is returned.
Blocks for 'timeout' seconds in case the queue is empty,
so don't use this method for speedy retrieval of multiple
items (use get_all_from_queue for th... | Attempts to retrieve an item from the queue Q. If Q is
empty, None is returned.
Blocks for 'timeout' seconds in case the queue is empty,
so don't use this method for speedy retrieval of multiple
items (use get_all_from_queue for that). | entailment |
def argmin_list(seq, func):
""" Return a list of elements of seq[i] with the lowest
func(seq[i]) scores.
>>> argmin_list(['one', 'to', 'three', 'or'], len)
['to', 'or']
"""
best_score, best = func(seq[0]), []
for x in seq:
x_score = func(x)
if x_score < b... | Return a list of elements of seq[i] with the lowest
func(seq[i]) scores.
>>> argmin_list(['one', 'to', 'three', 'or'], len)
['to', 'or'] | entailment |
def flatten_iterable(iterable):
"""flatten iterable, but leaves out strings
[[[1, 2, 3], [4, 5]], 6] -> [1, 2, 3, 4, 5, 6]
"""
for item in iterable:
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
for sub in flatten_iterable(item):
... | flatten iterable, but leaves out strings
[[[1, 2, 3], [4, 5]], 6] -> [1, 2, 3, 4, 5, 6] | entailment |
def iterable(item):
"""generate iterable from item, but leaves out strings
"""
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
return item
else:
return [item] | generate iterable from item, but leaves out strings | entailment |
def natsorted(seq, cmp=natcmp):
"Returns a copy of seq, sorted by natural string sort."
import copy
temp = copy.copy(seq)
natsort(temp, cmp)
return temp | Returns a copy of seq, sorted by natural string sort. | entailment |
def get_iso_time():
'''returns time as ISO string, mapping to and from datetime in ugly way
convert to string with str()
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
t4 = t2.__str__()
try:
t4a, t4b = t4.split(".", 1)
except ValueError:
t4a = t... | returns time as ISO string, mapping to and from datetime in ugly way
convert to string with str() | entailment |
def get_float_time():
'''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
return time.mktime(t2.timetuple()) + 1e-6 * t2.microsecond | returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's | entailment |
def groupby_dict(dictionary, key):
''' Group dict of dicts by key.
'''
return dict((k, list(g)) for k, g in itertools.groupby(sorted(dictionary.keys(), key=lambda name: dictionary[name][key]), key=lambda name: dictionary[name][key])) | Group dict of dicts by key. | entailment |
def zip_nofill(*iterables):
'''Zipping iterables without fillvalue.
Note: https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue
'''
return (tuple([entry for entry in iterable if entry is not None]) for iterable in itertools.izip_longest(*iterables, fillvalue=None)) | Zipping iterables without fillvalue.
Note: https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue | entailment |
def find_file_dir_up(filename, path=None, n=None):
'''Finding file in directory upwards.
'''
if path is None:
path = os.getcwd()
i = 0
while True:
current_path = path
for _ in range(i):
current_path = os.path.split(current_path)[0]
if os.path.isf... | Finding file in directory upwards. | entailment |
def load_configuration_from_text_file(register, configuration_file):
'''Loading configuration from text files to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Full path (directory and filename) of the configuration file. If na... | Loading configuration from text files to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Full path (directory and filename) of the configuration file. If name is not given, reload configuration from file. | entailment |
def load_configuration_from_hdf5(register, configuration_file, node=''):
'''Loading configuration from HDF5 file to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
... | Loading configuration from HDF5 file to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
node : string
Additional identifier (subgroup). Useful when more than... | entailment |
def save_configuration_to_text_file(register, configuration_file):
'''Saving configuration to text files from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Filename of the configuration file.
'''
configuration_path, ... | Saving configuration to text files from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Filename of the configuration file. | entailment |
def save_configuration_to_hdf5(register, configuration_file, name=''):
'''Saving configuration to HDF5 file from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
... | Saving configuration to HDF5 file from register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string, file
Filename of the HDF5 configuration file or file object.
name : string
Additional identifier (subgroup). Useful when storing mo... | entailment |
def load_configuration(self, configuration_file):
'''Loading configuration
Parameters
----------
configuration_file : string
Path to the configuration file (text or HDF5 file).
'''
if os.path.isfile(configuration_file):
if not isinstance(... | Loading configuration
Parameters
----------
configuration_file : string
Path to the configuration file (text or HDF5 file). | entailment |
def save_configuration(self, configuration_file):
'''Saving configuration
Parameters
----------
configuration_file : string
Filename of the configuration file.
'''
if not isinstance(configuration_file, tb.file.File) and os.path.splitext(configuration_... | Saving configuration
Parameters
----------
configuration_file : string
Filename of the configuration file. | entailment |
def get_commands(self, command_name, **kwargs):
"""get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 specific behavior
"""
chip_id = kwargs.pop("ChipID", self.chip_id_bitarray)
commands = []
if command_n... | get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 specific behavior | entailment |
def build_command(self, command_name, **kwargs):
"""build command from command_name and keyword values
Returns
-------
command_bitvector : list
List of bitarrays.
Usage
-----
Receives: command name as defined inside xml file, key-value-pair... | build command from command_name and keyword values
Returns
-------
command_bitvector : list
List of bitarrays.
Usage
-----
Receives: command name as defined inside xml file, key-value-pairs as defined inside bit stream filed for each command | entailment |
def get_global_register_attributes(self, register_attribute, do_sort=True, **kwargs):
"""Calculating register numbers from register names.
Usage: get_global_register_attributes("attribute_name", name = [regname_1, regname_2, ...], addresses = 2)
Receives: attribute name to be returned, dict... | Calculating register numbers from register names.
Usage: get_global_register_attributes("attribute_name", name = [regname_1, regname_2, ...], addresses = 2)
Receives: attribute name to be returned, dictionaries (kwargs) of register attributes and values for making cuts
Returns: list of attr... | entailment |
def get_global_register_objects(self, do_sort=None, reverse=False, **kwargs):
"""Generate register objects (list) from register name list
Usage: get_global_register_objects(name = ["Amp2Vbn", "GateHitOr", "DisableColumnCnfg"], address = [2, 3])
Receives: keyword lists of register names, add... | Generate register objects (list) from register name list
Usage: get_global_register_objects(name = ["Amp2Vbn", "GateHitOr", "DisableColumnCnfg"], address = [2, 3])
Receives: keyword lists of register names, addresses,... for making cuts
Returns: list of register objects | entailment |
def get_global_register_bitsets(self, register_addresses): # TOTO: add sorting
"""Calculating register bitsets from register addresses.
Usage: get_global_register_bitsets([regaddress_1, regaddress_2, ...])
Receives: list of register addresses
Returns: list of register bitsets
... | Calculating register bitsets from register addresses.
Usage: get_global_register_bitsets([regaddress_1, regaddress_2, ...])
Receives: list of register addresses
Returns: list of register bitsets | entailment |
def get_pixel_register_objects(self, do_sort=None, reverse=False, **kwargs):
"""Generate register objects (list) from register name list
Usage: get_pixel_register_objects(name = ["TDAC", "FDAC"])
Receives: keyword lists of register names, addresses,...
Returns: list of register obj... | Generate register objects (list) from register name list
Usage: get_pixel_register_objects(name = ["TDAC", "FDAC"])
Receives: keyword lists of register names, addresses,...
Returns: list of register objects | entailment |
def get_pixel_register_bitset(self, register_object, bit_no, dc_no):
"""Calculating pixel register bitsets from pixel register addresses.
Usage: get_pixel_register_bitset(object, bit_number, double_column_number)
Receives: register object, bit number, double column number
Returns: ... | Calculating pixel register bitsets from pixel register addresses.
Usage: get_pixel_register_bitset(object, bit_number, double_column_number)
Receives: register object, bit number, double column number
Returns: double column bitset | entailment |
def create_restore_point(self, name=None):
'''Creating a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated.
'''
if name is None:
for i in iter(int, 1):
... | Creating a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated. | entailment |
def restore(self, name=None, keep=False, last=True, global_register=True, pixel_register=True):
'''Restoring a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated.
keep : bool
... | Restoring a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated.
keep : bool
Keeping restore point for later use.
last : bool
If name is not given, the la... | entailment |
def clear_restore_points(self, name=None):
'''Deleting all/a configuration restore points/point.
Parameters
----------
name : str
Name of the restore point to be deleted. If not given, all restore points will be deleted.
'''
if name is None:
... | Deleting all/a configuration restore points/point.
Parameters
----------
name : str
Name of the restore point to be deleted. If not given, all restore points will be deleted. | entailment |
def save_configuration_dict(h5_file, configuation_name, configuration, **kwargs):
'''Stores any configuration dictionary to HDF5 file.
Parameters
----------
h5_file : string, file
Filename of the HDF5 configuration file or file object.
configuation_name : str
Configuration n... | Stores any configuration dictionary to HDF5 file.
Parameters
----------
h5_file : string, file
Filename of the HDF5 configuration file or file object.
configuation_name : str
Configuration name. Will be used for table name.
configuration : dict
Configuration diction... | entailment |
def convert_data_array(array, filter_func=None, converter_func=None): # TODO: add copy parameter, otherwise in-place
'''Filter and convert raw data numpy array (numpy.ndarray).
Parameters
----------
array : numpy.array
Raw data array.
filter_func : function
Function that ta... | Filter and convert raw data numpy array (numpy.ndarray).
Parameters
----------
array : numpy.array
Raw data array.
filter_func : function
Function that takes array and returns true or false for each item in array.
converter_func : function
Function that takes array ... | entailment |
def convert_data_iterable(data_iterable, filter_func=None, converter_func=None): # TODO: add concatenate parameter
'''Convert raw data in data iterable.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_star... | Convert raw data in data iterable.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
filter_func : function
Function that takes array and returns true or false for eac... | entailment |
def data_array_from_data_iterable(data_iterable):
'''Convert data iterable to raw data numpy array.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
Returns
------... | Convert data iterable to raw data numpy array.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
Returns
-------
data_array : numpy.array
concatenated data... | entailment |
def convert_tdc_to_channel(channel):
''' Converts TDC words at a given channel to common TDC header (0x4).
'''
def f(value):
filter_func = logical_and(is_tdc_word, is_tdc_from_channel(channel))
select = filter_func(value)
value[select] = np.bitwise_and(value[select], 0x0FFFFFFF... | Converts TDC words at a given channel to common TDC header (0x4). | entailment |
def is_data_from_channel(channel=4): # function factory
'''Selecting FE data from given channel.
Parameters
----------
channel : int
Channel number (4 is default channel on Single Chip Card).
Returns
-------
Function.
Usage:
1 Selecting FE data from channel 4... | Selecting FE data from given channel.
Parameters
----------
channel : int
Channel number (4 is default channel on Single Chip Card).
Returns
-------
Function.
Usage:
1 Selecting FE data from channel 4 (combine with is_fe_word):
filter_fe_data_from_channel_... | entailment |
def logical_and(f1, f2): # function factory
'''Logical and from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
Usage:
filter_func=logical_and(is_data_rec... | Logical and from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
Usage:
filter_func=logical_and(is_data_record, is_data_from_channel(4)) # new filter function
... | entailment |
def logical_or(f1, f2): # function factory
'''Logical or from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
'''
def f(value):
return np.logical_o... | Logical or from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function. | entailment |
def logical_not(f): # function factory
'''Logical not from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
'''
def f(value):
return np.logical_not(... | Logical not from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function. | entailment |
def logical_xor(f1, f2): # function factory
'''Logical xor from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
'''
def f(value):
return np.logical... | Logical xor from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function. | entailment |
def get_trigger_data(value, mode=0):
'''Returns 31bit trigger counter (mode=0), 31bit timestamp (mode=1), 15bit timestamp and 16bit trigger counter (mode=2)
'''
if mode == 2:
return np.right_shift(np.bitwise_and(value, 0x7FFF0000), 16), np.bitwise_and(value, 0x0000FFFF)
else:
retur... | Returns 31bit trigger counter (mode=0), 31bit timestamp (mode=1), 15bit timestamp and 16bit trigger counter (mode=2) | entailment |
def get_col_row_tot_array_from_data_record_array(array): # TODO: max ToT
'''Convert raw data array to column, row, and ToT array.
Parameters
----------
array : numpy.array
Raw data array.
Returns
-------
Tuple of arrays.
'''
def get_col_row_tot_1_array_from_dat... | Convert raw data array to column, row, and ToT array.
Parameters
----------
array : numpy.array
Raw data array.
Returns
-------
Tuple of arrays. | entailment |
def interpret_pixel_data(data, dc, pixel_array, invert=True):
'''Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching.
The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit).
Parameters
----------
... | Takes the pixel raw data and interprets them. This includes consistency checks and pixel/data matching.
The data has to come from one double column only but can have more than one pixel bit (e.g. TDAC = 5 bit).
Parameters
----------
data : numpy.ndarray
The raw data words.
dc : int
... | entailment |
def set_standard_settings(self):
'''Set all settings to their standard values.
'''
if self.is_open(self.out_file_h5):
self.out_file_h5.close()
self.out_file_h5 = None
self._setup_clusterizer()
self.chunk_size = 3000000
self.n_injections = None
... | Set all settings to their standard values. | entailment |
def trig_count(self, value):
"""Set the numbers of BCIDs (usually 16) of one event."""
self._trig_count = 16 if value == 0 else value
self.interpreter.set_trig_count(self._trig_count) | Set the numbers of BCIDs (usually 16) of one event. | entailment |
def max_tot_value(self, value):
"""Set maximum ToT value that is considered to be a hit"""
self._max_tot_value = value
self.interpreter.set_max_tot(self._max_tot_value)
self.histogram.set_max_tot(self._max_tot_value)
self.clusterizer.set_max_hit_charge(self._max_tot_value) | Set maximum ToT value that is considered to be a hit | entailment |
def interpret_word_table(self, analyzed_data_file=None, use_settings_from_file=True, fei4b=None):
'''Interprets the raw data word table of all given raw data files with the c++ library.
Creates the h5 output file and PDF plots.
Parameters
----------
analyzed_data_file : string
... | Interprets the raw data word table of all given raw data files with the c++ library.
Creates the h5 output file and PDF plots.
Parameters
----------
analyzed_data_file : string
The file name of the output analyzed data file. If None, the output analyzed data file
... | entailment |
def analyze_hit_table(self, analyzed_data_file=None, analyzed_data_out_file=None):
'''Analyzes a hit table with the c++ histogrammming/clusterizer.
Parameters
----------
analyzed_data_file : string
The filename of the analyzed data file. If None, the analyzed data file
... | Analyzes a hit table with the c++ histogrammming/clusterizer.
Parameters
----------
analyzed_data_file : string
The filename of the analyzed data file. If None, the analyzed data file
specified during initialization is taken.
Filename extension (.h5) does not... | entailment |
def _deduce_settings_from_file(self, opened_raw_data_file): # TODO: parse better
'''Tries to get the scan parameters needed for analysis from the raw data file
'''
try: # take infos raw data files (not avalable in old files)
flavor = opened_raw_data_file.root.configuration.miscella... | Tries to get the scan parameters needed for analysis from the raw data file | entailment |
def _get_plsr_dac_charge(self, plsr_dac_array, no_offset=False):
'''Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis
'''
charge = np.zeros_like(self.c_low_mask, dtype=np.float16) # charge in electrons
if self.... | Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis | entailment |
def _parse_fields(self, result, field_name):
""" If Schema access, parse fields and build respective lists
"""
field_list = []
for key, value in result.get('schema', {}).get(field_name, {}).items():
if key not in field_list:
field_list.append(key)
retu... | If Schema access, parse fields and build respective lists | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.