sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def run(self): """ Listen to the stream and send events to the client. """ channel = self._ssh_client.get_transport().open_session() self._channel = channel channel.exec_command("gerrit stream-events") stdout = channel.makefile() stderr = channel.makefile_stderr() ...
Listen to the stream and send events to the client.
entailment
def run_command(self, command): """ Run a command. :arg str command: The command to run. :Return: The result as a string. :Raises: `ValueError` if `command` is not a string. """ if not isinstance(command, basestring): raise ValueError("command must be a st...
Run a command. :arg str command: The command to run. :Return: The result as a string. :Raises: `ValueError` if `command` is not a string.
entailment
def query(self, term): """ Run a query. :arg str term: The query term to run. :Returns: A list of results as :class:`pygerrit.models.Change` objects. :Raises: `ValueError` if `term` is not a string. """ results = [] command = ["query", "--current-patch-set", "...
Run a query. :arg str term: The query term to run. :Returns: A list of results as :class:`pygerrit.models.Change` objects. :Raises: `ValueError` if `term` is not a string.
entailment
def start_event_stream(self): """ Start streaming events from `gerrit stream-events`. """ if not self._stream: self._stream = GerritStream(self, ssh_client=self._ssh_client) self._stream.start()
Start streaming events from `gerrit stream-events`.
entailment
def stop_event_stream(self): """ Stop streaming events from `gerrit stream-events`.""" if self._stream: self._stream.stop() self._stream.join() self._stream = None with self._events.mutex: self._events.queue.clear()
Stop streaming events from `gerrit stream-events`.
entailment
def get_event(self, block=True, timeout=None): """ Get the next event from the queue. :arg boolean block: Set to True to block if no event is available. :arg seconds timeout: Timeout to wait if no event is available. :Returns: The next event as a :class:`pygerrit.events.GerritEvent` ...
Get the next event from the queue. :arg boolean block: Set to True to block if no event is available. :arg seconds timeout: Timeout to wait if no event is available. :Returns: The next event as a :class:`pygerrit.events.GerritEvent` instance, or `None` if: - `block` is...
entailment
def put_event(self, data): """ Create event from `data` and add it to the queue. :arg json data: The JSON data from which to create the event. :Raises: :class:`pygerrit.error.GerritError` if the queue is full, or the factory could not create the event. """ try: ...
Create event from `data` and add it to the queue. :arg json data: The JSON data from which to create the event. :Raises: :class:`pygerrit.error.GerritError` if the queue is full, or the factory could not create the event.
entailment
def _extract_version(version_string, pattern): """ Extract the version from `version_string` using `pattern`. Return the version as a string, with leading/trailing whitespace stripped. """ if version_string: match = pattern.match(version_string.strip()) if match: return...
Extract the version from `version_string` using `pattern`. Return the version as a string, with leading/trailing whitespace stripped.
entailment
def _configure(self): """ Configure the ssh parameters from the config file. """ configfile = expanduser("~/.ssh/config") if not isfile(configfile): raise GerritError("ssh config file '%s' does not exist" % configfile) config = SSHConfig() ...
Configure the ssh parameters from the config file.
entailment
def _do_connect(self): """ Connect to the remote. """ self.load_system_host_keys() if self.username is None or self.port is None: self._configure() try: self.connect(hostname=self.hostname, port=self.port, username...
Connect to the remote.
entailment
def _connect(self): """ Connect to the remote if not already connected. """ if not self.connected.is_set(): try: self.lock.acquire() # Another thread may have connected while we were # waiting to acquire the lock if not self.con...
Connect to the remote if not already connected.
entailment
def get_remote_version(self): """ Return the version of the remote Gerrit server. """ if self.remote_version is None: result = self.run_gerrit_command("version") version_string = result.stdout.read() pattern = re.compile(r'^gerrit version (.*)$') self.remo...
Return the version of the remote Gerrit server.
entailment
def run_gerrit_command(self, command): """ Run the given command. Make sure we're connected to the remote server, and run `command`. Return the results as a `GerritSSHCommandResult`. Raise `ValueError` if `command` is not a string, or `GerritError` if command execution fails. ...
Run the given command. Make sure we're connected to the remote server, and run `command`. Return the results as a `GerritSSHCommandResult`. Raise `ValueError` if `command` is not a string, or `GerritError` if command execution fails.
entailment
def register(cls, name): """ Decorator to register the event identified by `name`. Return the decorated class. Raise GerritError if the event is already registered. """ def decorate(klazz): """ Decorator. """ if name in cls._events: rai...
Decorator to register the event identified by `name`. Return the decorated class. Raise GerritError if the event is already registered.
entailment
def create(cls, data): """ Create a new event instance. Return an instance of the `GerritEvent` subclass after converting `data` to json. Raise GerritError if json parsed from `data` does not contain a `type` key. """ try: json_data = json.loads(dat...
Create a new event instance. Return an instance of the `GerritEvent` subclass after converting `data` to json. Raise GerritError if json parsed from `data` does not contain a `type` key.
entailment
def _decode_response(response): """ Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error status code. """ con...
Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error status code.
entailment
def put(self, endpoint, **kwargs): """ Send HTTP PUT to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error. """ kwargs.update(self.kwargs.co...
Send HTTP PUT to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error.
entailment
def delete(self, endpoint, **kwargs): """ Send HTTP DELETE to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error. """ kwargs.update(self.kwa...
Send HTTP DELETE to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error.
entailment
def review(self, change_id, revision, review): """ Submit a review. :arg str change_id: The change ID. :arg str revision: The revision. :arg str review: The review details as a :class:`GerritReview`. :returns: JSON decoded result. :raises: reque...
Submit a review. :arg str change_id: The change ID. :arg str revision: The revision. :arg str review: The review details as a :class:`GerritReview`. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error.
entailment
def add_comments(self, comments): """ Add inline comments. :arg dict comments: Comments to add. Usage:: add_comments([{'filename': 'Makefile', 'line': 10, 'message': 'inline message'}]) add_comments([{'filename': '...
Add inline comments. :arg dict comments: Comments to add. Usage:: add_comments([{'filename': 'Makefile', 'line': 10, 'message': 'inline message'}]) add_comments([{'filename': 'Makefile', 'range':...
entailment
def connection_made(self, transport): ''' override asyncio.Protocol ''' self._connected = True self.transport = transport self.remote_ip, self.port = transport.get_extra_info('peername')[:2] logging.debug( 'Connection made (address: {} port: {})' ...
override asyncio.Protocol
entailment
def connection_lost(self, exc): ''' override asyncio.Protocol ''' self._connected = False logging.debug( 'Connection lost (address: {} port: {})' .format(self.remote_ip, self.port)) for pid, (future, task) in self._requests.items(): t...
override asyncio.Protocol
entailment
def data_received(self, data): ''' override asyncio.Protocol ''' self._buffered_data.extend(data) while self._buffered_data: size = len(self._buffered_data) if self._data_package is None: if size < DataPackage.struct_datapackage.size: ...
override asyncio.Protocol
entailment
def connection_made(self, transport): ''' override _SiriDBProtocol ''' self.transport = transport self.remote_ip, self.port = transport.get_extra_info('peername')[:2] logging.debug( 'Connection made (address: {} port: {})' .format(self.remote_ip,...
override _SiriDBProtocol
entailment
def _register_server(self, server, timeout=30): '''Register a new SiriDB Server. This method is used by the SiriDB manage tool and should not be used otherwise. Full access rights are required for this request. ''' result = self._loop.run_until_complete( self._protoc...
Register a new SiriDB Server. This method is used by the SiriDB manage tool and should not be used otherwise. Full access rights are required for this request.
entailment
def _get_file(self, fn, timeout=30): '''Request a SiriDB configuration file. This method is used by the SiriDB manage tool and should not be used otherwise. Full access rights are required for this request. ''' msg = FILE_MAP.get(fn, None) if msg is None: rai...
Request a SiriDB configuration file. This method is used by the SiriDB manage tool and should not be used otherwise. Full access rights are required for this request.
entailment
def _bits_to_float(bits, lower=-90.0, middle=0.0, upper=90.0): """Convert GeoHash bits to a float.""" for i in bits: if i: lower = middle else: upper = middle middle = (upper + lower) / 2 return middle
Convert GeoHash bits to a float.
entailment
def _float_to_bits(value, lower=-90.0, middle=0.0, upper=90.0, length=15): """Convert a float to a list of GeoHash bits.""" ret = [] for i in range(length): if value >= middle: lower = middle ret.append(1) else: upper = middle ret.append(0) middle = (upper + lower) / 2 return...
Convert a float to a list of GeoHash bits.
entailment
def _geohash_to_bits(value): """Convert a GeoHash to a list of GeoHash bits.""" b = map(BASE32MAP.get, value) ret = [] for i in b: out = [] for z in range(5): out.append(i & 0b1) i = i >> 1 ret += out[::-1] return ret
Convert a GeoHash to a list of GeoHash bits.
entailment
def _bits_to_geohash(value): """Convert a list of GeoHash bits to a GeoHash.""" ret = [] # Get 5 bits at a time for i in (value[i:i+5] for i in xrange(0, len(value), 5)): # Convert binary to integer # Note: reverse here, the slice above doesn't work quite right in reverse. total = sum([(bit*2**count...
Convert a list of GeoHash bits to a GeoHash.
entailment
def decode(value): """Decode a geohash. Returns a (lon,lat) pair.""" assert value, "Invalid geohash: %s"%value # Get the GeoHash bits bits = _geohash_to_bits(value) # Unzip the GeoHash bits. lon = bits[0::2] lat = bits[1::2] # Convert to lat/lon return ( _bits_to_float(lon, lower=-180.0, upper=180...
Decode a geohash. Returns a (lon,lat) pair.
entailment
def encode(lonlat, length=12): """Encode a (lon,lat) pair to a GeoHash.""" assert len(lonlat) == 2, "Invalid lon/lat: %s"%lonlat # Half the length for each component. length /= 2 lon = _float_to_bits(lonlat[0], lower=-180.0, upper=180.0, length=length*5) lat = _float_to_bits(lonlat[1], lower=-90.0, upper=90...
Encode a (lon,lat) pair to a GeoHash.
entailment
def adjacent(geohash, direction): """Return the adjacent geohash for a given direction.""" # Based on an MIT licensed implementation by Chris Veness from: # http://www.movable-type.co.uk/scripts/geohash.html assert direction in 'nsew', "Invalid direction: %s"%direction assert geohash, "Invalid geohash: %s"%...
Return the adjacent geohash for a given direction.
entailment
def neighbors(geohash): """Return all neighboring geohashes.""" return { 'n': adjacent(geohash, 'n'), 'ne': adjacent(adjacent(geohash, 'n'), 'e'), 'e': adjacent(geohash, 'e'), 'se': adjacent(adjacent(geohash, 's'), 'e'), 's': adjacent(geohash, 's'), 'sw': adjacent(adjacent(geohash, 's'), ...
Return all neighboring geohashes.
entailment
def thunkify(thread_name=None, daemon=True, default_func=None): '''Make a function immediately return a function of no args which, when called, waits for the result, which will start being processed in another thread. Taken from https://wiki.python.org/moin/PythonDecoratorLibrary. ''' def actual_dec...
Make a function immediately return a function of no args which, when called, waits for the result, which will start being processed in another thread. Taken from https://wiki.python.org/moin/PythonDecoratorLibrary.
entailment
def set_event_when_keyboard_interrupt(_lambda): '''Decorator function that sets Threading.Event() when keyboard interrupt (Ctrl+C) was raised Parameters ---------- _lambda : function Lambda function that points to Threading.Event() object Returns ------- wrapper : function Exa...
Decorator function that sets Threading.Event() when keyboard interrupt (Ctrl+C) was raised Parameters ---------- _lambda : function Lambda function that points to Threading.Event() object Returns ------- wrapper : function Examples -------- @set_event_when_keyboard_interru...
entailment
def run_id(self): '''Run name without whitespace ''' s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', self.__class__.__name__) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Run name without whitespace
entailment
def conf(self): '''Configuration (namedtuple) ''' conf = namedtuple('conf', field_names=self._conf.keys()) return conf(**self._conf)
Configuration (namedtuple)
entailment
def run_conf(self): '''Run configuration (namedtuple) ''' run_conf = namedtuple('run_conf', field_names=self._run_conf.keys()) return run_conf(**self._run_conf)
Run configuration (namedtuple)
entailment
def default_run_conf(self): '''Default run configuration (namedtuple) ''' default_run_conf = namedtuple('default_run_conf', field_names=self._default_run_conf.keys()) return default_run_conf(**self._default_run_conf)
Default run configuration (namedtuple)
entailment
def _init(self, run_conf, run_number=None): '''Initialization before a new run. ''' self.stop_run.clear() self.abort_run.clear() self._run_status = run_status.running self._write_run_number(run_number) self._init_run_conf(run_conf)
Initialization before a new run.
entailment
def connect_cancel(self, functions): '''Run given functions when a run is cancelled. ''' self._cancel_functions = [] for func in functions: if isinstance(func, basestring) and hasattr(self, func) and callable(getattr(self, func)): self._cancel_functions.append...
Run given functions when a run is cancelled.
entailment
def handle_cancel(self, **kwargs): '''Cancelling a run. ''' for func in self._cancel_functions: f_args = getargspec(func)[0] f_kwargs = {key: kwargs[key] for key in f_args if key in kwargs} func(**f_kwargs)
Cancelling a run.
entailment
def stop(self, msg=None): '''Stopping a run. Control for loops. Gentle stop/abort. This event should provide a more gentle abort. The run should stop ASAP but the run is still considered complete. ''' if not self.stop_run.is_set(): if msg: logging.info('%s%s ...
Stopping a run. Control for loops. Gentle stop/abort. This event should provide a more gentle abort. The run should stop ASAP but the run is still considered complete.
entailment
def abort(self, msg=None): '''Aborting a run. Control for loops. Immediate stop/abort. The implementation should stop a run ASAP when this event is set. The run is considered incomplete. ''' if not self.abort_run.is_set(): if msg: logging.error('%s%s Aborting...
Aborting a run. Control for loops. Immediate stop/abort. The implementation should stop a run ASAP when this event is set. The run is considered incomplete.
entailment
def run_run(self, run, conf=None, run_conf=None, use_thread=False, catch_exception=True): '''Runs a run in another thread. Non-blocking. Parameters ---------- run : class, object Run class or object. run_conf : str, dict, file Specific configuration for t...
Runs a run in another thread. Non-blocking. Parameters ---------- run : class, object Run class or object. run_conf : str, dict, file Specific configuration for the run. use_thread : bool If True, run run in thread and returns blocking functio...
entailment
def run_primlist(self, primlist, skip_remaining=False): '''Runs runs from a primlist. Parameters ---------- primlist : string Filename of primlist. skip_remaining : bool If True, skip remaining runs, if a run does not exit with status FINISHED. N...
Runs runs from a primlist. Parameters ---------- primlist : string Filename of primlist. skip_remaining : bool If True, skip remaining runs, if a run does not exit with status FINISHED. Note ---- Primlist is a text file of the following f...
entailment
def analyze_beam_spot(scan_base, combine_n_readouts=1000, chunk_size=10000000, plot_occupancy_hists=False, output_pdf=None, output_file=None): ''' Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The occupanc...
Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The occupancy is determined for the given combined events and stored into a pdf file. At the end the beam x and y is plotted into a scatter plot with absolute ...
entailment
def analyze_event_rate(scan_base, combine_n_readouts=1000, time_line_absolute=True, output_pdf=None, output_file=None): ''' Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data i...
Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data info and stored into a pdf file. Parameters ---------- scan_base: list of str scan base names (e.g.: ['...
entailment
def analyse_n_cluster_per_event(scan_base, include_no_cluster=False, time_line_absolute=True, combine_n_readouts=1000, chunk_size=10000000, plot_n_cluster_hists=False, output_pdf=None, output_file=None): ''' Determines the number of cluster per event as a function of time. Therefore the data of a fixed number of re...
Determines the number of cluster per event as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). Parameters ---------- scan_base: list of str scan base names (e.g.: ['//data//SCC_50_fei4_self_trigger_scan_390', ] include_no_cluster: bool ...
entailment
def select_hits_from_cluster_info(input_file_hits, output_file_hits, cluster_size_condition, n_cluster_condition, chunk_size=4000000): ''' Takes a hit table and stores only selected hits into a new table. The selection is done on an event base and events are selected if they have a certain number of cluster or clus...
Takes a hit table and stores only selected hits into a new table. The selection is done on an event base and events are selected if they have a certain number of cluster or cluster size. To increase the analysis speed a event index for the input hit file is created first. Since a cluster hit table can be created to...
entailment
def select_hits(input_file_hits, output_file_hits, condition=None, cluster_size_condition=None, n_cluster_condition=None, chunk_size=5000000): ''' Takes a hit table and stores only selected hits into a new table. The selection of hits is done with a numexp string. Only if this expression evaluates to true the h...
Takes a hit table and stores only selected hits into a new table. The selection of hits is done with a numexp string. Only if this expression evaluates to true the hit is taken. One can also select hits from cluster conditions. This selection is done on an event basis, meaning events are selected where the clus...
entailment
def analyze_cluster_size_per_scan_parameter(input_file_hits, output_file_cluster_size, parameter='GDAC', max_chunk_size=10000000, overwrite_output_files=False, output_pdf=None): ''' This method takes multiple hit files and determines the cluster size for different scan parameter values of Parameters -----...
This method takes multiple hit files and determines the cluster size for different scan parameter values of Parameters ---------- input_files_hits: string output_file_cluster_size: string The data file with the results parameter: string The name of the parameter to separate the dat...
entailment
def histogram_cluster_table(analyzed_data_file, output_file, chunk_size=10000000): '''Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array. The 3rd dimension of the occupancy array is the number of different scan parameters used Parameters ---------- ana...
Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array. The 3rd dimension of the occupancy array is the number of different scan parameters used Parameters ---------- analyzed_data_file : string HDF5 filename of the file containing the cluster table. I...
entailment
def analyze_hits_per_scan_parameter(analyze_data, scan_parameters=None, chunk_size=50000): '''Takes the hit table and analyzes the hits per scan parameter Parameters ---------- analyze_data : analysis.analyze_raw_data.AnalyzeRawData object with an opened hit file (AnalyzeRawData.out_file_h5) or a f...
Takes the hit table and analyzes the hits per scan parameter Parameters ---------- analyze_data : analysis.analyze_raw_data.AnalyzeRawData object with an opened hit file (AnalyzeRawData.out_file_h5) or a file name with the hit data given (AnalyzeRawData._analyzed_data_file) scan_parameters : list o...
entailment
def interpret_data_from_tektronix(preamble, data): ''' Interprets raw data from Tektronix returns: lists of x, y values in seconds/volt''' # Y mode ("WFMPRE:PT_FMT"): # Xn = XZEro + XINcr (n - PT_Off) # Yn = YZEro + YMUlt (yn - YOFf) voltage = np.array(data, dtype=np.float) meta_data = pream...
Interprets raw data from Tektronix returns: lists of x, y values in seconds/volt
entailment
def read_chip_sn(self): '''Reading Chip S/N Note ---- Bits [MSB-LSB] | [15] | [14-6] | [5-0] Content | reserved | wafer number | chip number ''' commands = [] commands.extend(self.register.get_commands("ConfMode")) self.register_utils.send_commands(com...
Reading Chip S/N Note ---- Bits [MSB-LSB] | [15] | [14-6] | [5-0] Content | reserved | wafer number | chip number
entailment
def read_global_register(self, name, overwrite_config=False): '''The function reads the global register, interprets the data and returns the register value. Parameters ---------- name : register name overwrite_config : bool The read values overwrite the config in RAM if true. ...
The function reads the global register, interprets the data and returns the register value. Parameters ---------- name : register name overwrite_config : bool The read values overwrite the config in RAM if true. Returns ------- register value
entailment
def read_pixel_register(self, pix_regs=None, dcs=range(40), overwrite_config=False): '''The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register. Pixels without any data are masked. Parameters ---------- pix_regs ...
The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register. Pixels without any data are masked. Parameters ---------- pix_regs : iterable, string List of pixel register to read (e.g. Enable, C_High, ...). ...
entailment
def is_fe_ready(self): '''Get FEI4 status of module. If FEI4 is not ready, resetting service records is necessary to bring the FEI4 to a defined state. Returns ------- value : bool True if FEI4 is ready, False if the FEI4 was powered up recently and is not ready. ''' with...
Get FEI4 status of module. If FEI4 is not ready, resetting service records is necessary to bring the FEI4 to a defined state. Returns ------- value : bool True if FEI4 is ready, False if the FEI4 was powered up recently and is not ready.
entailment
def invert_pixel_mask(mask): '''Invert pixel mask (0->1, 1(and greater)->0). Parameters ---------- mask : array-like Mask. Returns ------- inverted_mask : array-like Inverted Mask. ''' inverted_mask = np.ones(shape=(80, 336), dtype=np.dtype('>u1')) ...
Invert pixel mask (0->1, 1(and greater)->0). Parameters ---------- mask : array-like Mask. Returns ------- inverted_mask : array-like Inverted Mask.
entailment
def make_pixel_mask(steps, shift, default=0, value=1, enable_columns=None, mask=None): '''Generate pixel mask. Parameters ---------- steps : int Number of mask steps, e.g. steps=3 (every third pixel is enabled), steps=336 (one pixel per column), steps=672 (one pixel per double column). ...
Generate pixel mask. Parameters ---------- steps : int Number of mask steps, e.g. steps=3 (every third pixel is enabled), steps=336 (one pixel per column), steps=672 (one pixel per double column). shift : int Shift mask by given value to the bottom (towards higher row numbers). F...
entailment
def make_pixel_mask_from_col_row(column, row, default=0, value=1): '''Generate mask from column and row lists Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not ...
Generate mask from column and row lists Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not selected by the mask. value : int Value of pixels that are se...
entailment
def make_box_pixel_mask_from_col_row(column, row, default=0, value=1): '''Generate box shaped mask from column and row lists. Takes the minimum and maximum value from each list. Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of r...
Generate box shaped mask from column and row lists. Takes the minimum and maximum value from each list. Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not selected by...
entailment
def make_xtalk_mask(mask): """ Generate xtalk mask (row - 1, row + 1) from pixel mask. Parameters ---------- mask : ndarray Pixel mask. Returns ------- ndarray Xtalk mask. Example ------- Input: [[1 0 0 0 0 0 1 0 0 0 ... 0 0 0 0 1 0 0 0...
Generate xtalk mask (row - 1, row + 1) from pixel mask. Parameters ---------- mask : ndarray Pixel mask. Returns ------- ndarray Xtalk mask. Example ------- Input: [[1 0 0 0 0 0 1 0 0 0 ... 0 0 0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 1 ... 0 1 ...
entailment
def make_checkerboard_mask(column_distance, row_distance, column_offset=0, row_offset=0, default=0, value=1): """ Generate chessboard/checkerboard mask. Parameters ---------- column_distance : int Column distance of the enabled pixels. row_distance : int Row distance of...
Generate chessboard/checkerboard mask. Parameters ---------- column_distance : int Column distance of the enabled pixels. row_distance : int Row distance of the enabled pixels. column_offset : int Additional column offset which shifts the columns by the given amount...
entailment
def scan_loop(self, command, repeat_command=100, use_delay=True, additional_delay=0, mask_steps=3, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=False, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=None, disable_shift_masks=None, restore_...
Implementation of the scan loops (mask shifting, loop over double columns, repeatedly sending any arbitrary command). Parameters ---------- command : BitVector (FEI4) command that will be sent out serially. repeat_command : int The number of repetitions command will be sent out e...
entailment
def reset_service_records(self): '''Resetting Service Records This will reset Service Record counters. This will also bring back alive some FE where the output FIFO is stuck (no data is coming out in run mode). This should be only issued after power up and in the case of a stuck FIFO, other...
Resetting Service Records This will reset Service Record counters. This will also bring back alive some FE where the output FIFO is stuck (no data is coming out in run mode). This should be only issued after power up and in the case of a stuck FIFO, otherwise the BCID counter starts jumping.
entailment
def reset_bunch_counter(self): '''Resetting Bunch Counter ''' logging.info('Resetting Bunch Counter') commands = [] commands.extend(self.register.get_commands("RunMode")) commands.extend(self.register.get_commands("BCR")) self.send_commands(commands) ...
Resetting Bunch Counter
entailment
def generate_threshold_mask(hist): '''Masking array elements when equal 0.0 or greater than 10 times the median Parameters ---------- hist : array_like Input data. Returns ------- masked array Returns copy of the array with masked elements. ''' masked_array = np.ma....
Masking array elements when equal 0.0 or greater than 10 times the median Parameters ---------- hist : array_like Input data. Returns ------- masked array Returns copy of the array with masked elements.
entailment
def unique_row(array, use_columns=None, selected_columns_only=False): '''Takes a numpy array and returns the array reduced to unique rows. If columns are defined only these columns are taken to define a unique row. The returned array can have all columns of the original array or only the columns defined in use_...
Takes a numpy array and returns the array reduced to unique rows. If columns are defined only these columns are taken to define a unique row. The returned array can have all columns of the original array or only the columns defined in use_columns. Parameters ---------- array : numpy.ndarray use_colu...
entailment
def get_ranges_from_array(arr, append_last=True): '''Takes an array and calculates ranges [start, stop[. The last range end is none to keep the same length. Parameters ---------- arr : array like append_last: bool If True, append item with a pair of last array item and None. Returns ...
Takes an array and calculates ranges [start, stop[. The last range end is none to keep the same length. Parameters ---------- arr : array like append_last: bool If True, append item with a pair of last array item and None. Returns ------- numpy.array The array formed by pai...
entailment
def in1d_sorted(ar1, ar2): """ Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted. Is therefore much faster. """ if ar1.shape[0] == 0 or ar2.shape[0] == 0: # check for empty arrays to avoid crash return [] inds = ar2.searchsorted(ar1) inds[inds == len(ar2)] = 0 ...
Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted. Is therefore much faster.
entailment
def central_difference(x, y): '''Returns the dy/dx(x) via central difference method Parameters ---------- x : array like y : array like Returns ------- dy/dx : array like ''' if (len(x) != len(y)): raise ValueError("x, y must have the same length") z1 = np.hstack((y...
Returns the dy/dx(x) via central difference method Parameters ---------- x : array like y : array like Returns ------- dy/dx : array like
entailment
def get_profile_histogram(x, y, n_bins=100): '''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...
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 n_b...
entailment
def get_rate_normalization(hit_file, parameter, reference='event', cluster_file=None, plot=False, chunk_size=500000): ''' Takes different hit files (hit_files), extracts the number of events or the scan time (reference) per scan parameter (parameter) and returns an array with a normalization factor. This normal...
Takes different hit files (hit_files), extracts the number of events or the scan time (reference) per scan parameter (parameter) and returns an array with a normalization factor. This normalization factor has the length of the number of different parameters. If a cluster_file is specified also the number of clu...
entailment
def get_parameter_value_from_file_names(files, parameters=None, unique=False, sort=True): """ Takes a list of files, searches for the parameter name in the file name and returns a ordered dict with the file name in the first dimension and the corresponding parameter value in the second. The file names c...
Takes a list of files, searches for the parameter name in the file name and returns a ordered dict with the file name in the first dimension and the corresponding parameter value in the second. The file names can be sorted by the parameter value, otherwise the order is kept. If unique is true every parameter is...
entailment
def get_data_file_names_from_scan_base(scan_base, filter_str=['_analyzed.h5', '_interpreted.h5', '_cut.h5', '_result.h5', '_hists.h5'], sort_by_time=True, meta_data_v2=True): """ Generate a list of .h5 files which have a similar file name. Parameters ---------- scan_base : list, string List...
Generate a list of .h5 files which have a similar file name. Parameters ---------- scan_base : list, string List of string or string of the scan base names. The scan_base will be used to search for files containing the string. The .h5 file extension will be added automatically. filter : list, s...
entailment
def get_parameter_from_files(files, parameters=None, unique=False, sort=True): ''' Takes a list of files, searches for the parameter name in the file name and in the file. Returns a ordered dict with the file name in the first dimension and the corresponding parameter values in the second. If a scan paramet...
Takes a list of files, searches for the parameter name in the file name and in the file. Returns a ordered dict with the file name in the first dimension and the corresponding parameter values in the second. If a scan parameter appears in the file name and in the file the first parameter setting has to be in th...
entailment
def check_parameter_similarity(files_dict): """ Checks if the parameter names of all files are similar. Takes the dictionary from get_parameter_from_files output as input. """ try: parameter_names = files_dict.itervalues().next().keys() # get the parameter names of the first file, to check if ...
Checks if the parameter names of all files are similar. Takes the dictionary from get_parameter_from_files output as input.
entailment
def combine_meta_data(files_dict, meta_data_v2=True): """ Takes the dict of hdf5 files and combines their meta data tables into one new numpy record array. Parameters ---------- meta_data_v2 : bool True for new (v2) meta data format, False for the old (v1) format. """ if len(files_d...
Takes the dict of hdf5 files and combines their meta data tables into one new numpy record array. Parameters ---------- meta_data_v2 : bool True for new (v2) meta data format, False for the old (v1) format.
entailment
def smooth_differentiation(x, y, weigths=None, order=5, smoothness=3, derivation=1): '''Returns the dy/dx(x) with the fit and differentiation of a spline curve Parameters ---------- x : array like y : array like Returns ------- dy/dx : array like ''' if (len(x) != len(y)): ...
Returns the dy/dx(x) with the fit and differentiation of a spline curve Parameters ---------- x : array like y : array like Returns ------- dy/dx : array like
entailment
def reduce_sorted_to_intersect(ar1, ar2): """ Takes two sorted arrays and return the intersection ar1 in ar2, ar2 in ar1. Parameters ---------- ar1 : (M,) array_like Input array. ar2 : array_like Input array. Returns ------- ar1, ar1 : ndarray, ndarray The ...
Takes two sorted arrays and return the intersection ar1 in ar2, ar2 in ar1. Parameters ---------- ar1 : (M,) array_like Input array. ar2 : array_like Input array. Returns ------- ar1, ar1 : ndarray, ndarray The intersection values.
entailment
def get_not_unique_values(array): '''Returns the values that appear at least twice in array. Parameters ---------- array : array like Returns ------- numpy.array ''' s = np.sort(array, axis=None) s = s[s[1:] == s[:-1]] return np.unique(s)
Returns the values that appear at least twice in array. Parameters ---------- array : array like Returns ------- numpy.array
entailment
def get_meta_data_index_at_scan_parameter(meta_data_array, scan_parameter_name): '''Takes the analyzed meta_data table and returns the indices where the scan parameter changes Parameters ---------- meta_data_array : numpy.recordarray scan_parameter_name : string Returns ------- numpy.n...
Takes the analyzed meta_data table and returns the indices where the scan parameter changes Parameters ---------- meta_data_array : numpy.recordarray scan_parameter_name : string Returns ------- numpy.ndarray: first dimension: scan parameter value second dimension: index wh...
entailment
def select_hits(hits_array, condition=None): '''Selects the hits with condition. E.g.: condition = 'rel_BCID == 7 & event_number < 1000' Parameters ---------- hits_array : numpy.array condition : string A condition that is applied to the hits in numexpr. Only if the expression evaluates...
Selects the hits with condition. E.g.: condition = 'rel_BCID == 7 & event_number < 1000' Parameters ---------- hits_array : numpy.array condition : string A condition that is applied to the hits in numexpr. Only if the expression evaluates to True the hit is taken. Returns ------- ...
entailment
def get_hits_in_events(hits_array, events, assume_sorted=True, condition=None): '''Selects the hits that occurred in events and optional selection criterion. If a event range can be defined use the get_data_in_event_range function. It is much faster. Parameters ---------- hits_array : numpy.arr...
Selects the hits that occurred in events and optional selection criterion. If a event range can be defined use the get_data_in_event_range function. It is much faster. Parameters ---------- hits_array : numpy.array events : array assume_sorted : bool Is true if the events to select ...
entailment
def get_hits_of_scan_parameter(input_file_hits, scan_parameters=None, try_speedup=False, chunk_size=10000000): '''Takes the hit table of a hdf5 file and returns hits in chunks for each unique combination of scan_parameters. Yields the hits in chunks, since they usually do not fit into memory. Parameters ...
Takes the hit table of a hdf5 file and returns hits in chunks for each unique combination of scan_parameters. Yields the hits in chunks, since they usually do not fit into memory. Parameters ---------- input_file_hits : pytable hdf5 file Has to include a hits node scan_parameters : iterable...
entailment
def get_data_in_event_range(array, event_start=None, event_stop=None, assume_sorted=True): '''Selects the data (rows of a table) that occurred in the given event range [event_start, event_stop[ Parameters ---------- array : numpy.array event_start : int, None event_stop : int, None assume_s...
Selects the data (rows of a table) that occurred in the given event range [event_start, event_stop[ Parameters ---------- array : numpy.array event_start : int, None event_stop : int, None assume_sorted : bool Set to true if the hits are sorted by the event_number. Increases speed. ...
entailment
def write_hits_in_events(hit_table_in, hit_table_out, events, start_hit_word=0, chunk_size=5000000, condition=None): '''Selects the hits that occurred in events and writes them to a pytable. This function reduces the in RAM operations and has to be used if the get_hits_in_events function raises a memory error. ...
Selects the hits that occurred in events and writes them to a pytable. This function reduces the in RAM operations and has to be used if the get_hits_in_events function raises a memory error. Also a condition can be set to select hits. Parameters ---------- hit_table_in : pytable.table hit_table_ou...
entailment
def write_hits_in_event_range(hit_table_in, hit_table_out, event_start=None, event_stop=None, start_hit_word=0, chunk_size=5000000, condition=None): '''Selects the hits that occurred in given event range [event_start, event_stop[ and write them to a pytable. This function reduces the in RAM operations and ha...
Selects the hits that occurred in given event range [event_start, event_stop[ and write them to a pytable. This function reduces the in RAM operations and has to be used if the get_data_in_event_range function raises a memory error. Also a condition can be set to select hits. Parameters ---------- h...
entailment
def get_events_with_n_cluster(event_number, condition='n_cluster==1'): '''Selects the events with a certain number of cluster. Parameters ---------- event_number : numpy.array Returns ------- numpy.array ''' logging.debug("Calculate events with clusters where " + condition) n_...
Selects the events with a certain number of cluster. Parameters ---------- event_number : numpy.array Returns ------- numpy.array
entailment
def get_events_with_cluster_size(event_number, cluster_size, condition='cluster_size==1'): '''Selects the events with cluster of a given cluster size. Parameters ---------- event_number : numpy.array cluster_size : numpy.array condition : string Returns ------- numpy.array ''' ...
Selects the events with cluster of a given cluster size. Parameters ---------- event_number : numpy.array cluster_size : numpy.array condition : string Returns ------- numpy.array
entailment
def get_events_with_error_code(event_number, event_status, select_mask=0b1111111111111111, condition=0b0000000000000000): '''Selects the events with a certain error code. Parameters ---------- event_number : numpy.array event_status : numpy.array select_mask : int The mask that selects ...
Selects the events with a certain error code. Parameters ---------- event_number : numpy.array event_status : numpy.array select_mask : int The mask that selects the event error code to check. condition : int The value the selected event error code should have. Returns ...
entailment
def get_scan_parameter(meta_data_array, unique=True): '''Takes the numpy meta data array and returns the different scan parameter settings and the name aligned in a dictionary Parameters ---------- meta_data_array : numpy.ndarray unique: boolean If true only unique values for each scan para...
Takes the numpy meta data array and returns the different scan parameter settings and the name aligned in a dictionary Parameters ---------- meta_data_array : numpy.ndarray unique: boolean If true only unique values for each scan parameter are returned Returns ------- python.dict{s...
entailment
def get_scan_parameters_table_from_meta_data(meta_data_array, scan_parameters=None): '''Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data . Parameters ---------- meta_data_array : numpy.ndarray The array with the scan pa...
Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data . Parameters ---------- meta_data_array : numpy.ndarray The array with the scan parameters. scan_parameters : list of strings The name of the scan parameters to t...
entailment
def get_scan_parameters_index(scan_parameter): '''Takes the scan parameter array and creates a scan parameter index labeling the unique scan parameter combinations. Parameters ---------- scan_parameter : numpy.ndarray The table with the scan parameters. Returns ------- numpy.Histogr...
Takes the scan parameter array and creates a scan parameter index labeling the unique scan parameter combinations. Parameters ---------- scan_parameter : numpy.ndarray The table with the scan parameters. Returns ------- numpy.Histogram
entailment
def get_unique_scan_parameter_combinations(meta_data_array, scan_parameters=None, scan_parameter_columns_only=False): '''Takes the numpy meta data array and returns the first rows with unique combinations of different scan parameter values for selected scan parameters. If selected columns only is true, the ...
Takes the numpy meta data array and returns the first rows with unique combinations of different scan parameter values for selected scan parameters. If selected columns only is true, the returned histogram only contains the selected columns. Parameters ---------- meta_data_array : numpy.ndarray ...
entailment
def data_aligned_at_events(table, start_event_number=None, stop_event_number=None, start_index=None, stop_index=None, chunk_size=10000000, try_speedup=False, first_event_aligned=True, fail_on_missing_events=True): '''Takes the table with a event_number column and returns chunks with the size up to chunk_size. The c...
Takes the table with a event_number column and returns chunks with the size up to chunk_size. The chunks are chosen in a way that the events are not splitted. Additional parameters can be set to increase the readout speed. Events between a certain range can be selected. Also the start and the stop indices limit...
entailment
def select_good_pixel_region(hits, col_span, row_span, min_cut_threshold=0.2, max_cut_threshold=2.0): '''Takes the hit array and masks all pixels with a certain occupancy. Parameters ---------- hits : array like If dim > 2 the additional dimensions are summed up. min_cut_threshold : float ...
Takes the hit array and masks all pixels with a certain occupancy. Parameters ---------- hits : array like If dim > 2 the additional dimensions are summed up. min_cut_threshold : float A number to specify the minimum threshold, which pixel to take. Pixels are masked if occupancy...
entailment