code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not item.remote_id:
command = CreateFolderCommand(self.settings, item, parent)
self.task_runner_add(parent, item, command) | def visit_folder(self, item, parent) | Adds create folder command to task runner if folder doesn't already exist. | 11.434208 | 5.93142 | 1.927735 |
if item.need_to_send:
if item.size > self.settings.config.upload_bytes_per_chunk:
msg = "Programmer Error: Trying to upload large file as small item size:{} name:{}"
raise ValueError(msg.format(item.size, item.name))
else:
command ... | def visit_file(self, item, parent) | If file is small add create small file command otherwise raise error.
Large files shouldn't be passed to SmallItemUploadTaskBuilder. | 8.293347 | 5.93576 | 1.397184 |
parent_task_id = self.item_to_id.get(parent)
task_id = self.task_runner.add(parent_task_id, command)
self.item_to_id[item] = task_id | def task_runner_add(self, parent, item, command) | Add command to task runner with parent's task id createing a task id for item/command.
Save this item's id to a lookup.
:param parent: object: parent of item
:param item: object: item we are running command on
:param command: parallel TaskCommand we want to have run | 2.586552 | 2.587302 | 0.99971 |
self.local_project.set_remote_id_after_send(result_id)
self.settings.project_id = result_id | def after_run(self, result_id) | Save uuid associated with project we just created.
:param result_id: str: uuid of the project | 11.757857 | 10.224874 | 1.149927 |
params = (self.remote_folder.name, self.parent.kind, self.parent.remote_id)
return UploadContext(self.settings, params, message_queue, task_id) | def create_context(self, message_queue, task_id) | Create values to be used by upload_folder_run function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly | 9.122855 | 9.183779 | 0.993366 |
parent_data = ParentData(self.parent.kind, self.parent.remote_id)
path_data = self.local_file.get_path_data()
params = parent_data, path_data, self.local_file.remote_id
return UploadContext(self.settings, params, message_queue, task_id) | def create_context(self, message_queue, task_id) | Create values to be used by create_small_file function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly | 5.906877 | 6.456899 | 0.914816 |
if self.file_upload_post_processor:
self.file_upload_post_processor.run(self.settings.data_service, remote_file_data)
remote_file_id = remote_file_data['id']
self.settings.watcher.transferring_item(self.local_file)
self.local_file.set_remote_id_after_send(remote_file... | def after_run(self, remote_file_data) | Save uuid of file to our LocalFile
:param remote_file_data: dict: DukeDS file data | 4.922233 | 5.026586 | 0.97924 |
watcher = self.settings.watcher
if started_waiting:
watcher.start_waiting()
else:
watcher.done_waiting() | def on_message(self, started_waiting) | Receives started_waiting boolean from create_small_file method and notifies project_status_monitor in settings.
:param started_waiting: boolean: True when we start waiting, False when done | 6.122044 | 4.97033 | 1.231718 |
if item.kind == KindType.file_str:
if item.need_to_send:
self.add_upload_item(item.path)
else:
if item.kind == KindType.project_str:
pass
else:
if not item.remote_id:
self.add_upload_item(ite... | def _visit_recur(self, item) | Recursively visits children of item.
:param item: object: project, folder or file we will add to upload_items if necessary. | 4.497927 | 3.491784 | 1.288146 |
arg_parser.add_argument("-p", '--project-name',
metavar='ProjectName',
type=to_unicode,
dest='project_name',
help=help_text,
required=required) | def add_project_name_arg(arg_parser, required, help_text) | Adds project_name parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str label displayed in usage | 3.145506 | 3.864977 | 0.813849 |
project_name_or_id = arg_parser.add_mutually_exclusive_group(required=required)
name_help_text = "Name of the project to {}.".format(help_text_suffix)
add_project_name_arg(project_name_or_id, required=False, help_text=name_help_text)
id_help_text = "ID of the project to {}.".format(help_text_suffix... | def add_project_name_or_id_arg(arg_parser, required=True, help_text_suffix="manage") | Adds project name or project id argument. These two are mutually exclusive.
:param arg_parser:
:param required:
:param help_text:
:return: | 1.568463 | 1.678134 | 0.934647 |
path = to_unicode(path)
if not os.path.exists(path):
raise argparse.ArgumentTypeError("{} is not a valid file/folder.".format(path))
return path | def _paths_must_exists(path) | Raises error if path doesn't exist.
:param path: str path to check
:return: str same path passed in | 3.598315 | 4.631256 | 0.776963 |
basename = os.path.basename(path)
if any([bad_char in basename for bad_char in INVALID_PATH_CHARS]):
raise argparse.ArgumentTypeError("{} contains invalid characters for a directory.".format(path))
return path | def _path_has_ok_chars(path) | Validate path for invalid characters.
:param path: str possible filesystem path
:return: path if it was ok otherwise raises error | 4.355134 | 4.335999 | 1.004413 |
help_text = "Specifies which project permissions to give to the user. Example: 'project_admin'. "
help_text += "See command list_auth_roles for AuthRole values."
arg_parser.add_argument("--auth-role",
metavar='AuthRole',
type=to_unicode,
... | def _add_auth_role_arg(arg_parser, default_permissions) | Adds optional auth_role parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param default_permissions: default value to use for this argument | 5.261264 | 5.510284 | 0.954808 |
help_text = "Filters project listing to just those projects with the specified role. "
help_text += "See command list_auth_roles for AuthRole values."
arg_parser.add_argument("--auth-role",
metavar='AuthRole',
type=to_unicode,
... | def _add_project_filter_auth_role_arg(arg_parser) | Adds optional auth_role filtering parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to. | 5.434571 | 5.468652 | 0.993768 |
arg_parser.add_argument("--resend",
action='store_true',
default=False,
dest='resend',
help=resend_help) | def _add_resend_arg(arg_parser, resend_help) | Adds resend parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param type_str | 2.047161 | 2.889515 | 0.708479 |
arg_parser.add_argument("--include",
metavar='Path',
action='append',
type=to_unicode,
dest='include_paths',
help="Specifies a single path to include. This argument can be... | def _add_include_arg(arg_parser) | Adds optional repeatable include parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to. | 4.49608 | 4.836937 | 0.92953 |
arg_parser.add_argument('--msg-file',
type=argparse.FileType('r'),
help=help_text) | def _add_message_file(arg_parser, help_text) | Add mesage file argument with help_text to arg_parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str: help text for this argument | 2.647993 | 3.314391 | 0.798938 |
description = "Uploads local files and folders to a remote host."
upload_parser = self.subparsers.add_parser('upload', description=description)
_add_dry_run(upload_parser, help_text="Instead of uploading displays a list of folders/files that "
... | def register_upload_command(self, upload_func) | Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks). | 4.667688 | 4.304213 | 1.084446 |
description = "Gives user permission to access a remote project."
add_user_parser = self.subparsers.add_parser('add-user', description=description)
add_project_name_or_id_arg(add_user_parser, help_text_suffix="add a user to")
user_or_email = add_user_parser.add_mutually_exclusiv... | def register_add_user_command(self, add_user_func) | Add the add-user command to the parser and call add_user_func(project_name, user_full_name, auth_role)
when chosen.
:param add_user_func: func Called when this option is chosen: upload_func(project_name, user_full_name, auth_role). | 3.507749 | 3.453743 | 1.015637 |
description = "Removes user permission to access a remote project."
remove_user_parser = self.subparsers.add_parser('remove-user', description=description)
add_project_name_or_id_arg(remove_user_parser, help_text_suffix="remove a user from")
user_or_email = remove_user_parser.ad... | def register_remove_user_command(self, remove_user_func) | Add the remove-user command to the parser and call remove_user_func(project_name, user_full_name) when chosen.
:param remove_user_func: func Called when this option is chosen: remove_user_func(project_name, user_full_name). | 3.04007 | 3.076084 | 0.988292 |
description = "Download the contents of a remote remote project to a local folder."
download_parser = self.subparsers.add_parser('download', description=description)
add_project_name_or_id_arg(download_parser, help_text_suffix="download")
_add_folder_positional_arg(download_pars... | def register_download_command(self, download_func) | Add 'download' command for downloading a project to a directory.
For non empty directories it will download remote files replacing local files.
:param download_func: function to run when user choses this option | 3.22727 | 3.351289 | 0.962994 |
description = "Share a project with another user with specified permissions. " \
"Sends the other user an email message via D4S2 service. " \
"If not specified this command gives user download permissions."
share_parser = self.subparsers.add_parser('... | def register_share_command(self, share_func) | Add 'share' command for adding view only project permissions and sending email via another service.
:param share_func: function to run when user choses this option | 4.99213 | 5.119139 | 0.975189 |
description = "Initiate delivery of a project to another user. Removes other user's current permissions. " \
"Send message to D4S2 service to send email and allow access to the project once user " \
"acknowledges receiving the data."
deliver_parser = ... | def register_deliver_command(self, deliver_func) | Add 'deliver' command for transferring a project to another user.,
:param deliver_func: function to run when user choses this option | 3.825361 | 3.781087 | 1.011709 |
description = "Show a list of project names or folders/files of a single project."
list_parser = self.subparsers.add_parser('list', description=description)
project_name_or_auth_role = list_parser.add_mutually_exclusive_group(required=False)
_add_project_filter_auth_role_arg(pro... | def register_list_command(self, list_func) | Add 'list' command to get a list of projects or details about one project.
:param list_func: function: run when user choses this option. | 4.320748 | 4.229531 | 1.021567 |
description = "Permanently delete a project."
delete_parser = self.subparsers.add_parser('delete', description=description)
add_project_name_or_id_arg(delete_parser, help_text_suffix="delete")
_add_force_arg(delete_parser, "Do not prompt before deleting.")
delete_parser.... | def register_delete_command(self, delete_func) | Add 'delete' command delete a project from the remote store.
:param delete_func: function: run when user choses this option. | 3.978061 | 4.435707 | 0.896827 |
description = "List authorization roles for use with add_user command."
list_auth_roles_parser = self.subparsers.add_parser('list-auth-roles', description=description)
list_auth_roles_parser.set_defaults(func=list_auth_roles_func) | def register_list_auth_roles_command(self, list_auth_roles_func) | Add 'list_auth_roles' command to list project authorization roles that can be used with add_user.
:param list_auth_roles_func: function: run when user choses this option. | 2.994609 | 2.616744 | 1.144403 |
parsed_args = self.parser.parse_args(args)
if hasattr(parsed_args, 'func'):
parsed_args.func(parsed_args)
else:
self.parser.print_help() | def run_command(self, args) | Parse command line arguments and run function registered for the appropriate command.
:param args: [str] command line arguments | 2.043918 | 2.231087 | 0.916109 |
df_resampled = data_frame.resample(str(1 / self.sampling_frequency) + 'S').mean()
f = interpolate.interp1d(data_frame.td, data_frame.mag_sum_acc)
new_timestamp = np.arange(data_frame.td[0], data_frame.td[-1], 1.0 / self.sampling_frequency)
df_resampled.mag_sum_acc = f(new_times... | def resample_signal(self, data_frame) | Convenience method for frequency conversion and resampling of data frame.
Object must have a DatetimeIndex. After re-sampling, this methods interpolate the time magnitude sum
acceleration values and the x,y,z values of the data frame acceleration
:param data_frame: the data frame ... | 3.445341 | 3.070565 | 1.122054 |
b, a = signal.butter(self.filter_order, 2*self.cutoff_frequency/self.sampling_frequency,'high', analog=False)
filtered_signal = signal.lfilter(b, a, data_frame[ts].values)
data_frame['filtered_signal'] = filtered_signal
logging.debug("filter signal")
return data_frame | def filter_signal(self, data_frame, ts='mag_sum_acc') | This method filters a data frame signal as suggested in :cite:`Kassavetis2015`. First step is to high \
pass filter the data frame using a \
`Butterworth <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.butter.html>`_ \
digital and analog filter. Then this me... | 3.26129 | 3.157382 | 1.032909 |
signal_length = len(data_frame.filtered_signal.values)
ll = int(signal_length / 2 - self.window / 2)
rr = int(signal_length / 2 + self.window / 2)
msa = data_frame.filtered_signal[ll:rr].values
hann_window = signal.hann(self.window)
msa_window = (msa * hann_wind... | def fft_signal(self, data_frame) | This method perform Fast Fourier Transform on the data frame using a \
`hanning window <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.hann.html>`_
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return: data frame with a '... | 3.057011 | 2.781974 | 1.098864 |
signal_length = len(data_frame.filtered_signal)
normalised_transformed_signal = data_frame.transformed_signal.values / signal_length
k = np.arange(signal_length)
T = signal_length / self.sampling_frequency
f = k / T # two sides frequency range
f = f[range(int(... | def amplitude_by_fft(self, data_frame) | This methods extract the fft components and sum the ones from lower to upper freq as per \
:cite:`Kassavetis2015`
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return ampl: the ampl
:rtype ampl: float
:return freq: the freq... | 4.226589 | 3.997726 | 1.057248 |
frq, Pxx_den = signal.welch(data_frame.filtered_signal.values, self.sampling_frequency, nperseg=self.window)
freq = frq[Pxx_den.argmax(axis=0)]
ampl = sum(Pxx_den[(frq > self.lower_frequency) & (frq < self.upper_frequency)])
logging.debug("tremor amplitude by welch calculated")... | def amplitude_by_welch(self, data_frame) | This methods uses the Welch method :cite:`Welch1967` to obtain the power spectral density, this is a robust
alternative to using fft_signal & amplitude
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return: the ampl
:rtype ampl: float
... | 3.830013 | 3.953614 | 0.968737 |
if m is None or r is None:
m = 2
r = 0.3
entropy = feature_calculators.approximate_entropy(x, m, r)
logging.debug("approximate entropy by tsfresh calculated")
return entropy | def approximate_entropy(self, x, m=None, r=None) | As in tsfresh \
`approximate_entropy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1601>`_
Implements a `vectorized approximate entropy algorithm <https://en.wikipedia.org/wiki/Approximate_entropy>`_
For short time-series this ... | 6.397137 | 4.647955 | 1.376333 |
# This is important: If a series is passed, the product below is calculated
# based on the index, which corresponds to squaring the series.
if lag is None:
lag = 0
_autoc = feature_calculators.autocorrelation(x, lag)
logging.debug("autocorrelation by tsfresh ... | def autocorrelation(self, x, lag) | As in tsfresh `autocorrelation <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1457>`_
Calculates the autocorrelation of the specified lag, according to the `formula <https://en.wikipedia.org/wiki/\
Autocorrelation#Estimation>`_:
... | 13.510376 | 12.021661 | 1.123836 |
if param is None:
param = [{'lag': 3}, {'lag': 5}, {'lag': 6}]
_partialc = feature_calculators.partial_autocorrelation(x, param)
logging.debug("partial autocorrelation by tsfresh calculated")
return _partialc | def partial_autocorrelation(self, x, param=None) | As in tsfresh `partial_autocorrelation <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/\
feature_extraction/feature_calculators.py#L308>`_
Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial \
autocorrelation of a time series :math:`\\l... | 6.914414 | 4.949216 | 1.397073 |
ratio = feature_calculators.ratio_value_number_to_time_series_length(x)
logging.debug("ratio value number to time series length by tsfresh calculated")
return ratio | def ratio_value_number_to_time_series_length(self, x) | As in tsfresh `ratio_value_number_to_time_series_length <https://github.com/blue-yonder/tsfresh/blob/master\
/tsfresh/feature_extraction/feature_calculators.py#L830>`_
Returns a factor which is 1 if all values in the time series occur only once,
and below one if this is not the case... | 6.403706 | 5.191501 | 1.233498 |
if ql is None or qh is None or isabs is None or f_agg is None:
f_agg = 'mean'
isabs = True
qh = 0.2
ql = 0.0
quantile = feature_calculators.change_quantiles(x, ql, qh, isabs, f_agg)
logging.debug("change_quantiles by tsfresh calculated")
... | def change_quantiles(self, x, ql=None, qh=None, isabs=None, f_agg=None) | As in tsfresh `change_quantiles <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/\
feature_extraction/feature_calculators.py#L1248>`_
First fixes a corridor given by the quantiles ql and qh of the distribution of x. Then calculates the \
average, absolute value of consecu... | 3.514225 | 3.19037 | 1.10151 |
if n is None:
n = 5
peaks = feature_calculators.number_peaks(x, n)
logging.debug("agg linear trend by tsfresh calculated")
return peaks | def number_peaks(self, x, n=None) | As in tsfresh `number_peaks <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1003>`_
Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined \
as a subsequence of x ... | 12.337322 | 10.850812 | 1.136995 |
if param is None:
param = [{'attr': 'intercept', 'chunk_len': 5, 'f_agg': 'min'},
{'attr': 'rvalue', 'chunk_len': 10, 'f_agg': 'var'},
{'attr': 'intercept', 'chunk_len': 10, 'f_agg': 'min'}]
agg = feature_calculators.agg_linear_trend(x, para... | def agg_linear_trend(self, x, param=None) | As in tsfresh `agg_inear_trend <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/\
feature_extraction/feature_calculators.py#L1727>`_
Calculates a linear least-squares regression for values of the time series that were aggregated over chunks\
versus the sequenc... | 4.724027 | 2.980234 | 1.58512 |
if param is None:
param = [{'coeff': 2}, {'coeff': 5}, {'coeff': 8}]
welch = feature_calculators.spkt_welch_density(x, param)
logging.debug("spkt welch density by tsfresh calculated")
return list(welch) | def spkt_welch_density(self, x, param=None) | As in tsfresh `spkt_welch_density <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/\
feature_extraction/feature_calculators.py#L1162>`_ . This feature calculator estimates the cross power \
spectral density of the time series x at different frequencies. To do so, the time series is fi... | 6.012042 | 4.49764 | 1.33671 |
_perc = feature_calculators.percentage_of_reoccurring_datapoints_to_all_datapoints(x)
logging.debug("percentage of reoccurring datapoints to all datapoints by tsfresh calculated")
return _perc | def percentage_of_reoccurring_datapoints_to_all_datapoints(self, x) | As in tsfresh `percentage_of_reoccurring_datapoints_to_all_datapoints <https://github.com/blue-yonder/tsfresh/\
blob/master/tsfresh/feature_extraction/feature_calculators.py#L739>`_ \
Returns the percentage of unique values, that are present in the time series more than once.\
len(different val... | 4.775628 | 3.904019 | 1.223259 |
_energy = feature_calculators.abs_energy(x)
logging.debug("abs energy by tsfresh calculated")
return _energy | def abs_energy(self, x) | As in tsfresh `abs_energy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L390>`_ \
Returns the absolute energy of the time series which is the sum over the squared values\
.. math::
E=\\sum_{i=1,\ldots, n}x_... | 15.587068 | 10.105529 | 1.54243 |
if param is None:
param = [{'aggtype': 'centroid'}]
_fft_agg = feature_calculators.fft_aggregated(x, param)
logging.debug("fft aggregated by tsfresh calculated")
return list(_fft_agg) | def fft_aggregated(self, x, param=None) | As in tsfresh `fft_aggregated <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L896>`_
Returns the spectral centroid (mean), variance, skew, and kurtosis of the absolute fourier transform spectrum.
:param x: the time series to calc... | 10.117872 | 5.02744 | 2.01253 |
if param is None:
param = [{'attr': 'abs', 'coeff': 44}, {'attr': 'abs', 'coeff': 63}, {'attr': 'abs', 'coeff': 0},
{'attr': 'real', 'coeff': 0}, {'attr': 'real', 'coeff': 23}]
_fft_coef = feature_calculators.fft_coefficient(x, param)
logging.debug("fft ... | def fft_coefficient(self, x, param=None) | As in tsfresh `fft_coefficient <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L852>`_ \
Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast \
fourier transformation algorithm
... | 4.849985 | 3.556871 | 1.363554 |
mean_signal = np.mean(data_frame.mag_sum_acc)
data_frame['dc_mag_sum_acc'] = data_frame.mag_sum_acc - mean_signal
logging.debug("dc remove signal")
return data_frame | def dc_remove_signal(self, data_frame) | Removes the dc component of the signal as per :cite:`Kassavetis2015`
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return: the data frame with dc remove signal field
:rtype: pandas.DataFrame | 5.212075 | 4.98391 | 1.04578 |
try:
data_frame_resampled = self.resample_signal(data_frame)
data_frame_dc = self.dc_remove_signal(data_frame_resampled)
data_frame_filtered = self.filter_signal(data_frame_dc, 'dc_mag_sum_acc')
if method == 'fft':
data_frame_fft = self.f... | def bradykinesia(self, data_frame, method='fft') | This method calculates the bradykinesia amplitude of the data frame. It accepts two different methods, \
'fft' and 'welch'. First the signal gets re-sampled, dc removed and then high pass filtered.
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:par... | 3.378204 | 3.043365 | 1.110022 |
if reactor is None:
from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.internet import reactor
try:
AWSStatusIndicator(reactor)
gobject.set_application_name("aws-status")
reactor.run()
except ValueError:
# In this case, th... | def main(argv, reactor=None) | Run the client GUI.
Typical use:
>>> sys.exit(main(sys.argv))
@param argv: The arguments to run it with, e.g. sys.argv.
@param reactor: The reactor to use. Must be compatible with gtk as this
module uses gtk API"s.
@return exitcode: The exit code it returned, as per sys.exit. | 5.49265 | 5.98361 | 0.917949 |
arguments = arguments[1:]
options = {}
while arguments:
key = arguments.pop(0)
if key in ("-h", "--help"):
raise UsageError("Help requested.")
if key.startswith("--"):
key = key[2:]
try:
value = arguments.pop(0)
exc... | def parse_options(arguments) | Parse command line arguments.
The parsing logic is fairly simple. It can only parse long-style
parameters of the form::
--key value
Several parameters can be defined in the environment and will be used
unless explicitly overridden with command-line arguments. The access key,
secret and en... | 2.019266 | 1.857287 | 1.087213 |
options = parse_options(arguments)
key = options.pop("key")
secret = options.pop("secret")
endpoint = options.pop("endpoint")
action = options.pop("action")
return Command(key, secret, endpoint, action, options, output) | def get_command(arguments, output=None) | Parse C{arguments} and configure a L{Command} instance.
An access key, secret key, endpoint and action are required. Additional
parameters included with the request are passed as parameters to the
method call. For example, the following command will create a L{Command}
object that can invoke the C{De... | 2.967813 | 2.764548 | 1.073526 |
def run_command(arguments, output, reactor):
if output is None:
output = sys.stdout
try:
command = get_command(arguments, output)
except UsageError:
print >>output, USAGE_MESSAGE.strip()
if reactor:
reactor.callLater(0, re... | def main(arguments, output=None, testing_mode=None) | Entry point parses command-line arguments, runs the specified EC2 API
method and prints the response to the screen.
@param arguments: Command-line arguments, typically retrieved from
C{sys.argv}.
@param output: Optionally, a stream to write output to.
@param testing_mode: Optionally, a conditio... | 2.296082 | 2.297863 | 0.999225 |
# determine the number of values to forecast, if necessary
self._calculate_values_to_forecast(timeSeries)
# extract the required parameters, performance improvement
alpha = self._parameters["smoothingFactor"]
valuesToForecast = self._parameters["valuesToForec... | def execute(self, timeSeries) | Creates a new TimeSeries containing the smoothed and forcasted values.
:return: TimeSeries object containing the smoothed TimeSeries,
including the forecasted values.
:rtype: TimeSeries
:note: The first normalized value is chosen as the starting point. | 5.190341 | 5.04413 | 1.028986 |
parameterIntervals = {}
parameterIntervals["smoothingFactor"] = [0.0, 1.0, False, False]
parameterIntervals["trendSmoothingFactor"] = [0.0, 1.0, False, False]
return parameterIntervals | def _get_parameter_intervals(self) | Returns the intervals for the methods parameter.
Only parameters with defined intervals can be used for optimization!
:return: Returns a dictionary containing the parameter intervals, using the parameter
name as key, while the value hast the following format:
[minValue, maxV... | 4.95958 | 4.589976 | 1.080524 |
# determine the number of values to forecast, if necessary
self._calculate_values_to_forecast(timeSeries)
# extract the required parameters, performance improvement
alpha = self._parameters["smoothingFactor"]
beta = self._parameters["trendSmoothin... | def execute(self, timeSeries) | Creates a new TimeSeries containing the smoothed values.
:return: TimeSeries object containing the smoothed TimeSeries,
including the forecasted values.
:rtype: TimeSeries
:note: The first normalized value is chosen as the starting point. | 4.789913 | 4.691844 | 1.020902 |
# determine the number of values to forecast, if necessary
self._calculate_values_to_forecast(timeSeries)
seasonLength = self.get_parameter("seasonLength")
if len(timeSeries) < seasonLength:
raise ValueError("The time series must contain at least one full season.")
... | def execute(self, timeSeries) | Creates a new TimeSeries containing the smoothed values.
:param TimeSeries timeSeries: TimeSeries containing hte data.
:return: TimeSeries object containing the exponentially smoothed TimeSeries,
including the forecasted values.
:rtype: TimeSeries
:note: Currently t... | 3.402178 | 3.333516 | 1.020597 |
forecastResults = []
lastEstimator, lastSeasonValue, lastTrend = lastSmoothingParams
seasonLength = self.get_parameter("seasonLength")
#Forecasting. Determine the time difference between two points for extrapolation
currentTime = smoothedData[-1][0]
nor... | def _calculate_forecast(self, originalTimeSeries, smoothedData, seasonValues, lastSmoothingParams) | Calculates the actual forecasted based on the input data.
:param TimeSeries timeSeries: TimeSeries containing hte data.
:param list smoothedData: Contains the smoothed time series data.
:param list seasonValues: Contains the seasonal values for the forecast.
:param list lastSmoothingPar... | 5.639249 | 5.315431 | 1.06092 |
seasonLength = self.get_parameter("seasonLength")
try:
seasonValues = self.get_parameter("seasonValues")
assert seasonLength == len(seasonValues), "Preset Season Values have to have to be of season's length"
return seasonValues
except KeyError:
... | def initSeasonFactors(self, timeSeries) | Computes the initial season smoothing factors.
:return: Returns a list of season vectors of length "seasonLength".
:rtype: list | 5.567059 | 5.336959 | 1.043114 |
result = 0.0
seasonLength = self.get_parameter("seasonLength")
k = min(len(timeSeries) - seasonLength, seasonLength) #In case of only one full season, use average trend of the months that we have twice
for i in xrange(0, k):
result += (timeSeries[seasonLength + i][1... | def initialTrendSmoothingFactors(self, timeSeries) | Calculate the initial Trend smoothing Factor b0.
Explanation:
http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing
:return: Returns the initial trend smoothing factor b0 | 6.301237 | 6.796232 | 0.927166 |
seasonLength = self.get_parameter("seasonLength")
A_j = 0
for i in range(seasonLength):
A_j += timeSeries[(seasonLength * (j)) + i][1]
return A_j / seasonLength | def computeA(self, j, timeSeries) | Calculates A_j. Aj is the average value of x in the jth cycle of your data
:return: A_j
:rtype: numeric | 4.735283 | 4.337131 | 1.091801 |
quoted = False
escaped = False
result = []
for i, ch in enumerate(text):
if escaped:
escaped = False
result.append(ch)
elif ch == u'\\':
escaped = True
elif ch == u'"':
quoted = not quoted
elif not quoted and ch == u' '... | def _split_quoted(text) | Split a unicode string on *SPACE* characters.
Splitting is not done at *SPACE* characters occurring within matched
*QUOTATION MARK*s. *REVERSE SOLIDUS* can be used to remove all
interpretation from the following character.
:param unicode text: The string to split.
:return: A two-tuple of unicode... | 2.055853 | 2.429122 | 0.846336 |
data = self.resample_signal(x).values
f_res = self.sampling_frequency / self.window
f_nr_LBs = int(self.loco_band[0] / f_res)
f_nr_LBe = int(self.loco_band[1] / f_res)
f_nr_FBs = int(self.freeze_band[0] / f_res)
f_nr_FBe = int(self.freeze_band[1] / f_res)
... | def freeze_of_gait(self, x) | This method assess freeze of gait following :cite:`g-BachlinPRMHGT10`.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:return freeze_time: What times do freeze of gait events occur. [measured in time (h:m:s)]
... | 2.934465 | 2.601249 | 1.128099 |
peaks_data = x[start_offset: -end_offset].values
maxtab, mintab = peakdet(peaks_data, self.delta)
x = np.mean(peaks_data[maxtab[1:,0].astype(int)] - peaks_data[maxtab[:-1,0].astype(int)])
frequency_of_peaks = abs(1/x)
return frequency_of_peaks | def frequency_of_peaks(self, x, start_offset=100, end_offset=100) | This method assess the frequency of the peaks on any given 1-dimensional time series.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:param start_offset: Signal to leave out (of calculations) from the begining of t... | 4.401056 | 4.462593 | 0.986211 |
coeffs = wavedec(x.values, wavelet=wavelet_type, level=wavelet_level)
energy = [sum(coeffs[wavelet_level - i]**2) / len(coeffs[wavelet_level - i]) for i in range(wavelet_level)]
WEd1 = energy[0] / (5 * np.sqrt(2))
WEd2 = energy[1] / (4 * np.sqrt(2))
WEd3 = energy[2] /... | def speed_of_gait(self, x, wavelet_type='db3', wavelet_level=6) | This method assess the speed of gait following :cite:`g-MartinSB11`.
It extracts the gait speed from the energies of the approximation coefficients of wavelet functions.
Prefferably you should use the magnitude of x, y and z (mag_acc_sum) here, as the time series.
:param x: The tim... | 2.125065 | 2.064397 | 1.029388 |
def _symmetry(v):
maxtab, _ = peakdet(v, self.delta)
return maxtab[1][1], maxtab[2][1]
step_regularity_x, stride_regularity_x = _symmetry(autocorrelation(data_frame.x))
step_regularity_y, stride_regularity_y = _symmetry(autocorrelation(data_frame.y))
... | def walk_regularity_symmetry(self, data_frame) | This method extracts the step and stride regularity and also walk symmetry.
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame: pandas.DataFrame
:return step_regularity: Regularity of steps on [x, y, z] coordinates, defined as the consistency of ... | 1.986672 | 1.757337 | 1.130502 |
# Sum of absolute values across accelerometer axes:
data = data_frame.x.abs() + data_frame.y.abs() + data_frame.z.abs()
# Find maximum peaks of smoothed data:
dummy, ipeaks_smooth = self.heel_strikes(data)
data = data.values
# Compute number of samples between... | def walk_direction_preheel(self, data_frame) | Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame:... | 3.923506 | 3.857703 | 1.017058 |
# Demean data:
data = x.values
data -= data.mean()
# TODO: fix this
# Low-pass filter the AP accelerometer data by the 4th order zero lag
# Butterworth filter whose cut frequency is set to 5 Hz:
filtered = butter_lowpass_filter(data, self.sa... | def heel_strikes(self, x) | Estimate heel strike times between sign changes in accelerometer data.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:return strikes: Heel strike timings measured in seconds.
:rtype striles: numpy.ndar... | 5.095108 | 5.019917 | 1.014978 |
if (average_step_duration=='autodetect') or (average_stride_duration=='autodetect'):
strikes, _ = self.heel_strikes(x)
step_durations = []
for i in range(1, np.size(strikes)):
step_durations.append(strikes[i] - strikes[i-1])
average_ste... | def gait_regularity_symmetry(self, x, average_step_duration='autodetect', average_stride_duration='autodetect', unbias=1, normalize=2) | Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:param average_step_duration: Average duration of each step... | 1.927635 | 1.863248 | 1.034556 |
sections = [[]]
mask = data_frame[labels_col].apply(lambda x: x in labels_to_keep)
for i,m in enumerate(mask):
if m:
sections[-1].append(i)
if not m and len(sections[-1]) > min_labels_in_sequence:
section... | def separate_into_sections(self, data_frame, labels_col='anno', labels_to_keep=[1,2], min_labels_in_sequence=100) | Helper function to separate a time series into multiple sections based on a labeled column.
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame: pandas.DataFrame
:param labels_col: The column which has the labels we would like to separate ... | 2.562747 | 3.415124 | 0.750411 |
peaks, prominences = get_signal_peaks_and_prominences(x)
bellman_idx = BellmanKSegment(prominences, states)
return peaks, prominences, bellman_idx | def bellman_segmentation(self, x, states) | Divide a univariate time-series, data_frame, into states contiguous segments, using Bellman k-segmentation algorithm on the peak prominences of the data.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:para... | 5.854547 | 3.477288 | 1.683653 |
peaks, prominences = get_signal_peaks_and_prominences(x)
# sklearn fix: reshape to (-1, 1)
sklearn_idx = cluster_fn.fit_predict(prominences.reshape(-1, 1))
return peaks, prominences, sklearn_idx | def sklearn_segmentation(self, x, cluster_fn) | Divide a univariate time-series, data_frame, into states contiguous segments, using sk-learn clustering algorithms on the peak prominences of the data.
:param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc.
:type x: pandas.Series
:param ... | 5.613963 | 4.447876 | 1.262167 |
# add some checks to see if dictionary is in the right format!
data_frame['segmentation'] = 'unknown'
for i, (k, v) in enumerate(segmentation_dictionary.items()):
for start, end in v:
if type(start) != np.datetime64:... | def add_manual_segmentation_to_data_frame(self, data_frame, segmentation_dictionary) | Utility method to store manual segmentation of gait time series.
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame: pandas.DataFrame
:param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_... | 3.401221 | 3.202485 | 1.062057 |
data = x
fig, ax = plt.subplots()
fig.set_size_inches(figsize[0], figsize[1])
# fix this!!
colors = 'bgrcmykwbgrcmykwbgrcmykw'
data.plot(ax=ax)
for i, (k, v) in enumerate(segmentation_dictionary.items()):
for start, end in v:
... | def plot_segmentation_dictionary(self, x, segmentation_dictionary, figsize=(10, 5)) | Utility method used to visualize how the segmentation dictionary interacts with the time series.
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame: pandas.DataFrame
:param segmentation_dictionary: A dictionary of the form {'signal_type': [(from,... | 2.597811 | 2.607108 | 0.996434 |
# fix this!!
colors = 'bgrcmykwbgrcmykwbgrcmykw'
keys = np.unique(segmented_data_frame['segmentation'])
fig, ax = plt.subplots()
fig.set_size_inches(figsize[0], figsize[1])
segmented_data_frame[axis].plot(ax=ax)
for i, k in enu... | def plot_segmentation_data_frame(self, segmented_data_frame, axis='mag_sum_acc', figsize=(10, 5)) | Utility method used to visualize how the segmentation dictionary interacts with the time series.
:param segmented_data_frame: The segmented data frame. It should have x, y, z and segmentation columns.
:type segmented_data_frame: pandas.DataFrame
:param axis: The axis which we want t... | 2.760817 | 2.794313 | 0.988013 |
http_status = 0
if error.check(TwistedWebError):
xml_payload = error.value.response
if error.value.status:
http_status = int(error.value.status)
else:
error.raiseException()
if http_status >= 400:
if not xml_payload:
error.raiseException()
... | def error_wrapper(error, errorClass) | We want to see all error messages from cloud services. Amazon's EC2 says
that their errors are accompanied either by a 400-series or 500-series HTTP
response code. As such, the first thing we want to do is check to see if
the error is in that range. If it is, we then need to see if the error
message is ... | 3.274962 | 3.100614 | 1.05623 |
return b'/' + b'/'.join(seg.encode('utf-8') for seg in ctx.path) | def _get_joined_path(ctx) | @type ctx: L{_URLContext}
@param ctx: A URL context.
@return: The path component, un-urlencoded, but joined by slashes.
@rtype: L{bytes} | 7.369969 | 7.431968 | 0.991658 |
contextFactory = None
scheme, host, port, path = parse(url)
data = kwds.get('postdata', None)
self._method = method = kwds.get('method', 'GET')
self.request_headers = self._headers(kwds.get('headers', {}))
if (self.body_producer is None) and (data is not None):
... | def get_page(self, url, *args, **kwds) | Define our own get_page method so that we can easily override the
factory when we need to. This was copied from the following:
* twisted.web.client.getPage
* twisted.web.client._makeGetterFactory | 3.73959 | 3.333441 | 1.121841 |
return Headers(dict((k,[v]) for (k,v) in headers_dict.items())) | def _headers(self, headers_dict) | Convert dictionary of headers into twisted.web.client.Headers object. | 6.706185 | 4.200034 | 1.596698 |
return dict((k,v[0]) for (k,v) in headers.getAllRawHeaders()) | def _unpack_headers(self, headers) | Unpack twisted.web.client.Headers object to dict. This is to provide
backwards compatability. | 5.467134 | 3.133498 | 1.744738 |
if self.request_headers:
return self._unpack_headers(self.request_headers) | def get_request_headers(self, *args, **kwds) | A convenience method for obtaining the headers that were sent to the
S3 server.
The AWS S3 API depends upon setting headers. This method is provided as
a convenience for debugging issues with the S3 communications. | 5.440435 | 6.48714 | 0.838649 |
self.client.status = response.code
self.response_headers = response.headers
# XXX This workaround (which needs to be improved at that) for possible
# bug in Twisted with new client:
# http://twistedmatrix.com/trac/ticket/5476
if self._method.upper() == 'HEAD' or ... | def _handle_response(self, response) | Handle the HTTP response by memoing the headers and then delivering
bytes. | 6.246725 | 5.894888 | 1.059685 |
if self.response_headers:
return self._unpack_headers(self.response_headers) | def get_response_headers(self, *args, **kwargs) | A convenience method for obtaining the headers that were sent from the
S3 server.
The AWS S3 API depends upon setting headers. This method is used by the
head_object API call for getting a S3 object's metadata. | 5.743883 | 6.777877 | 0.847446 |
assert secret, "Missing secret key"
assert client_id, "Missing client id"
headers = {
"typ": __type__,
"alg": __algorithm__
}
claims = {
'iss': client_id,
'iat': epoch_seconds()
}
return jwt.encode(payload=claims, key=secret, headers=headers).decode() | def create_jwt_token(secret, client_id) | Create JWT token for GOV.UK Notify
Tokens have standard header:
{
"typ": "JWT",
"alg": "HS256"
}
Claims consist of:
iss: identifier for the client
iat: issued at in epoch seconds (UTC)
:param secret: Application signing secret
:param client_id: Identifier for the clien... | 3.342669 | 3.284168 | 1.017813 |
try:
unverified = decode_token(token)
if 'iss' not in unverified:
raise TokenIssuerError
return unverified.get('iss')
except jwt.DecodeError:
raise TokenDecodeError | def get_token_issuer(token) | Issuer of a token is the identifier used to recover the secret
Need to extract this from token to ensure we can proceed to the signature validation stage
Does not check validity of the token
:param token: signed JWT token
:return issuer: iss field of the JWT token
:raises TokenIssuerError: if iss fi... | 4.316354 | 3.715554 | 1.161698 |
try:
# check signature of the token
decoded_token = jwt.decode(
token,
key=secret.encode(),
verify=True,
algorithms=[__algorithm__],
leeway=__bound__
)
# token has all the required fields
if 'iss' not in decoded... | def decode_jwt_token(token, secret) | Validates and decodes the JWT token
Token checked for
- signature of JWT token
- token issued date is valid
:param token: jwt token
:param secret: client specific secret
:return boolean: True if valid token, False otherwise
:raises TokenIssuerError: if iss field not present
:rai... | 3.3895 | 2.982731 | 1.136375 |
if in_superblank:
if char == ']':
in_superblank = False
text_buffer += char
elif char == '\\':
text_buffer += char
text_buffer += next(stream)
else:
text_buffer += char
elif in_lexical_uni... | def parse(stream, with_text=False): # type: (Iterator[str], bool) -> Iterator[Union[Tuple[str, LexicalUnit], LexicalUnit]]
buffer = ''
text_buffer = ''
in_lexical_unit = False
in_superblank = False
for char in stream | Generates lexical units from a character stream.
Args:
stream (Iterator[str]): A character stream containing lexical units, superblanks and other text.
with_text (Optional[bool]): A boolean defining whether to output preceding text with each lexical unit.
Yields:
:class:`LexicalUnit`: ... | 1.902536 | 1.809991 | 1.05113 |
try:
datafile = file(datafilepath, "wb")
except Exception:
return False
if self._timestampFormat is None:
self._timestampFormat = _STR_EPOCHS
datafile.write("# time_as_<%s> value\n" % self._timestampFormat)
convert = TimeSeries.conv... | def to_gnuplot_datafile(self, datafilepath) | Dumps the TimeSeries into a gnuplot compatible data file.
:param string datafilepath: Path used to create the file. If that file already exists,
it will be overwritten!
:return: Returns :py:const:`True` if the data could be written, :py:const:`False` otherwise.
:rtype: bool... | 4.031081 | 3.936671 | 1.023982 |
# create and fill the given TimeSeries
ts = TimeSeries()
ts.set_timeformat(tsformat)
for entry in datalist:
ts.add_entry(*entry[:2])
# set the normalization level
ts._normalized = ts.is_normalized()
ts.sort_timeseries()
return ts | def from_twodim_list(cls, datalist, tsformat=None) | Creates a new TimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefined format,
the second represents the value. All othe... | 7.613647 | 8.080458 | 0.94223 |
# initialize the result
tuples = 0
# add the SQL result to the time series
data = sqlcursor.fetchmany()
while 0 < len(data):
for entry in data:
self.add_entry(str(entry[0]), entry[1])
data = sqlcursor.fetchmany()
# set t... | def initialize_from_sql_cursor(self, sqlcursor) | Initializes the TimeSeries's data from the given SQL cursor.
You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`.
:param SQLCursor sqlcursor: Cursor that was holds the SQL result for any given
"SELECT timestamp, value, ... FROM ..." SQL query.
On... | 6.451953 | 5.760233 | 1.120085 |
return time.mktime(time.strptime(timestamp, tsformat)) | def convert_timestamp_to_epoch(cls, timestamp, tsformat) | Converts the given timestamp into a float representing UNIX-epochs.
:param string timestamp: Timestamp in the defined format.
:param string tsformat: Format of the given timestamp. This is used to convert the
timestamp into UNIX epochs. For valid examples take a look into
the... | 4.057193 | 6.1393 | 0.660856 |
return time.strftime(tsformat, time.gmtime(timestamp)) | def convert_epoch_to_timestamp(cls, timestamp, tsformat) | Converts the given float representing UNIX-epochs into an actual timestamp.
:param float timestamp: Timestamp as UNIX-epochs.
:param string tsformat: Format of the given timestamp. This is used to convert the
timestamp from UNIX epochs. For valid examples take a look into the
... | 4.352735 | 5.947947 | 0.731805 |
self._normalized = self._predefinedNormalized
self._sorted = self._predefinedSorted
tsformat = self._timestampFormat
if tsformat is not None:
timestamp = TimeSeries.convert_timestamp_to_epoch(timestamp, tsformat)
self._timeseriesData.append([float(times... | def add_entry(self, timestamp, data) | Adds a new data entry to the TimeSeries.
:param timestamp: Time stamp of the data.
This has either to be a float representing the UNIX epochs
or a string containing a timestamp in the given format.
:param numeric data: Actual data value. | 7.676253 | 7.012821 | 1.094603 |
# the time series is sorted by default
if ascending and self._sorted:
return
sortorder = 1
if not ascending:
sortorder = -1
self._predefinedSorted = False
self._timeseriesData.sort(key=lambda i: sortorder * i[0])
self._sorte... | def sort_timeseries(self, ascending=True) | Sorts the data points within the TimeSeries according to their occurrence inline.
:param boolean ascending: Determines if the TimeSeries will be ordered ascending or
descending. If this is set to descending once, the ordered parameter defined in
:py:meth:`TimeSeries.__init__` will be se... | 5.820385 | 6.341153 | 0.917875 |
sortorder = 1
if not ascending:
sortorder = -1
data = sorted(self._timeseriesData, key=lambda i: sortorder * i[0])
newTS = TimeSeries(self._normalized)
for entry in data:
newTS.add_entry(*entry)
newTS._sorted = ascending
return... | def sorted_timeseries(self, ascending=True) | Returns a sorted copy of the TimeSeries, preserving the original one.
As an assumption this new TimeSeries is not ordered anymore if a new value is added.
:param boolean ascending: Determines if the TimeSeries will be ordered ascending
or descending.
:return: Returns a new T... | 4.795316 | 5.92647 | 0.809135 |
# do not normalize the TimeSeries if it is already normalized, either by
# definition or a prior call of normalize(*)
if self._normalizationLevel == normalizationLevel:
if self._normalized: # pragma: no cover
return
# check if all parameters are d... | def normalize(self, normalizationLevel="minute", fusionMethod="mean", interpolationMethod="linear") | Normalizes the TimeSeries data points.
If this function is called, the TimeSeries gets ordered ascending
automatically. The new timestamps will represent the center of each time
bucket. Within a normalized TimeSeries, the temporal distance between two consecutive data points is constant.
... | 3.394744 | 3.347258 | 1.014187 |
lastDistance = None
distance = None
for idx in xrange(len(self) - 1):
distance = self[idx+1][0] - self[idx][0]
# first run
if lastDistance is None:
lastDistance = distance
continue
if lastDistance != d... | def _check_normalization(self) | Checks, if the TimeSeries is normalized.
:return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal
distance, :py:const:`False` otherwise. | 3.793853 | 3.683921 | 1.029841 |
# check, if the methods requirements are fullfilled
if method.has_to_be_normalized() and not self._normalized:
raise StandardError("method requires a normalized TimeSeries instance.")
if method.has_to_be_sorted():
self.sort_timeseries()
return method.ex... | def apply(self, method) | Applies the given ForecastingAlgorithm or SmoothingMethod from the :py:mod:`pycast.methods`
module to the TimeSeries.
:param BaseMethod method: Method that should be used with the TimeSeries.
For more information about the methods take a look into their corresponding documentation.
... | 7.817977 | 5.506098 | 1.419876 |
if not (0.0 < percentage < 1.0):
raise ValueError("Parameter percentage has to be in (0.0, 1.0).")
cls = self.__class__
value_count = int(len(self) * percentage)
values = random.sample(self, value_count)
sample = cls.from_twodim_list(value... | def sample(self, percentage) | Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries.
The original timeseries is not changed.
:param float percentage: How many percent of the original timeseries should be in the sample
:return: A tuple containing (sample, rest) as two TimeSeries.
... | 3.660134 | 2.894112 | 1.264683 |
if not isinstance(data, list):
data = [data]
if len(data) != self._dimensionCount:
raise ValueError("data does contain %s instead of %s dimensions.\n %s" % (len(data), self._dimensionCount, data))
self._normalized = self._predefinedNormalized
self._so... | def add_entry(self, timestamp, data) | Adds a new data entry to the TimeSeries.
:param timestamp: Time stamp of the data.
This has either to be a float representing the UNIX epochs
or a string containing a timestamp in the given format.
:param list data: A list containing the actual dimension values.
:... | 5.159081 | 4.480377 | 1.151484 |
if self._timestampFormat is None:
return self._timeseriesData
datalist = []
append = datalist.append
convert = TimeSeries.convert_epoch_to_timestamp
for entry in self._timeseriesData:
append([convert(entry[0], self._timestampFormat), entry[1:]... | def to_twodim_list(self) | Serializes the MultiDimensionalTimeSeries data into a two dimensional list of [timestamp, [values]] pairs.
:return: Returns a two dimensional list containing [timestamp, [values]] pairs.
:rtype: list | 5.61811 | 5.021433 | 1.118826 |
# create and fill the given TimeSeries
ts = MultiDimensionalTimeSeries(dimensions=dimensions)
ts.set_timeformat(tsformat)
for entry in datalist:
ts.add_entry(entry[0], entry[1])
# set the normalization level
ts._normalized = ts.is_normalized()
... | def from_twodim_list(cls, datalist, tsformat=None, dimensions=1) | Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefined format,
the second is a list, con... | 5.859243 | 6.169972 | 0.949639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.