INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Convert a single string into a list of substrings split along punctuation and word boundaries. Keep whitespace intact by always attaching it to the previous token. | def tokenize(text, normalize_ascii=True):
"""
Convert a single string into a list of substrings
split along punctuation and word boundaries. Keep
whitespace intact by always attaching it to the
previous token.
Arguments:
----------
text : str
normalize_ascii : bool, perform ... |
Main command line interface. | def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:]
cli = CommandLineTool()
try:
return cli.run(argv)
except KeyboardInterrupt:
print('Canceled')
return 3 |
Create the cipher object to encrypt or decrypt a payload. | def _create_cipher(self, password, salt, nonce = None):
"""
Create the cipher object to encrypt or decrypt a payload.
"""
from argon2.low_level import hash_secret_raw, Type
from Crypto.Cipher import AES
aesmode = self._get_mode(self.aesmode)
if aesmode is None: ... |
Return the AES mode or a list of valid AES modes if mode == None | def _get_mode(mode = None):
"""
Return the AES mode, or a list of valid AES modes, if mode == None
"""
from Crypto.Cipher import AES
AESModeMap = {
'CCM': AES.MODE_CCM,
'EAX': AES.MODE_EAX,
'GCM': AES.MODE_GCM,
'OCB': AES.MODE_OCB,... |
Applicable for all platforms where the schemes that are integrated with your environment does not fit. | def priority(self):
"""
Applicable for all platforms, where the schemes, that are integrated
with your environment, does not fit.
"""
try:
__import__('argon2.low_level')
except ImportError: # pragma: no cover
raise RuntimeError("argon2_cffi pac... |
check for a valid scheme | def _check_scheme(self, config):
"""
check for a valid scheme
raise AttributeError if missing
raise ValueError if not valid
"""
try:
scheme = config.get(
escape_for_ini('keyring-setting'),
escape_for_ini('scheme'),
... |
Starts the global Twisted logger subsystem with maybe stdout and/ or a file specified in the config file | def startLogging(console=True, filepath=None):
'''
Starts the global Twisted logger subsystem with maybe
stdout and/or a file specified in the config file
'''
global logLevelFilterPredicate
observers = []
if console:
observers.append( FilteringLogObserver(observer=textFileLogObse... |
Set a new log level for a given namespace LevelStr is: critical error warn info debug | def setLogLevel(namespace=None, levelStr='info'):
'''
Set a new log level for a given namespace
LevelStr is: 'critical', 'error', 'warn', 'info', 'debug'
'''
level = LogLevel.levelWithName(levelStr)
logLevelFilterPredicate.setLogLevelForNamespace(namespace=namespace, level=level) |
Connect to MQTT broker | def connectToBroker(self, protocol):
'''
Connect to MQTT broker
'''
self.protocol = protocol
self.protocol.onPublish = self.onPublish
self.protocol.onDisconnection = self.onDisconnection
self.protocol.setWindowSize(3)
try:
... |
Callback Receiving messages from publisher | def onPublish(self, topic, payload, qos, dup, retain, msgId):
'''
Callback Receiving messages from publisher
'''
log.debug("msg={payload}", payload=payload) |
get notfied of disconnections and get a deferred for a new protocol object ( next retry ) | def onDisconnection(self, reason):
'''
get notfied of disconnections
and get a deferred for a new protocol object (next retry)
'''
log.debug("<Connection was lost !> <reason={r}>", r=reason)
self.whenConnected().addCallback(self.connectToBroker) |
Connect to MQTT broker | def connectToBroker(self, protocol):
'''
Connect to MQTT broker
'''
self.protocol = protocol
self.protocol.onPublish = self.onPublish
self.protocol.onDisconnection = self.onDisconnection
self.protocol.setWindowSize(3)
self.task = task... |
Produce ids for Protocol packets outliving their sessions | def makeId(self):
'''Produce ids for Protocol packets, outliving their sessions'''
self.id = (self.id + 1) % 65536
self.id = self.id or 1 # avoid id 0
return self.id |
Send a CONNECT control packet. | def connect(self, request):
'''
Send a CONNECT control packet.
'''
state = self.__class__.__name__
return defer.fail(MQTTStateError("Unexpected connect() operation", state)) |
Handles CONNACK packet from the server | def handleCONNACK(self, response):
'''
Handles CONNACK packet from the server
'''
state = self.__class__.__name__
log.error("Unexpected {packet:7} packet received in {log_source}", packet="CONNACK") |
Abstract ======== | def connect(clientId, keepalive=0, willTopic=None,
willMessage=None, willQoS=0, willRetain=False,
username=None, password=None, cleanStart=True, version=mqtt.v311):
'''
Abstract
========
Send a CONNECT control packet.
Description
=======... |
Encode an UTF - 8 string into MQTT format. Returns a bytearray | def encodeString(string):
'''
Encode an UTF-8 string into MQTT format.
Returns a bytearray
'''
encoded = bytearray(2)
encoded.extend(bytearray(string, encoding='utf-8'))
l = len(encoded)-2
if(l > 65535):
raise StringValueError(l)
encoded[0] = l >> 8
encoded[1] = l & 0xFF... |
Decodes an UTF - 8 string from an encoded MQTT bytearray. Returns the decoded string and renaining bytearray to be parsed | def decodeString(encoded):
'''
Decodes an UTF-8 string from an encoded MQTT bytearray.
Returns the decoded string and renaining bytearray to be parsed
'''
length = encoded[0]*256 + encoded[1]
return (encoded[2:2+length].decode('utf-8'), encoded[2+length:]) |
Encodes a 16 bit unsigned integer into MQTT format. Returns a bytearray | def encode16Int(value):
'''
Encodes a 16 bit unsigned integer into MQTT format.
Returns a bytearray
'''
value = int(value)
encoded = bytearray(2)
encoded[0] = value >> 8
encoded[1] = value & 0xFF
return encoded |
Encodes value into a multibyte sequence defined by MQTT protocol. Used to encode packet length fields. | def encodeLength(value):
'''
Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet length fields.
'''
encoded = bytearray()
while True:
digit = value % 128
value //= 128
if value > 0:
digit |= 128
encoded.append(digit)... |
Decodes a variable length value defined in the MQTT protocol. This value typically represents remaining field lengths | def decodeLength(encoded):
'''
Decodes a variable length value defined in the MQTT protocol.
This value typically represents remaining field lengths
'''
value = 0
multiplier = 1
for i in encoded:
value += (i & 0x7F) * multiplier
multiplier *= 0x80
if (i & 0x80) !... |
Encode and store a DISCONNECT control packet. | def encode(self):
'''
Encode and store a DISCONNECT control packet.
'''
header = bytearray(2)
header[0] = 0xE0
self.encoded = header
return str(header) if PY2 else bytes(header) |
Encode and store a CONNECT control packet. | def encode(self):
'''
Encode and store a CONNECT control packet.
@raise e: C{ValueError} if any encoded topic string exceeds 65535 bytes.
@raise e: C{ValueError} if encoded username string exceeds 65535 bytes.
'''
header = bytearray(1)
varHeader = bytearray()
... |
Decode a CONNECT control packet. | def decode(self, packet):
'''
Decode a CONNECT control packet.
'''
self.encoded = packet
# Strip the fixed header plus variable length field
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
# Var... |
Encode and store a CONNACK control packet. | def encode(self):
'''
Encode and store a CONNACK control packet.
'''
header = bytearray(1)
varHeader = bytearray(2)
header[0] = 0x20
varHeader[0] = self.session
varHeader[1] = self.resultCode
header.extend(encodeLength(len(varHe... |
Decode a CONNACK control packet. | def decode(self, packet):
'''
Decode a CONNACK control packet.
'''
self.encoded = packet
# Strip the fixed header plus variable length field
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
self.... |
Decode a SUBSCRIBE control packet. | def decode(self, packet):
'''
Decode a SUBSCRIBE control packet.
'''
self.encoded = packet
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
self.msgId = decode16Int(packet_remaining[0:2])
self.... |
Encode and store a SUBACK control packet. | def encode(self):
'''
Encode and store a SUBACK control packet.
'''
header = bytearray(1)
payload = bytearray()
varHeader = encode16Int(self.msgId)
header[0] = 0x90
for code in self.granted:
payload.append(code[0] | (0x80 if code[1] == Tru... |
Encode and store an UNSUBCRIBE control packet | def encode(self):
'''
Encode and store an UNSUBCRIBE control packet
@raise e: C{ValueError} if any encoded topic string exceeds 65535 bytes
'''
header = bytearray(1)
payload = bytearray()
varHeader = encode16Int(self.msgId)
header[0] = 0xA2 # packe... |
Decode a UNSUBACK control packet. | def decode(self, packet):
'''
Decode a UNSUBACK control packet.
'''
self.encoded = packet
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
self.msgId = decode16Int(packet_remaining[0:2])
self.t... |
Encode and store an UNSUBACK control packet | def encode(self):
'''
Encode and store an UNSUBACK control packet
'''
header = bytearray(1)
varHeader = encode16Int(self.msgId)
header[0] = 0xB0
header.extend(encodeLength(len(varHeader)))
header.extend(varHeader)
self.encoded = header
... |
Encode and store a PUBLISH control packet. | def encode(self):
'''
Encode and store a PUBLISH control packet.
@raise e: C{ValueError} if encoded topic string exceeds 65535 bytes.
@raise e: C{ValueError} if encoded packet size exceeds 268435455 bytes.
@raise e: C{TypeError} if C{data} is not a string, bytearray, int, boolean... |
Decode a PUBLISH control packet. | def decode(self, packet):
'''
Decode a PUBLISH control packet.
'''
self.encoded = packet
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
self.dup = (packet[0] & 0x08) == 0x08
self.qos = (p... |
Decode a PUBREL control packet. | def decode(self, packet):
'''
Decode a PUBREL control packet.
'''
self.encoded = packet
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
self.msgId = decode16Int(packet_remaining)
self.dup = (pa... |
Return url for call method. | def get_url(self, method=None, **kwargs):
"""Return url for call method.
:param method (optional): `str` method name.
:returns: `str` URL.
"""
kwargs.setdefault('v', self.__version)
if self.__token is not None:
kwargs.setdefault('access_token', self.__token)... |
Send request to API. | def request(self, method, **kwargs):
"""
Send request to API.
:param method: `str` method name.
:returns: `dict` response.
"""
kwargs.setdefault('v', self.__version)
if self.__token is not None:
kwargs.setdefault('access_token', self.__token)
... |
Authentication on vk. com. | def authentication(login, password):
"""
Authentication on vk.com.
:param login: login on vk.com.
:param password: password on vk.com.
:returns: `requests.Session` session with cookies.
"""
session = requests.Session()
response = session.get('https://m.vk.com')
url = re.search(r'act... |
OAuth on vk. com. | def oauth(login, password, app_id=4729418, scope=2097151):
"""
OAuth on vk.com.
:param login: login on vk.com.
:param password: password on vk.com.
:param app_id: vk.com application id (default: 4729418).
:param scope: allowed actions (default: 2097151 (all)).
:returns: OAuth2 access token ... |
create a block from array like objects The operation is well defined only if array is at most 2d. | def create_from_array(self, blockname, array, Nfile=None, memorylimit=1024 * 1024 * 256):
""" create a block from array like objects
The operation is well defined only if array is at most 2d.
Parameters
----------
array : array_like,
array shall h... |
Refresh the list of blocks to the disk collectively | def refresh(self):
""" Refresh the list of blocks to the disk, collectively """
if self.comm.rank == 0:
self._blocks = self.list_blocks()
else:
self._blocks = None
self._blocks = self.comm.bcast(self._blocks) |
create a block from array like objects The operation is well defined only if array is at most 2d. | def create_from_array(self, blockname, array, Nfile=None, memorylimit=1024 * 1024 * 256):
""" create a block from array like objects
The operation is well defined only if array is at most 2d.
Parameters
----------
array : array_like,
array shall h... |
If value is a string type attempts to convert it to a boolean if it looks like it might be one otherwise returns the value unchanged. The difference between this and: func: pyramid. settings. asbool is how non - bools are handled: this returns the original value whereas asbool returns False. | def maybebool(value):
'''
If `value` is a string type, attempts to convert it to a boolean
if it looks like it might be one, otherwise returns the value
unchanged. The difference between this and
:func:`pyramid.settings.asbool` is how non-bools are handled: this
returns the original value, where... |
This function will take all webassets. * parameters and call the Environment () constructor with kwargs passed in. | def get_webassets_env_from_settings(settings, prefix='webassets'):
"""This function will take all webassets.* parameters, and
call the ``Environment()`` constructor with kwargs passed in.
The only two parameters that are not passed as keywords are:
* base_dir
* base_url
which are passed in po... |
Function for converting a dict to an array suitable for sklearn. | def format_data(self, data, scale=True):
"""
Function for converting a dict to an array suitable for sklearn.
Parameters
----------
data : dict
A dict of data, containing all elements of
`analytes` as items.
scale : bool
Whether or not... |
Function to format data for cluster fitting. | def fitting_data(self, data):
"""
Function to format data for cluster fitting.
Parameters
----------
data : dict
A dict of data, containing all elements of
`analytes` as items.
Returns
-------
A data array for initial cluster fitt... |
Fit KMeans clustering algorithm to data. | def fit_kmeans(self, data, n_clusters, **kwargs):
"""
Fit KMeans clustering algorithm to data.
Parameters
----------
data : array-like
A dataset formatted by `classifier.fitting_data`.
n_clusters : int
The number of clusters in the data.
*... |
Fit MeanShift clustering algorithm to data. | def fit_meanshift(self, data, bandwidth=None, bin_seeding=False, **kwargs):
"""
Fit MeanShift clustering algorithm to data.
Parameters
----------
data : array-like
A dataset formatted by `classifier.fitting_data`.
bandwidth : float
The bandwidth v... |
fit classifiers from large dataset. | def fit(self, data, method='kmeans', **kwargs):
"""
fit classifiers from large dataset.
Parameters
----------
data : dict
A dict of data for clustering. Must contain
items with the same name as analytes used for
clustering.
method : st... |
Label new data with cluster identities. | def predict(self, data):
"""
Label new data with cluster identities.
Parameters
----------
data : dict
A data dict containing the same analytes used to
fit the classifier.
sort_by : str
The name of an analyte used to sort the resulting... |
Translate cluster identity back to original data size. | def map_clusters(self, size, sampled, clusters):
"""
Translate cluster identity back to original data size.
Parameters
----------
size : int
size of original dataset
sampled : array-like
integer array describing location of finite values
... |
Sort clusters by the concentration of a particular analyte. | def sort_clusters(self, data, cs, sort_by):
"""
Sort clusters by the concentration of a particular analyte.
Parameters
----------
data : dict
A dataset containing sort_by as a key.
cs : array-like
An array of clusters, the same length as values of... |
Return a datetime oject from a string with optional time format. | def get_date(datetime, time_format=None):
"""
Return a datetime oject from a string, with optional time format.
Parameters
----------
datetime : str
Date-time as string in any sensible format.
time_format : datetime str (optional)
String describing the datetime format. If missin... |
Returns the total number of data points in values of dict. | def get_total_n_points(d):
"""
Returns the total number of data points in values of dict.
Paramters
---------
d : dict
"""
n = 0
for di in d.values():
n += len(di)
return n |
Returns total length of analysis. | def get_total_time_span(d):
"""
Returns total length of analysis.
"""
tmax = 0
for di in d.values():
if di.uTime.max() > tmax:
tmax = di.uTime.max()
return tmax |
Determines the most appropriate plotting unit for data. | def unitpicker(a, llim=0.1, denominator=None, focus_stage=None):
"""
Determines the most appropriate plotting unit for data.
Parameters
----------
a : float or array-like
number to optimise. If array like, the 25% quantile is optimised.
llim : float
minimum allowable value in sc... |
Returns formatted element name. | def pretty_element(s):
"""
Returns formatted element name.
Parameters
----------
s : str
of format [A-Z][a-z]?[0-9]+
Returns
-------
str
LaTeX formatted string with superscript numbers.
"""
el = re.match('.*?([A-z]{1,3}).*?', s).groups()[0]
m = re.match('.*?... |
Converts analytes in format 27Al to Al27. | def analyte_2_namemass(s):
"""
Converts analytes in format '27Al' to 'Al27'.
Parameters
----------
s : str
of format [A-z]{1,3}[0-9]{1,3}
Returns
-------
str
Name in format [0-9]{1,3}[A-z]{1,3}
"""
el = re.match('.*?([A-z]{1,3}).*?', s).groups()[0]
m = re.ma... |
Converts analytes in format Al27 to 27Al. | def analyte_2_massname(s):
"""
Converts analytes in format 'Al27' to '27Al'.
Parameters
----------
s : str
of format [0-9]{1,3}[A-z]{1,3}
Returns
-------
str
Name in format [A-z]{1,3}[0-9]{1,3}
"""
el = re.match('.*?([A-z]{1,3}).*?', s).groups()[0]
m = re.ma... |
Copy all csvs in nested directroy to single directory. | def collate_data(in_dir, extension='.csv', out_dir=None):
"""
Copy all csvs in nested directroy to single directory.
Function to copy all csvs from a directory, and place
them in a new directory.
Parameters
----------
in_dir : str
Input directory containing csv files in subfolders
... |
Convert boolean array into a 2D array of ( start stop ) pairs. | def bool_2_indices(a):
"""
Convert boolean array into a 2D array of (start, stop) pairs.
"""
if any(a):
lims = []
lims.append(np.where(a[:-1] != a[1:])[0])
if a[0]:
lims.append([0])
if a[-1]:
lims.append([len(a) - 1])
lims = np.concatenate... |
Consecutively numbers contiguous booleans in array. | def enumerate_bool(bool_array, nstart=0):
"""
Consecutively numbers contiguous booleans in array.
i.e. a boolean sequence, and resulting numbering
T F T T T F T F F F T T F
0-1 1 1 - 2 ---3 3 -
where ' - '
Parameters
----------
bool_array : array_like
Array of booleans.
... |
Generate boolean array from list of limit tuples. | def tuples_2_bool(tuples, x):
"""
Generate boolean array from list of limit tuples.
Parameters
----------
tuples : array_like
[2, n] array of (start, end) values
x : array_like
x scale the tuples are mapped to
Returns
-------
array_like
boolean array, True w... |
Returns ( win len ( a )) rolling - window array of data. | def rolling_window(a, window, pad=None):
"""
Returns (win, len(a)) rolling - window array of data.
Parameters
----------
a : array_like
Array to calculate the rolling window of
window : int
Description of `window`.
pad : same as dtype(a)
Description of `pad`.
Re... |
Returns rolling - window smooth of a. | def fastsmooth(a, win=11):
"""
Returns rolling - window smooth of a.
Function to efficiently calculate the rolling mean of a numpy
array using 'stride_tricks' to split up a 1D array into an ndarray of
sub - sections of the original array, of dimensions [len(a) - win, win].
Parameters
-----... |
Returns rolling - window gradient of a. | def fastgrad(a, win=11):
"""
Returns rolling - window gradient of a.
Function to efficiently calculate the rolling gradient of a numpy
array using 'stride_tricks' to split up a 1D array into an ndarray of
sub - sections of the original array, of dimensions [len(a) - win, win].
Parameters
-... |
Calculate gradients of values in dat. Parameters ---------- x: array like Independent variable for items in dat. dat: dict { key: dependent_variable } pairs keys: str or array - like Which keys in dict to calculate the gradient of. win: int The side of the rolling window for gradient calculation | def calc_grads(x, dat, keys=None, win=5):
"""
Calculate gradients of values in dat.
Parameters
----------
x : array like
Independent variable for items in dat.
dat : dict
{key: dependent_variable} pairs
keys : str or array-like
Which keys in dict to calculate the... |
Function to find local minima. | def findmins(x, y):
""" Function to find local minima.
Parameters
----------
x, y : array_like
1D arrays of the independent (x) and dependent (y) variables.
Returns
-------
array_like
Array of points in x where y has a local minimum.
"""
return x[np.r_[False, y[1:] ... |
Combine elements of ddict into an array of shape ( len ( ddict [ key ] ) len ( keys )). | def stack_keys(ddict, keys, extra=None):
"""
Combine elements of ddict into an array of shape (len(ddict[key]), len(keys)).
Useful for preparing data for sklearn.
Parameters
----------
ddict : dict
A dict containing arrays or lists to be stacked.
Must be of equal length.
ke... |
Identify clusters using Meanshift algorithm. | def cluster_meanshift(data, bandwidth=None, bin_seeding=False, **kwargs):
"""
Identify clusters using Meanshift algorithm.
Parameters
----------
data : array_like
array of size [n_samples, n_features].
bandwidth : float or None
If None, bandwidth is estimated automatically using... |
Identify clusters using K - Means algorithm. | def cluster_kmeans(data, n_clusters, **kwargs):
"""
Identify clusters using K - Means algorithm.
Parameters
----------
data : array_like
array of size [n_samples, n_features].
n_clusters : int
The number of clusters expected in the data.
Returns
-------
dict
... |
Identify clusters using DBSCAN algorithm. | def cluster_DBSCAN(data, eps=None, min_samples=None,
n_clusters=None, maxiter=200, **kwargs):
"""
Identify clusters using DBSCAN algorithm.
Parameters
----------
data : array_like
array of size [n_samples, n_features].
eps : float
The minimum 'distance' points... |
Returns list of SRMS defined in the SRM database | def get_defined_srms(srm_file):
"""
Returns list of SRMS defined in the SRM database
"""
srms = read_table(srm_file)
return np.asanyarray(srms.index.unique()) |
Read LAtools configuration file and return parameters as dict. | def read_configuration(config='DEFAULT'):
"""
Read LAtools configuration file, and return parameters as dict.
"""
# read configuration file
_, conf = read_latoolscfg()
# if 'DEFAULT', check which is the default configuration
if config == 'DEFAULT':
config = conf['DEFAULT']['config']
... |
Reads configuration returns a ConfigParser object. | def read_latoolscfg():
"""
Reads configuration, returns a ConfigParser object.
Distinct from read_configuration, which returns a dict.
"""
config_file = pkgrs.resource_filename('latools', 'latools.cfg')
cf = configparser.ConfigParser()
cf.read(config_file)
return config_file, cf |
Prints all currently defined configurations. | def print_all():
"""
Prints all currently defined configurations.
"""
# read configuration file
_, conf = read_latoolscfg()
default = conf['DEFAULT']['config']
pstr = '\nCurrently defined LAtools configurations:\n\n'
for s in conf.sections():
if s == default:
pstr +... |
Creates a copy of the default SRM table at the specified location. | def copy_SRM_file(destination=None, config='DEFAULT'):
"""
Creates a copy of the default SRM table at the specified location.
Parameters
----------
destination : str
The save location for the SRM file. If no location specified,
saves it as 'LAtools_[config]_SRMTable.csv' in the cur... |
Adds a new configuration to latools. cfg. | def create(config_name, srmfile=None, dataformat=None, base_on='DEFAULT', make_default=False):
"""
Adds a new configuration to latools.cfg.
Parameters
----------
config_name : str
The name of the new configuration. This should be descriptive
(e.g. UC Davis Foram Group)
srmfile :... |
Change the default configuration. | def change_default(config):
"""
Change the default configuration.
"""
config_file, cf = read_latoolscfg()
if config not in cf.sections():
raise ValueError("\n'{:s}' is not a defined configuration.".format(config))
if config == 'REPRODUCE':
pstr = ('Are you SURE you want to set ... |
Return boolean arrays where a > = and < threshold. | def threshold(values, threshold):
"""
Return boolean arrays where a >= and < threshold.
Parameters
----------
values : array-like
Array of real values.
threshold : float
Threshold value
Returns
-------
(below, above) : tuple or boolean arrays
"""
values ... |
Exclude all data after the first excluded portion. | def exclude_downhole(filt, threshold=2):
"""
Exclude all data after the first excluded portion.
This makes sense for spot measurements where, because
of the signal mixing inherent in LA-ICPMS, once a
contaminant is ablated, it will always be present to
some degree in signals from further down t... |
Defragment a filter. | def defrag(filt, threshold=3, mode='include'):
"""
'Defragment' a filter.
Parameters
----------
filt : boolean array
A filter
threshold : int
Consecutive values equal to or below this threshold
length are considered fragments, and will be removed.
mode : str
... |
Remove points from the start and end of True regions. Parameters ---------- start end: int The number of points to remove from the start and end of the specified filter. ind: boolean array Which filter to trim. If True applies to currently active filters. | def trim(ind, start=1, end=0):
"""
Remove points from the start and end of True regions.
Parameters
----------
start, end : int
The number of points to remove from the start and end of
the specified filter.
ind : boolean array
Which filter to trim. If True, applies t... |
Set the focus attribute of the data file. | def setfocus(self, focus):
"""
Set the 'focus' attribute of the data file.
The 'focus' attribute of the object points towards data from a
particular stage of analysis. It is used to identify the 'working
stage' of the data. Processing functions operate on the 'focus'
sta... |
Applies expdecay_despiker and noise_despiker to data. | def despike(self, expdecay_despiker=True, exponent=None,
noise_despiker=True, win=3, nlim=12., maxiter=3):
"""
Applies expdecay_despiker and noise_despiker to data.
Parameters
----------
expdecay_despiker : bool
Whether or not to apply the exponential... |
Automatically separates signal and background data regions. | def autorange(self, analyte='total_counts', gwin=5, swin=3, win=30,
on_mult=[1., 1.], off_mult=[1., 1.5],
ploterrs=True, transform='log', **kwargs):
"""
Automatically separates signal and background data regions.
Automatically detect signal and background reg... |
Plot a detailed autorange report for this sample. | def autorange_plot(self, analyte='total_counts', gwin=7, swin=None, win=20,
on_mult=[1.5, 1.], off_mult=[1., 1.5],
transform='log'):
"""
Plot a detailed autorange report for this sample.
"""
if analyte is None:
# sig = self.focus[... |
Transform boolean arrays into list of limit pairs. | def mkrngs(self):
"""
Transform boolean arrays into list of limit pairs.
Gets Time limits of signal/background boolean arrays and stores them as
sigrng and bkgrng arrays. These arrays can be saved by 'save_ranges' in
the analyse object.
"""
bbool = bool_2_indices... |
Subtract provided background from signal ( focus stage ). | def bkg_subtract(self, analyte, bkg, ind=None, focus_stage='despiked'):
"""
Subtract provided background from signal (focus stage).
Results is saved in new 'bkgsub' focus stage
Returns
-------
None
"""
if 'bkgsub' not in self.data.keys():
sel... |
Correct spectral interference. | def correct_spectral_interference(self, target_analyte, source_analyte, f):
"""
Correct spectral interference.
Subtract interference counts from target_analyte, based on the
intensity of a source_analayte and a known fractional contribution (f).
Correction takes the form:
... |
Divide all analytes by a specified internal_standard analyte. | def ratio(self, internal_standard=None):
"""
Divide all analytes by a specified internal_standard analyte.
Parameters
----------
internal_standard : str
The analyte used as the internal_standard.
Returns
-------
None
"""
if in... |
Apply calibration to data. | def calibrate(self, calib_ps, analytes=None):
"""
Apply calibration to data.
The `calib_dict` must be calculated at the `analyse` level,
and passed to this calibrate function.
Parameters
----------
calib_dict : dict
A dict of calibration values to ap... |
Calculate sample statistics | def sample_stats(self, analytes=None, filt=True,
stat_fns={},
eachtrace=True):
"""
Calculate sample statistics
Returns samples, analytes, and arrays of statistics
of shape (samples, analytes). Statistics are calculated
from the 'focus' d... |
Function for calculating the ablation time for each ablation. | def ablation_times(self):
"""
Function for calculating the ablation time for each
ablation.
Returns
-------
dict of times for each ablation.
"""
ats = {}
for n in np.arange(self.n) + 1:
t = self.Time[self.ns == n]
ats[n... |
Apply threshold filter. | def filter_threshold(self, analyte, threshold):
"""
Apply threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'_above' keeps all the data above the... |
Apply gradient threshold filter. | def filter_gradient_threshold(self, analyte, win, threshold, recalc=True):
"""
Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'... |
Applies an n - dimensional clustering filter to the data. | def filter_clustering(self, analytes, filt=False, normalise=True,
method='meanshift', include_time=False,
sort=None, min_data=10, **kwargs):
"""
Applies an n - dimensional clustering filter to the data.
Available Clustering Algorithms
... |
Calculate local correlation between two analytes. | def calc_correlation(self, x_analyte, y_analyte, window=15, filt=True, recalc=True):
"""
Calculate local correlation between two analytes.
Parameters
----------
x_analyte, y_analyte : str
The names of the x and y analytes to correlate.
window : int, None
... |
Calculate correlation filter. | def filter_correlation(self, x_analyte, y_analyte, window=15,
r_threshold=0.9, p_threshold=0.05, filt=True, recalc=False):
"""
Calculate correlation filter.
Parameters
----------
x_analyte, y_analyte : str
The names of the x and y analytes ... |
Plot the local correlation between two analytes. | def correlation_plot(self, x_analyte, y_analyte, window=15, filt=True, recalc=False):
"""
Plot the local correlation between two analytes.
Parameters
----------
x_analyte, y_analyte : str
The names of the x and y analytes to correlate.
window : int, None
... |
Make new filter from combination of other filters. | def filter_new(self, name, filt_str):
"""
Make new filter from combination of other filters.
Parameters
----------
name : str
The name of the new filter. Should be unique.
filt_str : str
A logical combination of partial strings which will create
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.