Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def TensorBoardWSGIApp(logdir, plugins, multiplexer, reload_interval,
path_prefix='', reload_task='auto'):
path_to_run = parse_event_files_spec(logdir)
if reload_interval >= 0:
# We either reload the multiplexer once when TensorBoard starts ... | [
"Constructs the TensorBoard application.\n\n Args:\n logdir: the logdir spec that describes where data will be loaded.\n may be a directory, or comma,separated list of directories, or colons\n can be used to provide named directories\n plugins: A list of base_plugin.TBPlugin subclass instances.\n ... |
Please provide a description of the function:def parse_event_files_spec(logdir):
files = {}
if logdir is None:
return files
# Make sure keeping consistent with ParseURI in core/lib/io/path.cc
uri_pattern = re.compile('[a-zA-Z][0-9a-zA-Z.]*://.*')
for specification in logdir.split(','):
# Check if t... | [
"Parses `logdir` into a map from paths to run group names.\n\n The events files flag format is a comma-separated list of path specifications.\n A path specification either looks like 'group_name:/path/to/directory' or\n '/path/to/directory'; in the latter case, the group is unnamed. Group names\n cannot start w... |
Please provide a description of the function:def start_reloading_multiplexer(multiplexer, path_to_run, load_interval,
reload_task):
if load_interval < 0:
raise ValueError('load_interval is negative: %d' % load_interval)
def _reload():
while True:
start = time.time()... | [
"Starts automatically reloading the given multiplexer.\n\n If `load_interval` is positive, the thread will reload the multiplexer\n by calling `ReloadMultiplexer` every `load_interval` seconds, starting\n immediately. Otherwise, reloads the multiplexer once and never again.\n\n Args:\n multiplexer: The `Even... |
Please provide a description of the function:def get_database_info(db_uri):
if not db_uri:
return None, None
scheme = urlparse.urlparse(db_uri).scheme
if scheme == 'sqlite':
return sqlite3, create_sqlite_connection_provider(db_uri)
else:
raise ValueError('Only sqlite DB URIs are supported now: ' ... | [
"Returns TBContext fields relating to SQL database.\n\n Args:\n db_uri: A string URI expressing the DB file, e.g. \"sqlite:~/tb.db\".\n\n Returns:\n A tuple with the db_module and db_connection_provider TBContext fields. If\n db_uri was empty, then (None, None) is returned.\n\n Raises:\n ValueError: ... |
Please provide a description of the function:def create_sqlite_connection_provider(db_uri):
uri = urlparse.urlparse(db_uri)
if uri.scheme != 'sqlite':
raise ValueError('Scheme is not sqlite: ' + db_uri)
if uri.netloc:
raise ValueError('Can not connect to SQLite over network: ' + db_uri)
if uri.path =... | [
"Returns function that returns SQLite Connection objects.\n\n Args:\n db_uri: A string URI expressing the DB file, e.g. \"sqlite:~/tb.db\".\n\n Returns:\n A function that returns a new PEP-249 DB Connection, which must be closed,\n each time it is called.\n\n Raises:\n ValueError: If db_uri is not a ... |
Please provide a description of the function:def _serve_plugins_listing(self, request):
response = {}
for plugin in self._plugins:
start = time.time()
response[plugin.plugin_name] = plugin.is_active()
elapsed = time.time() - start
logger.info(
'Plugin listing: is_active() ... | [
"Serves an object mapping plugin name to whether it is enabled.\n\n Args:\n request: The werkzeug.Request object.\n\n Returns:\n A werkzeug.Response object.\n "
] |
Please provide a description of the function:def parse_time_indices(s):
if not s.startswith('['):
s = '[' + s + ']'
parsed = command_parser._parse_slices(s)
if len(parsed) != 1:
raise ValueError(
'Invalid number of slicing objects in time indices (%d)' % len(parsed))
else:
return parsed[0... | [
"Parse a string as time indices.\n\n Args:\n s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10'\n\n Returns:\n A slice object.\n\n Raises:\n ValueError: If `s` does not represent valid time indices.\n "
] |
Please provide a description of the function:def process_buffers_for_display(s, limit=40):
if isinstance(s, (list, tuple)):
return [process_buffers_for_display(elem, limit=limit) for elem in s]
else:
length = len(s)
if length > limit:
return (binascii.b2a_qp(s[:limit]) +
b' (lengt... | [
"Process a buffer for human-readable display.\n\n This function performs the following operation on each of the buffers in `s`.\n 1. Truncate input buffer if the length of the buffer is greater than\n `limit`, to prevent large strings from overloading the frontend.\n 2. Apply `binascii.b2a_qp` on the t... |
Please provide a description of the function:def array_view(array, slicing=None, mapping=None):
dtype = translate_dtype(array.dtype)
sliced_array = (array[command_parser._parse_slices(slicing)] if slicing
else array)
if np.isscalar(sliced_array) and str(dtype) == 'string':
# When a stri... | [
"View a slice or the entirety of an ndarray.\n\n Args:\n array: The input array, as an numpy.ndarray.\n slicing: Optional slicing string, e.g., \"[:, 1:3, :]\".\n mapping: Optional mapping string. Supported mappings:\n `None` or case-insensitive `'None'`: Unmapped nested list.\n `'image/png'`: I... |
Please provide a description of the function:def array_to_base64_png(array):
# TODO(cais): Deal with 3D case.
# TODO(cais): If there are None values in here, replace them with all NaNs.
array = np.array(array, dtype=np.float32)
if len(array.shape) != 2:
raise ValueError(
"Expected rank-2 array; r... | [
"Convert an array into base64-enoded PNG image.\n\n Args:\n array: A 2D np.ndarray or nested list of items.\n\n Returns:\n A base64-encoded string the image. The image is grayscale if the array is\n 2D. The image is RGB color if the image is 3D with lsat dimension equal to\n 3.\n\n Raises:\n Value... |
Please provide a description of the function:def _safe_copy_proto_list_values(dst_proto_list, src_proto_list, get_key):
def _assert_proto_container_unique_keys(proto_list, get_key):
keys = set()
for item in proto_list:
key = get_key(item)
if key in keys:
raise _ProtoListDuplicateK... | [
"Safely merge values from `src_proto_list` into `dst_proto_list`.\n\n Each element in `dst_proto_list` must be mapped by `get_key` to a key\n value that is unique within that list; likewise for `src_proto_list`.\n If an element of `src_proto_list` has the same key as an existing\n element in `dst_proto_list`, t... |
Please provide a description of the function:def combine_graph_defs(to_proto, from_proto):
if from_proto.version != to_proto.version:
raise ValueError('Cannot combine GraphDefs of different versions.')
try:
_safe_copy_proto_list_values(
to_proto.node,
from_proto.node,
lambda n: n... | [
"Combines two GraphDefs by adding nodes from from_proto into to_proto.\n\n All GraphDefs are expected to be of TensorBoard's.\n It assumes node names are unique across GraphDefs if contents differ. The\n names can be the same if the NodeDef content are exactly the same.\n\n Args:\n to_proto: A destination Te... |
Please provide a description of the function:def scalar(name, data, step=None, description=None):
summary_metadata = metadata.create_summary_metadata(
display_name=None, description=description)
# TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback
summary_scope = (
getattr... | [
"Write a scalar summary.\n\n Arguments:\n name: A name for this summary. The summary tag used for TensorBoard will\n be this name prefixed by any active name scopes.\n data: A real numeric scalar value, convertible to a `float32` Tensor.\n step: Explicit `int64`-castable monotonic step value for this... |
Please provide a description of the function:def scalar_pb(tag, data, description=None):
arr = np.array(data)
if arr.shape != ():
raise ValueError('Expected scalar shape for tensor, got shape: %s.'
% arr.shape)
if arr.dtype.kind not in ('b', 'i', 'u', 'f'): # bool, int, uint, float
... | [
"Create a scalar summary_pb2.Summary protobuf.\n\n Arguments:\n tag: String tag for the summary.\n data: A 0-dimensional `np.array` or a compatible python number type.\n description: Optional long-form description for this summary, as a\n `str`. Markdown is supported. Defaults to empty.\n\n Raises:\... |
Please provide a description of the function:def dump_data(logdir):
# Create a tfevents file in the logdir so it is detected as a run.
write_empty_event_file(logdir)
plugin_logdir = plugin_asset_util.PluginDirectory(
logdir, profile_plugin.ProfilePlugin.plugin_name)
_maybe_create_directory(plugin_logd... | [
"Dumps plugin data to the log directory."
] |
Please provide a description of the function:def calc_health_pill(tensor):
health_pill = [0.0] * 14
# TODO(cais): Add unit test for this method that compares results with
# DebugNumericSummary output.
# Is tensor initialized.
if not isinstance(tensor, np.ndarray):
return health_pill
health_pill[0... | [
"Calculate health pill of a tensor.\n\n Args:\n tensor: An instance of `np.array` (for initialized tensors) or\n `tensorflow.python.debug.lib.debug_data.InconvertibleTensorProto`\n (for unininitialized tensors).\n\n Returns:\n If `tensor` is an initialized tensor of numeric or boolean types:\n ... |
Please provide a description of the function:def _get_config(self):
'''Reads the config file from disk or creates a new one.'''
filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME)
modified_time = os.path.getmtime(filename)
if modified_time != self.config_last_modified_time:
config = re... | [] |
Please provide a description of the function:def _write_summary(self, session, frame):
'''Writes the frame to disk as a tensor summary.'''
summary = session.run(self.summary_op, feed_dict={
self.frame_placeholder: frame
})
path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME)
write_fil... | [] |
Please provide a description of the function:def _enough_time_has_passed(self, FPS):
'''For limiting how often frames are computed.'''
if FPS == 0:
return False
else:
earliest_time = self.last_update_time + (1.0 / FPS)
return time.time() >= earliest_time | [] |
Please provide a description of the function:def _update_recording(self, frame, config):
'''Adds a frame to the current video output.'''
# pylint: disable=redefined-variable-type
should_record = config['is_recording']
if should_record:
if not self.is_recording:
self.is_recording = True
... | [] |
Please provide a description of the function:def update(self, session, arrays=None, frame=None):
'''Creates a frame and writes it to disk.
Args:
arrays: a list of np arrays. Use the "custom" option in the client.
frame: a 2D np array. This way the plugin can be used for video of any
ki... | [] |
Please provide a description of the function:def gradient_helper(optimizer, loss, var_list=None):
'''A helper to get the gradients out at each step.
Args:
optimizer: the optimizer op.
loss: the op that computes your loss value.
Returns: the gradient tensors and the train_step op.
'''
i... | [] |
Please provide a description of the function:def _create_key_func(extractor, none_is_largest):
if none_is_largest:
def key_func_none_is_largest(session_group):
value = extractor(session_group)
return (value is None, value)
return key_func_none_is_largest
def key_func_none_is_smallest(session_... | [
"Returns a key_func to be used in list.sort().\n\n Returns a key_func to be used in list.sort() that sorts session groups\n by the value extracted by extractor. 'None' extracted values will either\n be considered largest or smallest as specified by the \"none_is_largest\"\n boolean parameter.\n\n Args:\n ex... |
Please provide a description of the function:def _create_extractors(col_params):
result = []
for col_param in col_params:
result.append(_create_extractor(col_param))
return result | [
"Creates extractors to extract properties corresponding to 'col_params'.\n\n Args:\n col_params: List of ListSessionGroupsRequest.ColParam protobufs.\n Returns:\n A list of extractor functions. The ith element in the\n returned list extracts the column corresponding to the ith element of\n _request.co... |
Please provide a description of the function:def _create_metric_extractor(metric_name):
def extractor_fn(session_or_group):
metric_value = _find_metric_value(session_or_group,
metric_name)
return metric_value.value if metric_value else None
return extractor_fn | [
"Returns function that extracts a metric from a session group or a session.\n\n Args:\n metric_name: tensorboard.hparams.MetricName protobuffer. Identifies the\n metric to extract from the session group.\n Returns:\n A function that takes a tensorboard.hparams.SessionGroup or\n tensorborad.hparams.Ses... |
Please provide a description of the function:def _find_metric_value(session_or_group, metric_name):
# Note: We can speed this up by converting the metric_values field
# to a dictionary on initialization, to avoid a linear search here. We'll
# need to wrap the SessionGroup and Session protos in a python object ... | [
"Returns the metric_value for a given metric in a session or session group.\n\n Args:\n session_or_group: A Session protobuffer or SessionGroup protobuffer.\n metric_name: A MetricName protobuffer. The metric to search for.\n Returns:\n A MetricValue protobuffer representing the value of the given metric... |
Please provide a description of the function:def _create_hparam_extractor(hparam_name):
def extractor_fn(session_group):
if hparam_name in session_group.hparams:
return _value_to_python(session_group.hparams[hparam_name])
return None
return extractor_fn | [
"Returns an extractor function that extracts an hparam from a session group.\n\n Args:\n hparam_name: str. Identies the hparam to extract from the session group.\n Returns:\n A function that takes a tensorboard.hparams.SessionGroup protobuffer and\n returns the value, as a native Python object, of the hp... |
Please provide a description of the function:def _create_filters(col_params, extractors):
result = []
for col_param, extractor in zip(col_params, extractors):
a_filter = _create_filter(col_param, extractor)
if a_filter:
result.append(a_filter)
return result | [
"Creates filters for the given col_params.\n\n Args:\n col_params: List of ListSessionGroupsRequest.ColParam protobufs.\n extractors: list of extractor functions of the same length as col_params.\n Each element should extract the column described by the corresponding\n element of col_params.\n Ret... |
Please provide a description of the function:def _create_filter(col_param, extractor):
include_missing_values = not col_param.exclude_missing_values
if col_param.HasField('filter_regexp'):
value_filter_fn = _create_regexp_filter(col_param.filter_regexp)
elif col_param.HasField('filter_interval'):
value... | [
"Creates a filter for the given col_param and extractor.\n\n Args:\n col_param: A tensorboard.hparams.ColParams object identifying the column\n and describing the filter to apply.\n extractor: A function that extract the column value identified by\n 'col_param' from a tensorboard.hparams.SessionGro... |
Please provide a description of the function:def _create_regexp_filter(regex):
# Warning: Note that python's regex library allows inputs that take
# exponential time. Time-limiting it is difficult. When we move to
# a true multi-tenant tensorboard server, the regexp implementation here
# would need to be rep... | [
"Returns a boolean function that filters strings based on a regular exp.\n\n Args:\n regex: A string describing the regexp to use.\n Returns:\n A function taking a string and returns True if any of its substrings\n matches regex.\n "
] |
Please provide a description of the function:def _create_interval_filter(interval):
def filter_fn(value):
if (not isinstance(value, six.integer_types) and
not isinstance(value, float)):
raise error.HParamsError(
'Cannot use an interval filter for a value of type: %s, Value: %s' %
... | [
"Returns a function that checkes whether a number belongs to an interval.\n\n Args:\n interval: A tensorboard.hparams.Interval protobuf describing the interval.\n Returns:\n A function taking a number (a float or an object of a type in\n six.integer_types) that returns True if the number belongs to (the ... |
Please provide a description of the function:def _value_to_python(value):
assert isinstance(value, struct_pb2.Value)
field = value.WhichOneof('kind')
if field == 'number_value':
return value.number_value
elif field == 'string_value':
return value.string_value
elif field == 'bool_value':
return... | [
"Converts a google.protobuf.Value to a native Python object."
] |
Please provide a description of the function:def _set_avg_session_metrics(session_group):
assert session_group.sessions, 'SessionGroup cannot be empty.'
# Algorithm: Iterate over all (session, metric) pairs and maintain a
# dict from _MetricIdentifier to _MetricStats objects.
# Then use the final dict state ... | [
"Sets the metrics for the group to be the average of its sessions.\n\n The resulting session group metrics consist of the union of metrics across\n the group's sessions. The value of each session group metric is the average\n of that metric values across the sessions in the group. The 'step' and\n 'wall_time_se... |
Please provide a description of the function:def _set_median_session_metrics(session_group, aggregation_metric):
measurements = sorted(_measurements(session_group, aggregation_metric),
key=operator.attrgetter('metric_value.value'))
median_session = measurements[(len(measurements) - 1) // ... | [
"Sets the metrics for session_group to those of its \"median session\".\n\n The median session is the session in session_group with the median value\n of the metric given by 'aggregation_metric'. The median is taken over the\n subset of sessions in the group whose 'aggregation_metric' was measured\n at the larg... |
Please provide a description of the function:def _set_extremum_session_metrics(session_group, aggregation_metric,
extremum_fn):
measurements = _measurements(session_group, aggregation_metric)
ext_session = extremum_fn(
measurements,
key=operator.attrgetter('metric_va... | [
"Sets the metrics for session_group to those of its \"extremum session\".\n\n The extremum session is the session in session_group with the extremum value\n of the metric given by 'aggregation_metric'. The extremum is taken over the\n subset of sessions in the group whose 'aggregation_metric' was measured\n at ... |
Please provide a description of the function:def _measurements(session_group, metric_name):
for session_index, session in enumerate(session_group.sessions):
metric_value = _find_metric_value(session, metric_name)
if not metric_value:
continue
yield _Measurement(metric_value, session_index) | [
"A generator for the values of the metric across the sessions in the group.\n\n Args:\n session_group: A SessionGroup protobuffer.\n metric_name: A MetricName protobuffer.\n Yields:\n The next metric value wrapped in a _Measurement instance.\n "
] |
Please provide a description of the function:def run(self):
session_groups = self._build_session_groups()
session_groups = self._filter(session_groups)
self._sort(session_groups)
return self._create_response(session_groups) | [
"Handles the request specified on construction.\n\n Returns:\n A ListSessionGroupsResponse object.\n\n "
] |
Please provide a description of the function:def _build_session_groups(self):
# Algorithm: We keep a dict 'groups_by_name' mapping a SessionGroup name
# (str) to a SessionGroup protobuffer. We traverse the runs associated with
# the plugin--each representing a single session. We form a Session
# p... | [
"Returns a list of SessionGroups protobuffers from the summary data."
] |
Please provide a description of the function:def _add_session(self, session, start_info, groups_by_name):
# If the group_name is empty, this session's group contains only
# this session. Use the session name for the group name since session
# names are unique.
group_name = start_info.group_name or ... | [
"Adds a new Session protobuffer to the 'groups_by_name' dictionary.\n\n Called by _build_session_groups when we encounter a new session. Creates\n the Session protobuffer and adds it to the relevant group in the\n 'groups_by_name' dict. Creates the session group if this is the first time\n we encounter ... |
Please provide a description of the function:def _build_session(self, name, start_info, end_info):
assert start_info is not None
result = api_pb2.Session(
name=name,
start_time_secs=start_info.start_time_secs,
model_uri=start_info.model_uri,
metric_values=self._build_sessio... | [
"Builds a session object."
] |
Please provide a description of the function:def _build_session_metric_values(self, session_name):
# result is a list of api_pb2.MetricValue instances.
result = []
metric_infos = self._experiment.metric_infos
for metric_info in metric_infos:
metric_name = metric_info.name
try:
... | [
"Builds the session metric values."
] |
Please provide a description of the function:def _aggregate_metrics(self, session_group):
if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or
self._request.aggregation_type == api_pb2.AGGREGATION_UNSET):
_set_avg_session_metrics(session_group)
elif self._request.aggregation_type... | [
"Sets the metrics of the group based on aggregation_type."
] |
Please provide a description of the function:def _sort(self, session_groups):
# Sort by session_group name so we have a deterministic order.
session_groups.sort(key=operator.attrgetter('name'))
# Sort by lexicographical order of the _request.col_params whose order
# is not ORDER_UNSPECIFIED. The f... | [
"Sorts 'session_groups' in place according to _request.col_params."
] |
Please provide a description of the function:def recordAnalyzeAudio(duration, outputWavFile, midTermBufferSizeSec, modelName, modelType):
'''
recordAnalyzeAudio(duration, outputWavFile, midTermBufferSizeSec, modelName, modelType)
This function is used to record and analyze audio segments, in a fix window basis.
A... | [] |
Please provide a description of the function:def annotation2files(wavFile, csvFile):
'''
Break an audio stream to segments of interest,
defined by a csv file
- wavFile: path to input wavfile
- csvFile: path to csvFile of segment limits
Input CSV file ... | [] |
Please provide a description of the function:def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False):
'''
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used.
ARGUMENTS:
- dirNa... | [] |
Please provide a description of the function:def convertFsDirWavToWav(dirName, Fs, nC):
'''
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.
ARGUMENTS:
- dirName: the path of the folder where the WAVs are stored
- Fs: ... | [] |
Please provide a description of the function:def readAudioFile(path):
'''
This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
'''
extension = os.path.splitext(path)[1]
try:
#if extension.lower() == '.wav':
#[Fs, x] = wavfile.read(pat... | [] |
Please provide a description of the function:def stereo2mono(x):
'''
This function converts the input signal
(stored in a numpy array) to MONO (if it is STEREO)
'''
if isinstance(x, int):
return -1
if x.ndim==1:
return x
elif x.ndim==2:
if x.shape[1]==1:
r... | [] |
Please provide a description of the function:def selfSimilarityMatrix(featureVectors):
'''
This function computes the self-similarity matrix for a sequence
of feature vectors.
ARGUMENTS:
- featureVectors: a numpy matrix (nDims x nVectors) whose i-th column
corresponds... | [] |
Please provide a description of the function:def flags2segs(flags, window):
'''
ARGUMENTS:
- flags: a sequence of class flags (per time window)
- window: window duration (in seconds)
RETURNS:
- segs: a sequence of segment's limits: segs[i,0] is start and
seg... | [] |
Please provide a description of the function:def segs2flags(seg_start, seg_end, seg_label, win_size):
'''
This function converts segment endpoints and respective segment
labels to fix-sized class labels.
ARGUMENTS:
- seg_start: segment start points (in seconds)
- seg_end: segment endpoin... | [] |
Please provide a description of the function:def computePreRec(cm, class_names):
'''
This function computes the precision, recall and f1 measures,
given a confusion matrix
'''
n_classes = cm.shape[0]
if len(class_names) != n_classes:
print("Error in computePreRec! Confusion matrix and cl... | [] |
Please provide a description of the function:def readSegmentGT(gt_file):
'''
This function reads a segmentation ground truth file, following a simple CSV format with the following columns:
<segment start>,<segment end>,<class label>
ARGUMENTS:
- gt_file: the path of the CSV segment file
... | [] |
Please provide a description of the function:def plotSegmentationResults(flags_ind, flags_ind_gt, class_names, mt_step, ONLY_EVALUATE=False):
'''
This function plots statistics on the classification-segmentation results produced either by the fix-sized supervised method or the HMM method.
It also computes t... | [] |
Please provide a description of the function:def trainHMM_computeStatistics(features, labels):
'''
This function computes the statistics used to train an HMM joint segmentation-classification model
using a sequence of sequential features and respective labels
ARGUMENTS:
- features: a numpy matr... | [] |
Please provide a description of the function:def trainHMM_fromFile(wav_file, gt_file, hmm_model_name, mt_win, mt_step):
'''
This function trains a HMM model for segmentation-classification using a single annotated audio file
ARGUMENTS:
- wav_file: the path of the audio filename
- gt_file: ... | [] |
Please provide a description of the function:def trainHMM_fromDir(dirPath, hmm_model_name, mt_win, mt_step):
'''
This function trains a HMM model for segmentation-classification using
a where WAV files and .segment (ground-truth files) are stored
ARGUMENTS:
- dirPath: the path of the data di... | [] |
Please provide a description of the function:def mtFileClassification(input_file, model_name, model_type,
plot_results=False, gt_file=""):
'''
This function performs mid-term classification of an audio stream.
Towards this end, supervised knowledge is used, i.e. a pre-trained classi... | [] |
Please provide a description of the function:def silenceRemoval(x, fs, st_win, st_step, smoothWindow=0.5, weight=0.5, plot=False):
'''
Event Detection (silence removal)
ARGUMENTS:
- x: the input audio signal
- fs: sampling freq
- st_win, st_step: wi... | [] |
Please provide a description of the function:def speakerDiarization(filename, n_speakers, mt_size=2.0, mt_step=0.2,
st_win=0.05, lda_dim=35, plot_res=False):
'''
ARGUMENTS:
- filename: the name of the WAV file to be analyzed
- n_speakers the number of speakers (... | [] |
Please provide a description of the function:def speakerDiarizationEvaluateScript(folder_name, ldas):
'''
This function prints the cluster purity and speaker purity for
each WAV file stored in a provided directory (.SEGMENT files
are needed as ground-truth)
ARGUMENTS:
- ... | [] |
Please provide a description of the function:def musicThumbnailing(x, fs, short_term_size=1.0, short_term_step=0.5,
thumb_size=10.0, limit_1 = 0, limit_2 = 1):
'''
This function detects instances of the most representative part of a
music recording, also called "music thumbnails".
... | [] |
Please provide a description of the function:def generateColorMap():
'''
This function generates a 256 jet colormap of HTML-like
hex string colors (e.g. FF88AA)
'''
Map = cm.jet(np.arange(256))
stringColors = []
for i in range(Map.shape[0]):
rgb = (int(255*Map[i][0]), int(255*Map[i][... | [] |
Please provide a description of the function:def levenshtein(str1, s2):
'''
Distance between two strings
'''
N1 = len(str1)
N2 = len(s2)
stringRange = [range(N1 + 1)] * (N2 + 1)
for i in range(N2 + 1):
stringRange[i] = range(i,i + N1 + 1)
for i in range(0,N2):
for j in r... | [] |
Please provide a description of the function:def text_list_to_colors(names):
'''
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
'''
# STEP A: compute strings distance between all combnations of strings
Dnames = np.zeros( (len(names), len(... | [] |
Please provide a description of the function:def text_list_to_colors_simple(names):
'''
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
'''
uNames = list(set(names))
uNames.sort()
textToColor = [ uNames.index(n) for n in names ]
t... | [] |
Please provide a description of the function:def chordialDiagram(fileStr, SM, Threshold, names, namesCategories):
'''
Generates a d3js chordial diagram that illustrates similarites
'''
colors = text_list_to_colors_simple(namesCategories)
SM2 = SM.copy()
SM2 = (SM2 + SM2.T) / 2.0
for i in ran... | [] |
Please provide a description of the function:def visualizeFeaturesFolder(folder, dimReductionMethod, priorKnowledge = "none"):
'''
This function generates a chordial visualization for the recordings of the provided path.
ARGUMENTS:
- folder: path of the folder that contains the WAV files to b... | [] |
Please provide a description of the function:def stZCR(frame):
count = len(frame)
countZ = numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2
return (numpy.float64(countZ) / numpy.float64(count-1.0)) | [
"Computes zero crossing rate of frame"
] |
Please provide a description of the function:def stEnergyEntropy(frame, n_short_blocks=10):
Eol = numpy.sum(frame ** 2) # total frame energy
L = len(frame)
sub_win_len = int(numpy.floor(L / n_short_blocks))
if L != sub_win_len * n_short_blocks:
frame = frame[0:sub_win_len * n_short_b... | [
"Computes entropy of energy"
] |
Please provide a description of the function:def stSpectralCentroidAndSpread(X, fs):
ind = (numpy.arange(1, len(X) + 1)) * (fs/(2.0 * len(X)))
Xt = X.copy()
Xt = Xt / Xt.max()
NUM = numpy.sum(ind * Xt)
DEN = numpy.sum(Xt) + eps
# Centroid:
C = (NUM / DEN)
# Spread:
S = numpy.... | [
"Computes spectral centroid of frame (given abs(FFT))"
] |
Please provide a description of the function:def stSpectralEntropy(X, n_short_blocks=10):
L = len(X) # number of frame samples
Eol = numpy.sum(X ** 2) # total spectral energy
sub_win_len = int(numpy.floor(L / n_short_blocks)) # length of sub-frame
if L != sub_w... | [
"Computes the spectral entropy"
] |
Please provide a description of the function:def stSpectralFlux(X, X_prev):
# compute the spectral flux as the sum of square distances:
sumX = numpy.sum(X + eps)
sumPrevX = numpy.sum(X_prev + eps)
F = numpy.sum((X / sumX - X_prev/sumPrevX) ** 2)
return F | [
"\n Computes the spectral flux feature of the current frame\n ARGUMENTS:\n X: the abs(fft) of the current frame\n X_prev: the abs(fft) of the previous frame\n "
] |
Please provide a description of the function:def stSpectralRollOff(X, c, fs):
totalEnergy = numpy.sum(X ** 2)
fftLength = len(X)
Thres = c*totalEnergy
# Ffind the spectral rolloff as the frequency position
# where the respective spectral energy is equal to c*totalEnergy
CumSum = numpy.cums... | [
"Computes spectral roll-off"
] |
Please provide a description of the function:def stHarmonic(frame, fs):
M = numpy.round(0.016 * fs) - 1
R = numpy.correlate(frame, frame, mode='full')
g = R[len(frame)-1]
R = R[len(frame):-1]
# estimate m0 (as the first zero crossing of R)
[a, ] = numpy.nonzero(numpy.diff(numpy.sign(R)))
... | [
"\n Computes harmonic ratio and pitch\n "
] |
Please provide a description of the function:def mfccInitFilterBanks(fs, nfft):
# filter bank params:
lowfreq = 133.33
linsc = 200/3.
logsc = 1.0711703
numLinFiltTotal = 13
numLogFilt = 27
if fs < 8000:
nlogfil = 5
# Total number of filters
nFiltTotal = numLinFiltTota... | [
"\n Computes the triangular filterbank for MFCC computation \n (used in the stFeatureExtraction function before the stMFCC function call)\n This function is taken from the scikits.talkbox library (MIT Licence):\n https://pypi.python.org/pypi/scikits.talkbox\n "
] |
Please provide a description of the function:def stMFCC(X, fbank, n_mfcc_feats):
mspec = numpy.log10(numpy.dot(X, fbank.T)+eps)
ceps = dct(mspec, type=2, norm='ortho', axis=-1)[:n_mfcc_feats]
return ceps | [
"\n Computes the MFCCs of a frame, given the fft mag\n\n ARGUMENTS:\n X: fft magnitude abs(FFT)\n fbank: filter bank (see mfccInitFilterBanks)\n RETURN\n ceps: MFCCs (13 element vector)\n\n Note: MFCC calculation is, in general, taken from the \n scikits... |
Please provide a description of the function:def stChromaFeaturesInit(nfft, fs):
freqs = numpy.array([((f + 1) * fs) / (2 * nfft) for f in range(nfft)])
Cp = 27.50
nChroma = numpy.round(12.0 * numpy.log2(freqs / Cp)).astype(int)
nFreqsPerChroma = numpy.zeros((nChroma.shape[0], ))
uChr... | [
"\n This function initializes the chroma matrices used in the calculation of the chroma features\n "
] |
Please provide a description of the function:def stChromagram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = l... | [
"\n Short-term FFT mag for spectogram estimation:\n Returns:\n a numpy array (nFFT x numOfShortTermWindows)\n ARGUMENTS:\n signal: the input signal samples\n fs: the sampling freq (in Hz)\n win: the short-term window size (in samples)\n step: ... |
Please provide a description of the function:def beatExtraction(st_features, win_len, PLOT=False):
# Features that are related to the beat tracking task:
toWatch = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
max_beat_time = int(round(2.0 / win_len))
hist_all = numpy.zeros((max... | [
"\n This function extracts an estimate of the beat rate for a musical signal.\n ARGUMENTS:\n - st_features: a numpy array (n_feats x numOfShortTermWindows)\n - win_len: window size in seconds\n RETURNS:\n - BPM: estimates of beats per minute\n - Ratio: a confi... |
Please provide a description of the function:def stSpectogram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = l... | [
"\n Short-term FFT mag for spectogram estimation:\n Returns:\n a numpy array (nFFT x numOfShortTermWindows)\n ARGUMENTS:\n signal: the input signal samples\n fs: the sampling freq (in Hz)\n win: the short-term window size (in samples)\n step: ... |
Please provide a description of the function:def stFeatureExtraction(signal, fs, win, step):
win = int(win)
step = int(step)
# Signal normalization
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC... | [
"\n This function implements the shor-term windowing process. For each short-term window a set of features is extracted.\n This results to a sequence of feature vectors, stored in a numpy matrix.\n\n ARGUMENTS\n signal: the input signal samples\n fs: the sampling freq (in Hz)\... |
Please provide a description of the function:def mtFeatureExtraction(signal, fs, mt_win, mt_step, st_win, st_step):
mt_win_ratio = int(round(mt_win / st_step))
mt_step_ratio = int(round(mt_step / st_step))
mt_features = []
st_features, f_names = stFeatureExtraction(signal, fs, st_win, st_step)
... | [
"\n Mid-term feature extraction\n "
] |
Please provide a description of the function:def dirWavFeatureExtraction(dirName, mt_win, mt_step, st_win, st_step,
compute_beat=False):
all_mt_feats = numpy.array([])
process_times = []
types = ('*.wav', '*.aif', '*.aiff', '*.mp3', '*.au', '*.ogg')
wav_file_list = []... | [
"\n This function extracts the mid-term features of the WAVE files of a particular folder.\n\n The resulting feature vector is extracted by long-term averaging the mid-term features.\n Therefore ONE FEATURE VECTOR is extracted for each WAV file.\n\n ARGUMENTS:\n - dirName: the path of the ... |
Please provide a description of the function:def dirsWavFeatureExtraction(dirNames, mt_win, mt_step, st_win, st_step, compute_beat=False):
'''
Same as dirWavFeatureExtraction, but instead of a single dir it
takes a list of paths as input and returns a list of feature matrices.
EXAMPLE:
[features, cl... | [] |
Please provide a description of the function:def dirWavFeatureExtractionNoAveraging(dirName, mt_win, mt_step, st_win, st_step):
all_mt_feats = numpy.array([])
signal_idx = numpy.array([])
process_times = []
types = ('*.wav', '*.aif', '*.aiff', '*.ogg')
wav_file_list = []
for files in typ... | [
"\n This function extracts the mid-term features of the WAVE\n files of a particular folder without averaging each file.\n\n ARGUMENTS:\n - dirName: the path of the WAVE directory\n - mt_win, mt_step: mid-term window and step (in seconds)\n - st_win, st_step: short-term ... |
Please provide a description of the function:def mtFeatureExtractionToFile(fileName, midTermSize, midTermStep, shortTermSize, shortTermStep, outPutFile,
storeStFeatures=False, storeToCSV=False, PLOT=False):
[fs, x] = audioBasicIO.readAudioFile(fileName)
x = audioBasicIO.stereo... | [
"\n This function is used as a wrapper to:\n a) read the content of a WAV file\n b) perform mid-term feature extraction on that signal\n c) write the mid-term feature sequences to a numpy file\n "
] |
Please provide a description of the function:def market_value(self):
return sum(position.market_value for position in six.itervalues(self._positions)) | [
"\n [float] 市值\n "
] |
Please provide a description of the function:def transaction_cost(self):
return sum(position.transaction_cost for position in six.itervalues(self._positions)) | [
"\n [float] 总费用\n "
] |
Please provide a description of the function:def buy_open(id_or_ins, amount, price=None, style=None):
return order(id_or_ins, amount, SIDE.BUY, POSITION_EFFECT.OPEN, cal_style(price, style)) | [
"\n 买入开仓。\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n\n :param int amount: 下单手数\n\n :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。\n\n :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:... |
Please provide a description of the function:def buy_close(id_or_ins, amount, price=None, style=None, close_today=False):
position_effect = POSITION_EFFECT.CLOSE_TODAY if close_today else POSITION_EFFECT.CLOSE
return order(id_or_ins, amount, SIDE.BUY, position_effect, cal_style(price, style)) | [
"\n 平卖仓\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n\n :param int amount: 下单手数\n\n :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。\n\n :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~... |
Please provide a description of the function:def sell_open(id_or_ins, amount, price=None, style=None):
return order(id_or_ins, amount, SIDE.SELL, POSITION_EFFECT.OPEN, cal_style(price, style)) | [
"\n 卖出开仓\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n\n :param int amount: 下单手数\n\n :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。\n\n :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`... |
Please provide a description of the function:def sell_close(id_or_ins, amount, price=None, style=None, close_today=False):
position_effect = POSITION_EFFECT.CLOSE_TODAY if close_today else POSITION_EFFECT.CLOSE
return order(id_or_ins, amount, SIDE.SELL, position_effect, cal_style(price, style)) | [
"\n 平买仓\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n\n :param int amount: 下单手数\n\n :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。\n\n :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~... |
Please provide a description of the function:def get_future_contracts(underlying_symbol):
env = Environment.get_instance()
return env.data_proxy.get_future_contracts(underlying_symbol, env.trading_dt) | [
"\n 获取某一期货品种在策略当前日期的可交易合约order_book_id列表。按照到期月份,下标从小到大排列,返回列表中第一个合约对应的就是该品种的近月合约。\n\n :param str underlying_symbol: 期货合约品种,例如沪深300股指期货为'IF'\n\n :return: list[`str`]\n\n :example:\n\n 获取某一天的主力合约代码(策略当前日期是20161201):\n\n .. code-block:: python\n\n [In]\n logger.info(get_fut... |
Please provide a description of the function:def quantity(self):
if np.isnan(self._quantity):
raise RuntimeError("Quantity of order {} is not supposed to be nan.".format(self.order_id))
return self._quantity | [
"\n [int] 订单数量\n "
] |
Please provide a description of the function:def filled_quantity(self):
if np.isnan(self._filled_quantity):
raise RuntimeError("Filled quantity of order {} is not supposed to be nan.".format(self.order_id))
return self._filled_quantity | [
"\n [int] 订单已成交数量\n "
] |
Please provide a description of the function:def frozen_price(self):
if np.isnan(self._frozen_price):
raise RuntimeError("Frozen price of order {} is not supposed to be nan.".format(self.order_id))
return self._frozen_price | [
"\n [float] 冻结价格\n "
] |
Please provide a description of the function:def datetime(self):
try:
dt = self._tick_dict['datetime']
except (KeyError, ValueError):
return datetime.datetime.min
else:
if not isinstance(dt, datetime.datetime):
if dt > 1000000000000000... | [
"\n [datetime.datetime] 当前快照数据的时间戳\n "
] |
Please provide a description of the function:def value_percent(self):
accounts = Environment.get_instance().portfolio.accounts
if DEFAULT_ACCOUNT_TYPE.STOCK.name not in accounts:
return 0
total_value = accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name].total_value
return 0 if... | [
"\n [float] 获得该持仓的实时市场价值在股票投资组合价值中所占比例,取值范围[0, 1]\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.