_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q259400
Structure.get_evanno_table
validation
def get_evanno_table(self, kvalues, max_var_multiple=0, quiet=False): """ Calculates the Evanno table from results files for tests with K-values in the input list kvalues. The values lnPK, lnPPK, and deltaK are calculated. The max_var_multiplier arg can be used to exclude results files based on variance of the likelihood as a proxy for convergence. Parameters: ----------- kvalues : list The list of K-values for which structure was run for this object. e.g., kvalues = [3, 4, 5] max_var_multiple: int A multiplier value to use as a filter for convergence of runs. Default=0=no filtering. As an example, if 10 replicates were run then the variance of the run with the minimum variance is used as a benchmark. If other runs have a variance that is N times greater then that run will be excluded. Remember, if replicate runs sampled different distributions of SNPs then it is not unexpected that they will have very different variances. However, you may still want to exclude runs with very high variance since they likely have
python
{ "resource": "" }
q259401
Rep.parse
validation
def parse(self, psearch, dsearch): """ parse an _f structure output file """ stable = "" with open(self.repfile) as orep: dat = orep.readlines() for line in dat: ## stat lines if "Estimated Ln Prob of Data" in line: self.est_lnlik = float(line.split()[-1]) if "Mean value of ln likelihood" in line: self.mean_lnlik = float(line.split()[-1]) if "Variance of ln likelihood" in line: self.var_lnlik = float(line.split()[-1]) if "Mean value of alpha" in line: self.alpha = float(line.split()[-1]) ## matrix lines nonline = psearch.search(line) popline = dsearch.search(line) #if ") : " in line: if nonline: ## check if sample is supervised... abc = line.strip().split() outstr = "{}{}{}".format( " ".join([abc[0], abc[0], abc[2], abc[0].split('.')[0]]), " : ", " ".join(abc[4:]) ) self.inds += 1
python
{ "resource": "" }
q259402
_call_raxml
validation
def _call_raxml(command_list): """ call the command as sps """ proc = subprocess.Popen( command_list, stderr=subprocess.STDOUT,
python
{ "resource": "" }
q259403
Raxml.run
validation
def run(self, ipyclient=None, quiet=False, force=False, block=False, ): """ Submits raxml job to run. If no ipyclient object is provided then the function will block until the raxml run is finished. If an ipyclient is provided then the job is sent to a remote engine and an asynchronous result object is returned which can be queried or awaited until it finishes. Parameters ----------- ipyclient: Not yet supported... quiet: suppress print statements force: overwrite existing results files with this job name. block: will block progress in notebook until job finishes, even if job is running on a remote ipyclient. """ ## stop before trying in raxml if force: for key, oldfile in self.trees: if os.path.exists(oldfile): os.remove(oldfile) if os.path.exists(self.trees.info): print("Error: set a new name for this job or use Force flag.\nFile exists: {}"\ .format(self.trees.info)) return ## TODO: add a
python
{ "resource": "" }
q259404
Raxml._get_binary
validation
def _get_binary(self): """ find binaries available""" ## check for binary backup_binaries = ["raxmlHPC-PTHREADS", "raxmlHPC-PTHREADS-SSE3"] ## check user binary first, then backups for binary in [self.params.binary] + backup_binaries: proc = subprocess.Popen(["which", self.params.binary], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate() ##
python
{ "resource": "" }
q259405
dstat
validation
def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0): """ private function to perform a single D-stat test""" #if isinstance(inarr, str): # with open(inarr, 'r') as infile: # inarr = infile.read().strip().split("|\n") # ## get data as an array from loci file # ## if loci-list then parse arr from loci if isinstance(inarr, list): arr, _ = _loci_to_arr(inarr, taxdict, mindict) # ## if it's an array already then go ahead # elif isinstance(inarr, np.ndarray): # arr = inarr # ## if it's a simulation object get freqs from array # elif isinstance(inarr, Sim): # arr = _msp_to_arr(inarr, taxdict) #elif isinstance(inarr,
python
{ "resource": "" }
q259406
_get_boots
validation
def _get_boots(arr, nboots): """ return array of bootstrap D-stats """ ## hold results (nboots, [dstat, ]) boots = np.zeros((nboots,)) ## iterate to fill boots
python
{ "resource": "" }
q259407
Baba.taxon_table
validation
def taxon_table(self): """ Returns the .tests list of taxa as a pandas dataframe. By auto-generating this table from tests it means that the table itself cannot be modified unless it is returned and saved. """ if self.tests: keys = sorted(self.tests[0].keys()) if isinstance(self.tests, list): ld = [[(key, i[key]) for key in keys] for i in self.tests]
python
{ "resource": "" }
q259408
nexmake
validation
def nexmake(mdict, nlocus, dirs, mcmc_burnin, mcmc_ngen, mcmc_sample_freq): """ function that takes a dictionary mapping names to sequences, and a locus number, and writes it as a NEXUS file with a mrbayes analysis block. """ ## create matrix as a string max_name_len = max([len(i) for i in mdict]) namestring = "{:<" + str(max_name_len+1) + "}
python
{ "resource": "" }
q259409
call_fastq_dump_on_SRRs
validation
def call_fastq_dump_on_SRRs(self, srr, outname, paired): """ calls fastq-dump on SRRs, relabels fastqs by their accession names, and writes them to the workdir. Saves temp sra files in the designated tmp folder and immediately removes them. """ ## build command for fastq-dumping fd_cmd = [ "fastq-dump", srr, "--accession", outname, "--outdir", self.workdir, "--gzip", ] if paired: fd_cmd += ["--split-files"] ## call fq dump command proc = sps.Popen(fd_cmd, stderr=sps.STDOUT, stdout=sps.PIPE) o, e
python
{ "resource": "" }
q259410
fields_checker
validation
def fields_checker(fields): """ returns a fields argument formatted as a list of strings. and doesn't allow zero. """ ## make sure fields will work if isinstance(fields, int): fields = str(fields) if isinstance(fields, str):
python
{ "resource": "" }
q259411
SRA.run
validation
def run(self, force=False, ipyclient=None, name_fields=30, name_separator="_", dry_run=False): """ Download the accessions into a the designated workdir. Parameters ---------- force: (bool) If force=True then existing files with the same name will be overwritten. ipyclient: (ipyparallel.Client) If provided, work will be distributed across a parallel client, otherwise download will be run on a single core. name_fields: (int, str): Provide the index of the name fields to be used as a prefix for fastq output files. The default is 30, which is the SampleName field. Use sra.fetch_fields to see all available fields and their indices. A likely alternative is 1 (Run). If multiple are listed then they will be joined by a "_" character. For example (29,30) would yield something like: latin-name_sample-name (e.g., mus_musculus-NR10123). dry_run: (bool) If True then a table of file names that _would_ be downloaded will be shown, but the actual files will note be downloaded. """ ## temporarily set directory for tmpfiles used by fastq-dump ## if this fails then just skip it. try: ## ensure output directory, also used as tmpdir if not os.path.exists(self.workdir): os.makedirs(self.workdir) ## get original directory for sra files ## probably /home/ncbi/public/sra by default. self._set_vdbconfig_path() ## register ipyclient for cleanup if ipyclient: self._ipcluster["pids"] = {} for eid in ipyclient.ids: engine = ipyclient[eid] if not engine.outstanding: pid = engine.apply(os.getpid).get()
python
{ "resource": "" }
q259412
Client.Async
validation
def Async(cls, token, session=None, **options): """Returns the client in async mode."""
python
{ "resource": "" }
q259413
Client.get_constants
validation
def get_constants(self, **params: keys): """Get the CR Constants Parameters ---------- \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the
python
{ "resource": "" }
q259414
Client.get_player
validation
def get_player(self, *tags: crtag, **params: keys): """Get a player information Parameters ---------- \*tags: str Valid player tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the
python
{ "resource": "" }
q259415
Client.get_clan
validation
def get_clan(self, *tags: crtag, **params: keys): """Get a clan information Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the
python
{ "resource": "" }
q259416
Client.search_tournaments
validation
def search_tournaments(self, **params: keys): """Search for a tournament Parameters ---------- name: str The name of the tournament \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None Limit the number of items returned in the response \*\*page:
python
{ "resource": "" }
q259417
Client.get_top_war_clans
validation
def get_top_war_clans(self, country_key='', **params: keys): """Get a list of top clans by war location_id: Optional[str] = '' A location ID or '' (global) See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable location IDs \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None
python
{ "resource": "" }
q259418
Client.get_popular_clans
validation
def get_popular_clans(self, **params: keys): """Get a list of most queried clans \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None Limit the number of items returned in the response \*\*page: Optional[int] = None Works with
python
{ "resource": "" }
q259419
Client.get_popular_players
validation
def get_popular_players(self, **params: keys): """Get a list of most queried players \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None Limit the number of items returned in the response \*\*page: Optional[int] = None Works with
python
{ "resource": "" }
q259420
Client.get_popular_tournaments
validation
def get_popular_tournaments(self, **params: keys): """Get a list of most queried tournaments \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None Limit the number of items returned in the response \*\*page: Optional[int] = None Works
python
{ "resource": "" }
q259421
Client.get_popular_decks
validation
def get_popular_decks(self, **params: keys): """Get a list of most queried decks \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None Limit the number of items returned in the response \*\*page: Optional[int] = None Works
python
{ "resource": "" }
q259422
Client.get_known_tournaments
validation
def get_known_tournaments(self, **params: tournamentfilter): """Get a list of queried tournaments \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None Limit the number of items returned in the response \*\*page: Optional[int] = None Works
python
{ "resource": "" }
q259423
Client.get_player
validation
def get_player(self, tag: crtag, timeout=None): """Get information about a player Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None
python
{ "resource": "" }
q259424
Client.get_player_chests
validation
def get_player_chests(self, tag: crtag, timeout: int=None): """Get information about a player's chest cycle Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None
python
{ "resource": "" }
q259425
Client.get_clan
validation
def get_clan(self, tag: crtag, timeout: int=None): """Get inforamtion about a clan Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None
python
{ "resource": "" }
q259426
Client.search_clans
validation
def search_clans(self, **params: clansearch): """Search for a clan. At least one of the filters must be present Parameters ---------- name: Optional[str] The name of a clan (has to be at least 3 characters long) locationId: Optional[int] A location ID minMembers: Optional[int] The minimum member count of a clan maxMembers: Optional[int] The maximum member count of a clan
python
{ "resource": "" }
q259427
Client.search_tournaments
validation
def search_tournaments(self, name: str, **params: keys): """Search for a tournament by its name Parameters ---------- name: str The name of a tournament \*\*limit: Optional[int] = None Limit the number of items returned in the response \*\*timeout: Optional[int] = None
python
{ "resource": "" }
q259428
Client.get_all_cards
validation
def get_all_cards(self, timeout: int=None): """Get a list of all the cards in the game Parameters ---------- timeout: Optional[int] = None
python
{ "resource": "" }
q259429
Client.get_all_locations
validation
def get_all_locations(self, timeout: int=None): """Get a list of all locations Parameters ---------- timeout: Optional[int] = None
python
{ "resource": "" }
q259430
Client.get_location
validation
def get_location(self, location_id: int, timeout: int=None): """Get a location information Parameters ---------- location_id: int A location ID See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable location IDs timeout: Optional[int] = None
python
{ "resource": "" }
q259431
Client.get_top_clans
validation
def get_top_clans(self, location_id='global', **params: keys): """Get a list of top clans by trophy Parameters ---------- location_id: Optional[str] = 'global' A location ID or global See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable location IDs \*\*limit: Optional[int] = None
python
{ "resource": "" }
q259432
Client.get_clan_image
validation
def get_clan_image(self, obj: BaseAttrDict): """Get the clan badge image URL Parameters --------- obj: official_api.models.BaseAttrDict An object that has the clan badge ID either in ``.clan.badge_id`` or ``.badge_id`` Can be a clan or a profile for example. Returns str """ try: badge_id = obj.clan.badge_id except AttributeError: try:
python
{ "resource": "" }
q259433
Client.get_arena_image
validation
def get_arena_image(self, obj: BaseAttrDict): """Get the arena image URL Parameters --------- obj: official_api.models.BaseAttrDict An object that has the arena ID in ``.arena.id``
python
{ "resource": "" }
q259434
Client.get_deck_link
validation
def get_deck_link(self, deck: BaseAttrDict): """Form a deck link Parameters --------- deck: official_api.models.BaseAttrDict An object is a deck. Can be retrieved
python
{ "resource": "" }
q259435
Client.get_datetime
validation
def get_datetime(self, timestamp: str, unix=True): """Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp or a datetime.datetime object Parameters --------- timestamp: str A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API in the ``created_time`` field for example (eg. 20180718T145906.000Z) unix: Optional[bool] = True
python
{ "resource": "" }
q259436
typecasted
validation
def typecasted(func): """Decorator that converts arguments via annotations.""" signature = inspect.signature(func).parameters.items() @wraps(func) def wrapper(*args, **kwargs): args = list(args) new_args = [] new_kwargs = {} for _, param in signature: converter = param.annotation if converter is inspect._empty: converter = lambda a: a # do nothing if param.kind is param.POSITIONAL_OR_KEYWORD: if args:
python
{ "resource": "" }
q259437
coerce_annotation
validation
def coerce_annotation(ann, namespace): '''Validate that the annotation has the correct namespace, and is well-formed. If the annotation is not of the correct namespace, automatic conversion is attempted. Parameters ---------- ann : jams.Annotation The annotation object in question namespace : str The namespace pattern to match `ann` against Returns ------- ann_coerced: jams.Annotation The annotation coerced to the target namespace Raises ------ NamespaceError
python
{ "resource": "" }
q259438
beat
validation
def beat(ref, est, **kwargs): r'''Beat tracking evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also -------- mir_eval.beat.evaluate Examples -------- >>> # Load in the JAMS objects >>> ref_jam = jams.load('reference.jams') >>> est_jam = jams.load('estimated.jams') >>> # Select the first relevant annotations >>> ref_ann = ref_jam.search(namespace='beat')[0] >>> est_ann =
python
{ "resource": "" }
q259439
chord
validation
def chord(ref, est, **kwargs): r'''Chord evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also -------- mir_eval.chord.evaluate Examples
python
{ "resource": "" }
q259440
hierarchy_flatten
validation
def hierarchy_flatten(annotation): '''Flatten a multi_segment annotation into mir_eval style. Parameters ---------- annotation : jams.Annotation An annotation in the `multi_segment` namespace Returns ------- hier_intervalss : list A list of lists of intervals, ordered by increasing specificity. hier_labels : list A list of lists of labels, ordered by increasing specificity. ''' intervals, values = annotation.to_interval_values() ordering = dict() for interval, value in zip(intervals, values): level = value['level'] if level not in ordering: ordering[level] = dict(intervals=list(),
python
{ "resource": "" }
q259441
hierarchy
validation
def hierarchy(ref, est, **kwargs): r'''Multi-level segmentation evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also -------- mir_eval.hierarchy.evaluate Examples -------- >>> # Load in the JAMS objects >>> ref_jam = jams.load('reference.jams') >>> est_jam = jams.load('estimated.jams') >>> # Select the first relevant annotations >>> ref_ann = ref_jam.search(namespace='multi_segment')[0] >>> est_ann = est_jam.search(namespace='multi_segment')[0] >>> scores = jams.eval.hierarchy(ref_ann, est_ann) '''
python
{ "resource": "" }
q259442
tempo
validation
def tempo(ref, est, **kwargs): r'''Tempo evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also -------- mir_eval.tempo.evaluate
python
{ "resource": "" }
q259443
melody
validation
def melody(ref, est, **kwargs): r'''Melody extraction evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also -------- mir_eval.melody.evaluate Examples -------- >>> # Load in the JAMS objects >>> ref_jam = jams.load('reference.jams') >>> est_jam = jams.load('estimated.jams') >>> # Select the first relevant annotations >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0] >>> est_ann = est_jam.search(namespace='pitch_contour')[0] >>> scores = jams.eval.melody(ref_ann, est_ann) ''' namespace = 'pitch_contour' ref = coerce_annotation(ref, namespace) est =
python
{ "resource": "" }
q259444
pattern_to_mireval
validation
def pattern_to_mireval(ann): '''Convert a pattern_jku annotation object to mir_eval format. Parameters ---------- ann : jams.Annotation Must have `namespace='pattern_jku'` Returns ------- patterns : list of list of tuples - `patterns[x]` is a list containing all occurrences of pattern x - `patterns[x][y]` is a list containing all notes for occurrence y of pattern x - `patterns[x][y][z]` contains a time-note tuple `(time, midi note)` ''' # It's easier to work with dictionaries, since we can't assume # sequential pattern or occurrence identifiers patterns = defaultdict(lambda: defaultdict(list)) # Iterate over the data in interval-value format for
python
{ "resource": "" }
q259445
pattern
validation
def pattern(ref, est, **kwargs): r'''Pattern detection evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also --------
python
{ "resource": "" }
q259446
transcription
validation
def transcription(ref, est, **kwargs): r'''Note transcription evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. See Also -------- mir_eval.transcription.evaluate Examples -------- >>> # Load in the JAMS objects >>> ref_jam = jams.load('reference.jams') >>> est_jam = jams.load('estimated.jams') >>> # Select the first relevant annotations. You can use any annotation >>> # type that can be converted to pitch_contour (such as pitch_midi) >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0] >>> est_ann = est_jam.search(namespace='note_hz')[0] >>> scores = jams.eval.transcription(ref_ann, est_ann) '''
python
{ "resource": "" }
q259447
add_namespace
validation
def add_namespace(filename): '''Add a namespace definition to our working set. Namespace files consist of partial JSON schemas defining the behavior of the `value` and `confidence` fields of an Annotation. Parameters ---------- filename : str Path to json file
python
{ "resource": "" }
q259448
namespace
validation
def namespace(ns_key): '''Construct a validation schema for a given namespace. Parameters ---------- ns_key : str Namespace key identifier (eg, 'beat' or 'segment_tut') Returns ------- schema : dict JSON schema of `namespace` ''' if ns_key not in __NAMESPACE__: raise NamespaceError('Unknown namespace: {:s}'.format(ns_key)) sch =
python
{ "resource": "" }
q259449
namespace_array
validation
def namespace_array(ns_key): '''Construct a validation schema for arrays of a given namespace. Parameters ---------- ns_key : str Namespace key identifier Returns ------- schema : dict JSON schema of `namespace` observation arrays '''
python
{ "resource": "" }
q259450
values
validation
def values(ns_key): '''Return the allowed values for an enumerated namespace. Parameters ---------- ns_key : str Namespace key identifier Returns ------- values : list Raises ------ NamespaceError If `ns_key` is not found, or does not have enumerated values Examples -------- >>> jams.schema.values('tag_gtzan') ['blues', 'classical', 'country', 'disco', 'hip-hop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
python
{ "resource": "" }
q259451
get_dtypes
validation
def get_dtypes(ns_key): '''Get the dtypes associated with the value and confidence fields for a given namespace. Parameters ---------- ns_key : str The namespace key in question Returns ------- value_dtype, confidence_dtype : numpy.dtype Type identifiers for value and confidence fields. ''' # First, get the schema if ns_key
python
{ "resource": "" }
q259452
list_namespaces
validation
def list_namespaces(): '''Print out a listing of available namespaces''' print('{:30s}\t{:40s}'.format('NAME', 'DESCRIPTION')) print('-' * 78) for sch in sorted(__NAMESPACE__):
python
{ "resource": "" }
q259453
__get_dtype
validation
def __get_dtype(typespec): '''Get the dtype associated with a jsonschema type definition Parameters ---------- typespec : dict The schema definition Returns ------- dtype : numpy.dtype The associated dtype ''' if 'type' in typespec:
python
{ "resource": "" }
q259454
__load_jams_schema
validation
def __load_jams_schema(): '''Load the schema file from the package.''' schema_file = os.path.join(SCHEMA_DIR, 'jams_schema.json') jams_schema = None with open(resource_filename(__name__, schema_file), mode='r') as fdesc:
python
{ "resource": "" }
q259455
import_lab
validation
def import_lab(namespace, filename, infer_duration=True, **parse_options): r'''Load a .lab file as an Annotation object. .lab files are assumed to have the following format: ``TIME_START\tTIME_END\tANNOTATION`` By default, .lab files are assumed to have columns separated by one or more white-space characters, and have no header or index column information. If the .lab file contains only two columns, then an empty duration field is inferred. If the .lab file contains more than three columns, each row's annotation value is assigned the contents of last non-empty column. Parameters ---------- namespace : str The namespace for the new annotation filename : str Path to the .lab file infer_duration : bool If `True`, interval durations are inferred from `(start, end)` columns, or difference between successive times. If `False`, interval durations are assumed to be explicitly coded as `(start, duration)` columns. If only one time column is given, then durations are set to 0. For instantaneous event annotations (e.g., beats or onsets), this should be set to `False`. parse_options : additional keyword arguments Passed to ``pandas.DataFrame.read_csv`` Returns ------- annotation : Annotation The newly constructed annotation object See Also -------- pandas.DataFrame.read_csv ''' # Create a new annotation object annotation = core.Annotation(namespace) parse_options.setdefault('sep', r'\s+') parse_options.setdefault('engine', 'python') parse_options.setdefault('header', None)
python
{ "resource": "" }
q259456
expand_filepaths
validation
def expand_filepaths(base_dir, rel_paths): """Expand a list of relative paths to a give base directory. Parameters ---------- base_dir : str The target base directory rel_paths : list (or list-like) Collection of relative path strings Returns ------- expanded_paths : list `rel_paths` rooted at `base_dir`
python
{ "resource": "" }
q259457
smkdirs
validation
def smkdirs(dpath, mode=0o777): """Safely make a full directory path if it doesn't exist. Parameters ---------- dpath : str Path of directory/directories to create mode : int [default=0777]
python
{ "resource": "" }
q259458
find_with_extension
validation
def find_with_extension(in_dir, ext, depth=3, sort=True): """Naive depth-search into a directory for files with a given extension. Parameters ---------- in_dir : str Path to search. ext : str File extension to match. depth : int Depth of directories to search. sort : bool Sort the list alphabetically Returns ------- matched : list Collection of matching file paths. Examples -------- >>> jams.util.find_with_extension('Audio', 'wav') ['Audio/LizNelson_Rainfall/LizNelson_Rainfall_MIX.wav',
python
{ "resource": "" }
q259459
get_comments
validation
def get_comments(jam, ann): '''Get the metadata from a jam and an annotation, combined as a string. Parameters ---------- jam : JAMS The jams object ann : Annotation An annotation object Returns ------- comments : str The jam.file_metadata and ann.annotation_metadata, combined and serialized ''' jam_comments =
python
{ "resource": "" }
q259460
convert_jams
validation
def convert_jams(jams_file, output_prefix, csv=False, comment_char='#', namespaces=None): '''Convert jams to labs. Parameters ---------- jams_file : str The path on disk to the jams file in question output_prefix : str The file path prefix of the outputs csv : bool Whether to output in csv (True) or lab (False) format comment_char : str The character used to denote comments namespaces : list-like The set of namespace patterns to match for output ''' if namespaces is None: raise ValueError('No namespaces provided. Try ".*" for all namespaces.') jam = jams.load(jams_file) # Get all the annotations # Filter down to the unique ones # For each annotation # generate the comment string # generate the output filename # dump to csv # Make a counter object for each namespace type counter = collections.Counter() annotations = [] for query in namespaces: annotations.extend(jam.search(namespace=query)) if csv: suffix = 'csv' sep = ','
python
{ "resource": "" }
q259461
parse_arguments
validation
def parse_arguments(args): '''Parse arguments from the command line''' parser = argparse.ArgumentParser(description='Convert JAMS to .lab files') parser.add_argument('-c', '--comma-separated', dest='csv', action='store_true', default=False, help='Output in .csv instead of .lab') parser.add_argument('--comment', dest='comment_char', type=str,
python
{ "resource": "" }
q259462
_conversion
validation
def _conversion(target, source): '''A decorator to register namespace conversions. Usage ----- >>> @conversion('tag_open', 'tag_.*') ... def tag_to_open(annotation): ... annotation.namespace = 'tag_open' ... return annotation ''' def register(func):
python
{ "resource": "" }
q259463
convert
validation
def convert(annotation, target_namespace): '''Convert a given annotation to the target namespace. Parameters ---------- annotation : jams.Annotation An annotation object target_namespace : str The target namespace Returns ------- mapped_annotation : jams.Annotation if `annotation` already belongs to `target_namespace`, then it is returned directly. otherwise, `annotation` is copied and automatically converted to the target namespace. Raises ------ SchemaError if the input annotation fails to validate NamespaceError if no conversion is possible Examples -------- Convert frequency measurements in Hz
python
{ "resource": "" }
q259464
can_convert
validation
def can_convert(annotation, target_namespace): '''Test if an annotation can be mapped to a target namespace Parameters ---------- annotation : jams.Annotation An annotation object target_namespace : str The target namespace Returns ------- True if `annotation` can be automatically converted to
python
{ "resource": "" }
q259465
pitch_hz_to_contour
validation
def pitch_hz_to_contour(annotation): '''Convert a pitch_hz annotation to a contour''' annotation.namespace = 'pitch_contour' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence,
python
{ "resource": "" }
q259466
note_hz_to_midi
validation
def note_hz_to_midi(annotation): '''Convert a pitch_hz annotation to pitch_midi''' annotation.namespace = 'note_midi' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration,
python
{ "resource": "" }
q259467
scaper_to_tag
validation
def scaper_to_tag(annotation): '''Convert scaper annotations to tag_open''' annotation.namespace = 'tag_open' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration,
python
{ "resource": "" }
q259468
deprecated
validation
def deprecated(version, version_removed): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' def __wrapper(func, *args, **kwargs): '''Warn the user, and then proceed.''' code = six.get_function_code(func) warnings.warn_explicit( "{:s}.{:s}\n\tDeprecated as of JAMS version {:s}." "\n\tIt will be removed in JAMS version {:s}." .format(func.__module__, func.__name__,
python
{ "resource": "" }
q259469
_open
validation
def _open(name_or_fdesc, mode='r', fmt='auto'): '''An intelligent wrapper for ``open``. Parameters ---------- name_or_fdesc : string-type or open file descriptor If a string type, refers to the path to a file on disk. If an open file descriptor, it is returned as-is. mode : string The mode with which to open the file. See ``open`` for details. fmt : string ['auto', 'jams', 'json', 'jamz'] The encoding for the input/output stream. If `auto`, the format is inferred from the filename extension. Otherwise, use the specified coding. See Also -------- open gzip.open ''' open_map = {'jams': open, 'json': open, 'jamz': gzip.open, 'gz': gzip.open} # If we've been given an open descriptor, do the right thing if hasattr(name_or_fdesc, 'read') or hasattr(name_or_fdesc, 'write'): yield name_or_fdesc elif isinstance(name_or_fdesc, six.string_types): # Infer the opener from the extension if fmt == 'auto': _, ext = os.path.splitext(name_or_fdesc) # Pull off the extension separator ext = ext[1:]
python
{ "resource": "" }
q259470
load
validation
def load(path_or_file, validate=True, strict=True, fmt='auto'): r"""Load a JAMS Annotation from a file. Parameters ---------- path_or_file : str or file-like Path to the JAMS file to load OR An open file handle to load from. validate : bool Attempt to validate the JAMS object strict : bool if `validate == True`, enforce strict schema validation fmt : str ['auto', 'jams', 'jamz'] The encoding format of the input If `auto`, encoding is inferred from the file name. If the input is an open file handle, `jams` encoding is used. Returns ------- jam : JAMS The loaded JAMS object Raises ------ SchemaError if `validate == True`, `strict==True`, and validation fails See also -------- JAMS.validate JAMS.save Examples -------- >>> # Load a jams object from a file name >>> J = jams.load('data.jams') >>> # Or from
python
{ "resource": "" }
q259471
query_pop
validation
def query_pop(query, prefix, sep='.'): '''Pop a prefix from a query string. Parameters ---------- query : str The query string prefix : str The prefix string to pop, if it exists sep : str The string to separate fields Returns
python
{ "resource": "" }
q259472
match_query
validation
def match_query(string, query): '''Test if a string matches a query. Parameters ---------- string : str The string to test query : string, callable, or object Either a regular expression, callable function, or object. Returns ------- match : bool `True` if: - `query` is a callable and `query(string) == True` - `query` is a regular expression and `re.match(query, string)` - or `string == query` for any other query `False` otherwise '''
python
{ "resource": "" }
q259473
serialize_obj
validation
def serialize_obj(obj): '''Custom serialization functionality for working with advanced data types. - numpy arrays are converted to lists - lists are recursively serialized element-wise ''' if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray):
python
{ "resource": "" }
q259474
summary
validation
def summary(obj, indent=0): '''Helper function to format repr strings for JObjects and friends. Parameters ---------- obj The object to repr indent : int >= 0 indent each new line by `indent` spaces Returns ------- r : str If `obj` has a `__summary__` method, it is used. If `obj` is a `SortedKeyList`, then it returns a description of the
python
{ "resource": "" }
q259475
JObject.update
validation
def update(self, **kwargs): '''Update the attributes of a JObject. Parameters ---------- kwargs Keyword arguments of the form `attribute=new_value` Examples
python
{ "resource": "" }
q259476
JObject.validate
validation
def validate(self, strict=True): '''Validate a JObject against its schema Parameters ---------- strict : bool Enforce strict schema validation Returns ------- valid : bool True if the jam validates False if not, and `strict==False` Raises ------ SchemaError If `strict==True` and `jam` fails validation ''' valid = True
python
{ "resource": "" }
q259477
Annotation.append
validation
def append(self, time=None, duration=None, value=None, confidence=None): '''Append an observation to the data field Parameters ---------- time : float >= 0 duration : float >= 0 The time and duration of the new observation, in seconds value confidence The value and confidence of the new observations. Types and values should conform to the namespace of the Annotation object. Examples -------- >>> ann =
python
{ "resource": "" }
q259478
Annotation.append_records
validation
def append_records(self, records): '''Add observations from row-major storage. This is primarily useful for deserializing sparsely packed data. Parameters ---------- records : iterable of dicts or Observations Each element of `records` corresponds to one observation.
python
{ "resource": "" }
q259479
Annotation.append_columns
validation
def append_columns(self, columns): '''Add observations from column-major storage. This is primarily used for deserializing densely packed data. Parameters ---------- columns : dict of lists Keys must be `time, duration, value, confidence`, and each much be a list of equal length. ''' self.append_records([dict(time=t, duration=d, value=v, confidence=c) for (t, d, v, c)
python
{ "resource": "" }
q259480
Annotation.validate
validation
def validate(self, strict=True): '''Validate this annotation object against the JAMS schema, and its data against the namespace schema. Parameters ---------- strict : bool If `True`, then schema violations will cause an Exception. If `False`, then schema violations will issue a warning. Returns ------- valid : bool `True` if the object conforms to schema. `False` if the object fails to conform to schema, but `strict == False`. Raises ------ SchemaError If `strict == True` and the object fails validation See Also -------- JObject.validate ''' # Get the schema for this annotation ann_schema = schema.namespace_array(self.namespace) valid = True try: jsonschema.validate(self.__json_light__(data=False),
python
{ "resource": "" }
q259481
Annotation.trim
validation
def trim(self, start_time, end_time, strict=False): ''' Trim the annotation and return as a new `Annotation` object. Trimming will result in the new annotation only containing observations that occur in the intersection of the time range spanned by the annotation and the time range specified by the user. The new annotation will span the time range ``[trim_start, trim_end]`` where ``trim_start = max(self.time, start_time)`` and ``trim_end = min(self.time + self.duration, end_time)``. If ``strict=False`` (default) observations that start before ``trim_start`` and end after it will be trimmed such that they start at ``trim_start``, and similarly observations that start before ``trim_end`` and end after it will be trimmed to end at ``trim_end``. If ``strict=True`` such borderline observations will be discarded. The new duration of the annotation will be ``trim_end - trim_start``. Note that if the range defined by ``[start_time, end_time]`` doesn't intersect with the original time range spanned by the annotation the resulting annotation will contain no observations, will have the same start time as the original annotation and have duration 0. This function also copies over all the annotation metadata from the original annotation and documents the trim operation by adding a list of tuples to the annotation's sandbox keyed by ``Annotation.sandbox.trim`` which documents each trim operation with a tuple ``(start_time, end_time, trim_start, trim_end)``. Parameters ---------- start_time : float The desired start time for the trimmed annotation in seconds. end_time The desired end time for the trimmed annotation in seconds. Must be greater than ``start_time``. strict : bool When ``False`` (default) observations that lie at the boundaries of the trimming range (given by ``[trim_start, trim_end]`` as described above), i.e. observations that start before and end after either the trim start or end time, will have their time and/or duration adjusted such that only the part of the observation that lies within the trim range is kept. When ``True`` such observations are discarded and not included in the trimmed annotation. Returns ------- ann_trimmed : Annotation The trimmed annotation, returned as a new jams.Annotation object. If the trim range specified by ``[start_time, end_time]`` does not intersect at all with the original time range of the annotation a warning will be issued and the returned annotation will be empty. Raises ------ ParameterError If ``end_time`` is not greater than ``start_time``. Examples -------- >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8) >>> ann.append(time=2, duration=2, value='one') >>> ann.append(time=4, duration=2, value='two') >>> ann.append(time=6, duration=2, value='three') >>> ann.append(time=7, duration=2, value='four') >>> ann.append(time=8, duration=2, value='five') >>> ann_trim = ann.trim(5, 8, strict=False) >>> print(ann_trim.time, ann_trim.duration) (5, 3) >>> ann_trim.to_dataframe() time duration value confidence 0 5 1 two None 1 6 2 three None 2 7 1 four None >>> ann_trim_strict = ann.trim(5, 8, strict=True) >>> print(ann_trim_strict.time, ann_trim_strict.duration) (5, 3) >>> ann_trim_strict.to_dataframe() time duration value confidence 0 6 2 three None ''' # Check for basic start_time and end_time validity if end_time <= start_time: raise ParameterError( 'end_time must be greater than start_time.') # If the annotation does not have a set duration value, we'll assume # trimming is possible (up to the user to ensure this is valid). if self.duration is None: orig_time = start_time orig_duration = end_time - start_time warnings.warn( "Annotation.duration is not defined, cannot check "
python
{ "resource": "" }
q259482
Annotation.slice
validation
def slice(self, start_time, end_time, strict=False): ''' Slice the annotation and return as a new `Annotation` object. Slicing has the same effect as trimming (see `Annotation.trim`) except that while trimming does not modify the start time of the annotation or the observations it contains, slicing will set the new annotation's start time to ``max(0, trimmed_annotation.time - start_time)`` and the start time of its observations will be set with respect to this new reference start time. This function documents the slice operation by adding a list of tuples to the annotation's sandbox keyed by ``Annotation.sandbox.slice`` which documents each slice operation with a tuple ``(start_time, end_time, slice_start, slice_end)``, where ``slice_start`` and ``slice_end`` are given by ``trim_start`` and ``trim_end`` (see `Annotation.trim`). Since slicing is implemented using trimming, the trimming operation will also be documented in ``Annotation.sandbox.trim`` as described in `Annotation.trim`. This function is useful for example when trimming an audio file, allowing the user to trim the annotation while ensuring all time information matches the new trimmed audio file. Parameters ---------- start_time : float The desired start time for slicing in seconds. end_time The desired end time for slicing in seconds. Must be greater than ``start_time``. strict : bool When ``False`` (default) observations that lie at the boundaries of the slice (see `Annotation.trim` for details) will have their time and/or duration adjusted such that only the part of the observation that lies within the slice range is kept. When ``True`` such observations are discarded and not included in the sliced annotation. Returns ------- sliced_ann : Annotation The sliced annotation. See Also -------- Annotation.trim Examples -------- >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8) >>> ann.append(time=2, duration=2, value='one') >>> ann.append(time=4, duration=2, value='two') >>> ann.append(time=6, duration=2, value='three') >>> ann.append(time=7, duration=2, value='four') >>> ann.append(time=8, duration=2, value='five') >>> ann_slice = ann.slice(5, 8, strict=False) >>> print(ann_slice.time, ann_slice.duration) (0, 3) >>> ann_slice.to_dataframe() time duration value confidence
python
{ "resource": "" }
q259483
Annotation.pop_data
validation
def pop_data(self): '''Replace this observation's data with a fresh container. Returns ------- annotation_data : SortedKeyList The original
python
{ "resource": "" }
q259484
Annotation.to_samples
validation
def to_samples(self, times, confidence=False): '''Sample the annotation at specified times. Parameters ---------- times : np.ndarray, non-negative, ndim=1 The times (in seconds) to sample the annotation confidence : bool If `True`, return both values and confidences. If `False` (default) only return values. Returns ------- values : list `values[i]` is a list of observation values for intervals that cover `times[i]`. confidence : list (optional)
python
{ "resource": "" }
q259485
Annotation.to_html
validation
def to_html(self, max_rows=None): '''Render this annotation list in HTML Returns ------- rendered : str An HTML table containing this annotation's data. ''' n = len(self.data) div_id = _get_divid(self) out = r''' <div class="panel panel-default"> <div class="panel-heading" role="tab" id="heading-{0}"> <button type="button" data-toggle="collapse" data-parent="#accordion" href="#{0}" aria-expanded="false" class="collapsed btn btn-info btn-block" aria-controls="{0}"> {1:s} <span class="badge pull-right">{2:d}</span> </button> </div>'''.format(div_id, self.namespace, n) out += r''' <div id="{0}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-{0}"> <div class="panel-body">'''.format(div_id) out += r'''<div class="pull-right"> {} </div>'''.format(self.annotation_metadata._repr_html_()) out += r'''<div class="pull-right clearfix"> {} </div>'''.format(self.sandbox._repr_html_()) # -- Annotation content starts here out += r'''<div><table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th>
python
{ "resource": "" }
q259486
Annotation._key
validation
def _key(cls, obs): '''Provides sorting index for Observation objects''' if not
python
{ "resource": "" }
q259487
AnnotationArray.search
validation
def search(self, **kwargs): '''Filter the annotation array down to only those Annotation objects matching the query. Parameters ---------- kwargs : search parameters See JObject.search Returns ------- results : AnnotationArray An annotation array of the objects matching the query See Also -------- JObject.search
python
{ "resource": "" }
q259488
AnnotationArray.trim
validation
def trim(self, start_time, end_time, strict=False): ''' Trim every annotation contained in the annotation array using `Annotation.trim` and return as a new `AnnotationArray`. See `Annotation.trim` for details about trimming. This function does not modify the annotations in the original annotation array. Parameters ---------- start_time : float The desired start time for the trimmed annotations in seconds. end_time The desired end time for trimmed annotations in seconds. Must be
python
{ "resource": "" }
q259489
AnnotationArray.slice
validation
def slice(self, start_time, end_time, strict=False): ''' Slice every annotation contained in the annotation array using `Annotation.slice` and return as a new AnnotationArray See `Annotation.slice` for details about slicing. This function does not modify the annotations in the original annotation array. Parameters ---------- start_time : float The desired start time for slicing in seconds. end_time The desired end time for slicing in seconds. Must be greater than
python
{ "resource": "" }
q259490
JAMS.add
validation
def add(self, jam, on_conflict='fail'): """Add the contents of another jam to this object. Note that, by default, this method fails if file_metadata is not identical and raises a ValueError; either resolve this manually (because conflicts should almost never happen), force an 'overwrite', or tell the method to 'ignore' the metadata of the object being added. Parameters ---------- jam: JAMS object Object to add to this jam on_conflict: str, default='fail' Strategy for resolving metadata conflicts; one of ['fail', 'overwrite', or 'ignore']. Raises ------ ParameterError if `on_conflict` is an unknown value JamsError If a conflict is detected and `on_conflict='fail'` """ if on_conflict not in ['overwrite', 'fail', 'ignore']: raise ParameterError("on_conflict='{}' is not in ['fail', "
python
{ "resource": "" }
q259491
JAMS.save
validation
def save(self, path_or_file, strict=True, fmt='auto'): """Serialize annotation as a JSON formatted stream to file. Parameters ---------- path_or_file : str or file-like Path to save the JAMS object on disk OR An open file descriptor to write into strict : bool Force strict schema validation fmt : str ['auto', 'jams', 'jamz'] The output encoding format. If `auto`, it is inferred from the file name. If the input is an open file handle, `jams` encoding
python
{ "resource": "" }
q259492
JAMS.validate
validation
def validate(self, strict=True): '''Validate a JAMS object against the schema. Parameters ---------- strict : bool If `True`, an exception will be raised on validation failure. If `False`, a warning will be raised on validation failure. Returns ------- valid : bool `True` if the object passes schema validation. `False` otherwise. Raises ------ SchemaError If `strict==True` and the JAMS object does not match the schema See Also -------- jsonschema.validate ''' valid = True try: jsonschema.validate(self.__json_light__, schema.JAMS_SCHEMA) for ann in self.annotations: if isinstance(ann, Annotation): valid &= ann.validate(strict=strict) else:
python
{ "resource": "" }
q259493
JAMS.trim
validation
def trim(self, start_time, end_time, strict=False): ''' Trim all the annotations inside the jam and return as a new `JAMS` object. See `Annotation.trim` for details about how the annotations are trimmed. This operation is also documented in the jam-level sandbox with a list keyed by ``JAMS.sandbox.trim`` containing a tuple for each jam-level trim of the form ``(start_time, end_time)``. This function also copies over all of the file metadata from the original jam. Note: trimming does not affect the duration of the jam, i.e. the value of ``JAMS.file_metadata.duration`` will be the same for the original and trimmed jams. Parameters ---------- start_time : float The desired start time for the trimmed annotations in seconds. end_time The desired end time for trimmed annotations in seconds. Must be greater than ``start_time``. strict : bool When ``False`` (default) observations that lie at the boundaries of the trimming range (see `Annotation.trim` for details), will have their time and/or duration adjusted such that only the part of the observation that lies within the trim range is kept. When ``True`` such observations are discarded and not included in the trimmed annotation. Returns ------- jam_trimmed : JAMS The trimmed jam with trimmed annotations, returned as a new JAMS object. ''' # Make sure duration is set in file metadata if self.file_metadata.duration is None: raise JamsError( 'Duration must be set (jam.file_metadata.duration) before ' 'trimming can be performed.') # Make sure start and end times are within the file start/end times if not (0 <= start_time <= end_time <= float( self.file_metadata.duration)):
python
{ "resource": "" }
q259494
JAMS.slice
validation
def slice(self, start_time, end_time, strict=False): ''' Slice all the annotations inside the jam and return as a new `JAMS` object. See `Annotation.slice` for details about how the annotations are sliced. This operation is also documented in the jam-level sandbox with a list keyed by ``JAMS.sandbox.slice`` containing a tuple for each jam-level slice of the form ``(start_time, end_time)``. Since slicing is implemented using trimming, the operation will also be documented in ``JAMS.sandbox.trim`` as described in `JAMS.trim`. This function also copies over all of the file metadata from the original jam. Note: slicing will affect the duration of the jam, i.e. the new value of ``JAMS.file_metadata.duration`` will be ``end_time - start_time``. Parameters ---------- start_time : float The desired start time for slicing in seconds. end_time The desired end time for slicing in seconds. Must be greater than ``start_time``. strict : bool When ``False`` (default) observations that lie at the boundaries of the slicing range (see `Annotation.slice` for details), will have their time and/or duration adjusted such that only the part of the observation that lies within the slice range is kept. When ``True`` such observations are discarded and not included in the sliced annotation. Returns ------- jam_sliced: JAMS The sliced jam with sliced annotations, returned as a new JAMS object. ''' # Make sure duration is set in file metadata if self.file_metadata.duration is None: raise JamsError( 'Duration must be set (jam.file_metadata.duration) before ' 'slicing can be performed.') # Make sure start and end times are within the file start/end times if (start_time < 0 or start_time > float(self.file_metadata.duration) or
python
{ "resource": "" }
q259495
pprint_jobject
validation
def pprint_jobject(obj, **kwargs): '''Pretty-print a jobject. Parameters ---------- obj : jams.JObject kwargs additional parameters to `json.dumps` Returns ------- string A simplified display of `obj` contents. ''' obj_simple = {k: v for k, v in six.iteritems(obj.__json__) if v} string = json.dumps(obj_simple, **kwargs)
python
{ "resource": "" }
q259496
intervals
validation
def intervals(annotation, **kwargs): '''Plotting wrapper for labeled intervals''' times, labels = annotation.to_interval_values()
python
{ "resource": "" }
q259497
hierarchy
validation
def hierarchy(annotation, **kwargs): '''Plotting wrapper for hierarchical segmentations''' htimes, hlabels = hierarchy_flatten(annotation) htimes
python
{ "resource": "" }
q259498
pitch_contour
validation
def pitch_contour(annotation, **kwargs): '''Plotting wrapper for pitch contours''' ax = kwargs.pop('ax', None) # If the annotation is empty, we need to construct a new axes ax = mir_eval.display.__get_axes(ax=ax)[0] times, values = annotation.to_interval_values() indices = np.unique([v['index'] for v in values]) for idx in indices: rows = [i for (i, v) in enumerate(values) if v['index'] == idx]
python
{ "resource": "" }
q259499
event
validation
def event(annotation, **kwargs): '''Plotting wrapper for events''' times, values = annotation.to_interval_values()
python
{ "resource": "" }