commit/galaxy-central: carlfeberhard: data providers: add data to factory decorator to allow datasets api to parse query strings into provider settings; datasets API: allow new providers to be used in raw_data; clean up and pack scripts
1 new commit in galaxy-central: https://bitbucket.org/galaxy/galaxy-central/commits/72b02995c8b1/ Changeset: 72b02995c8b1 User: carlfeberhard Date: 2013-06-24 20:06:16 Summary: data providers: add data to factory decorator to allow datasets api to parse query strings into provider settings; datasets API: allow new providers to be used in raw_data; clean up and pack scripts Affected #: 20 files diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/binary.py --- a/lib/galaxy/datatypes/binary.py +++ b/lib/galaxy/datatypes/binary.py @@ -267,25 +267,25 @@ # bam does not use '#' to indicate comments/headers - we need to strip out those headers from the std. providers #TODO:?? seems like there should be an easier way to do/inherit this - metadata.comment_char? #TODO: incorporate samtools options to control output: regions first, then flags, etc. - @dataproviders.decorators.dataprovider_factory( 'line' ) + @dataproviders.decorators.dataprovider_factory( 'line', dataproviders.line.FilteredLineDataProvider.settings ) def line_dataprovider( self, dataset, **settings ): samtools_source = dataproviders.dataset.SamtoolsDataProvider( dataset ) settings[ 'comment_char' ] = '@' return dataproviders.line.FilteredLineDataProvider( samtools_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'regex-line' ) + @dataproviders.decorators.dataprovider_factory( 'regex-line', dataproviders.line.RegexLineDataProvider.settings ) def regex_line_dataprovider( self, dataset, **settings ): samtools_source = dataproviders.dataset.SamtoolsDataProvider( dataset ) settings[ 'comment_char' ] = '@' return dataproviders.line.RegexLineDataProvider( samtools_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'column' ) + @dataproviders.decorators.dataprovider_factory( 'column', dataproviders.column.ColumnarDataProvider.settings ) def column_dataprovider( self, dataset, **settings ): samtools_source = dataproviders.dataset.SamtoolsDataProvider( dataset ) settings[ 'comment_char' ] = '@' return dataproviders.column.ColumnarDataProvider( samtools_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'map' ) + @dataproviders.decorators.dataprovider_factory( 'map', dataproviders.column.MapDataProvider.settings ) def map_dataprovider( self, dataset, **settings ): samtools_source = dataproviders.dataset.SamtoolsDataProvider( dataset ) settings[ 'comment_char' ] = '@' @@ -293,30 +293,30 @@ # these can't be used directly - may need BamColumn, BamMap (Bam metadata -> column/map) # OR - see genomic_region_dataprovider - #@dataproviders.decorators.dataprovider_factory( 'dataset-column' ) + #@dataproviders.decorators.dataprovider_factory( 'dataset-column', dataproviders.column.ColumnarDataProvider.settings ) #def dataset_column_dataprovider( self, dataset, **settings ): # settings[ 'comment_char' ] = '@' # return super( Sam, self ).dataset_column_dataprovider( dataset, **settings ) - #@dataproviders.decorators.dataprovider_factory( 'dataset-map' ) + #@dataproviders.decorators.dataprovider_factory( 'dataset-map', dataproviders.column.MapDataProvider.settings ) #def dataset_map_dataprovider( self, dataset, **settings ): # settings[ 'comment_char' ] = '@' # return super( Sam, self ).dataset_map_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'header' ) + @dataproviders.decorators.dataprovider_factory( 'header', dataproviders.line.RegexLineDataProvider.settings ) def header_dataprovider( self, dataset, **settings ): # in this case we can use an option of samtools view to provide just what we need (w/o regex) samtools_source = dataproviders.dataset.SamtoolsDataProvider( dataset, '-H' ) return dataproviders.line.RegexLineDataProvider( samtools_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'id-seq-qual' ) + @dataproviders.decorators.dataprovider_factory( 'id-seq-qual', dataproviders.column.MapDataProvider.settings ) def id_seq_qual_dataprovider( self, dataset, **settings ): settings[ 'indeces' ] = [ 0, 9, 10 ] settings[ 'column_types' ] = [ 'str', 'str', 'str' ] settings[ 'column_names' ] = [ 'id', 'seq', 'qual' ] return self.map_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region', dataproviders.column.ColumnarDataProvider.settings ) def genomic_region_dataprovider( self, dataset, **settings ): # GenomicRegionDataProvider currently requires a dataset as source - may not be necc. #TODO:?? consider (at least) the possible use of a kwarg: metadata_source (def. to source.dataset), @@ -330,7 +330,7 @@ settings[ 'column_types' ] = [ 'str', 'int', 'int' ] return self.column_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region-map' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region-map', dataproviders.column.MapDataProvider.settings ) def genomic_region_map_dataprovider( self, dataset, **settings ): settings[ 'indeces' ] = [ 2, 3, 3 ] settings[ 'column_types' ] = [ 'str', 'int', 'int' ] diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/data.py --- a/lib/galaxy/datatypes/data.py +++ b/lib/galaxy/datatypes/data.py @@ -593,7 +593,6 @@ Base dataprovider factory for all datatypes that returns the proper provider for the given `data_format` or raises a `NoProviderAvailable`. """ - #TODO:?? is this handling super class providers? if self.has_dataprovider( data_format ): return self.dataproviders[ data_format ]( self, dataset, **settings ) raise dataproviders.exceptions.NoProviderAvailable( self, data_format ) @@ -603,12 +602,12 @@ dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.base.DataProvider( dataset_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'chunk' ) + @dataproviders.decorators.dataprovider_factory( 'chunk', dataproviders.chunk.ChunkDataProvider.settings ) def chunk_dataprovider( self, dataset, **settings ): dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.chunk.ChunkDataProvider( dataset_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'chunk64' ) + @dataproviders.decorators.dataprovider_factory( 'chunk64', dataproviders.chunk.Base64ChunkDataProvider.settings ) def chunk64_dataprovider( self, dataset, **settings ): dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.chunk.Base64ChunkDataProvider( dataset_source, **settings ) @@ -785,7 +784,7 @@ split = classmethod(split) # ------------- Dataproviders - @dataproviders.decorators.dataprovider_factory( 'line' ) + @dataproviders.decorators.dataprovider_factory( 'line', dataproviders.line.FilteredLineDataProvider.settings ) def line_dataprovider( self, dataset, **settings ): """ Returns an iterator over the dataset's lines (that have been `strip`ed) @@ -794,7 +793,7 @@ dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.line.FilteredLineDataProvider( dataset_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'regex-line' ) + @dataproviders.decorators.dataprovider_factory( 'regex-line', dataproviders.line.RegexLineDataProvider.settings ) def regex_line_dataprovider( self, dataset, **settings ): """ Returns an iterator over the dataset's lines diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/dataproviders/base.py --- a/lib/galaxy/datatypes/dataproviders/base.py +++ b/lib/galaxy/datatypes/dataproviders/base.py @@ -22,8 +22,13 @@ icorporate existing visualization/dataproviders some of the sources (esp. in datasets) don't need to be re-created +YAGNI: InterleavingMultiSourceDataProvider, CombiningMultiSourceDataProvider -YAGNI: InterleavingMultiSourceDataProvider, CombiningMultiSourceDataProvider +datasets API entry point: + kwargs should be parsed from strings 2 layers up (in the DatasetsAPI) - that's the 'proper' place for that. + but how would it know how/what to parse if it doesn't have access to the classes used in the provider? + Building a giant list by sweeping all possible dprov classes doesn't make sense + For now - I'm burying them in the class __init__s - but I don't like that """ import logging @@ -31,6 +36,31 @@ # ----------------------------------------------------------------------------- base classes +class HasSettings( type ): + """ + Metaclass for data providers that allows defining and inheriting + a dictionary named 'settings'. + + Useful for allowing class level access to expected variable types + passed to class `__init__` functions so they can be parsed from a query string. + """ + # yeah - this is all too acrobatic + def __new__( cls, name, base_classes, attributes ): + settings = {} + # get settings defined in base classes + for base_class in base_classes: + base_settings = getattr( base_class, 'settings', None ) + if base_settings: + settings.update( base_settings ) + # get settings defined in this class + new_settings = attributes.pop( 'settings', None ) + if new_settings: + settings.update( new_settings ) + attributes[ 'settings' ] = settings + return type.__new__( cls, name, base_classes, attributes ) + + +# ----------------------------------------------------------------------------- base classes class DataProvider( object ): """ Base class for all data providers. Data providers: @@ -39,6 +69,12 @@ (c) do not allow write methods (but otherwise implement the other file object interface methods) """ + # a definition of expected types for keyword arguments sent to __init__ + # useful for controlling how query string dictionaries can be parsed into correct types for __init__ + # empty in this base class + __metaclass__ = HasSettings + settings = {} + def __init__( self, source, **kwargs ): """ :param source: the source that this iterator will loop over. @@ -130,13 +166,16 @@ - `num_valid_data_read`: how many data have been returned from `filter`. - `num_data_returned`: how many data has this provider yielded. """ + # not useful here - we don't want functions over the query string + #settings.update({ 'filter_fn': 'function' }) + def __init__( self, source, filter_fn=None, **kwargs ): """ :param filter_fn: a lambda or function that will be passed a datum and return either the (optionally modified) datum or None. """ super( FilteredDataProvider, self ).__init__( source, **kwargs ) - self.filter_fn = filter_fn + self.filter_fn = filter_fn if hasattr( filter_fn, '__call__' ) else None # count how many data we got from the source self.num_data_read = 0 # how many valid data have we gotten from the source @@ -179,6 +218,12 @@ Useful for grabbing sections from a source (e.g. pagination). """ + # define the expected types of these __init__ arguments so they can be parsed out from query strings + settings = { + 'limit' : 'int', + 'offset': 'int' + } + #TODO: may want to squash this into DataProvider def __init__( self, source, offset=0, limit=None, **kwargs ): """ diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/dataproviders/chunk.py --- a/lib/galaxy/datatypes/dataproviders/chunk.py +++ b/lib/galaxy/datatypes/dataproviders/chunk.py @@ -26,6 +26,10 @@ """ MAX_CHUNK_SIZE = 2**16 DEFAULT_CHUNK_SIZE = MAX_CHUNK_SIZE + settings = { + 'chunk_index' : 'int', + 'chunk_size' : 'int' + } #TODO: subclass from LimitedOffsetDataProvider? # see web/framework/base.iterate_file, util/__init__.file_reader, and datatypes.tabular @@ -38,8 +42,8 @@ (gen. in bytes). """ super( ChunkDataProvider, self ).__init__( source, **kwargs ) - self.chunk_size = chunk_size - self.chunk_pos = chunk_index * self.chunk_size + self.chunk_size = int( chunk_size ) + self.chunk_pos = int( chunk_index ) * self.chunk_size def validate_source( self, source ): """ diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/dataproviders/column.py --- a/lib/galaxy/datatypes/dataproviders/column.py +++ b/lib/galaxy/datatypes/dataproviders/column.py @@ -29,6 +29,14 @@ the same number of columns as the number of indeces asked for (even if they are filled with None). """ + settings = { + 'indeces' : 'list:int', + 'column_count' : 'int', + 'column_types' : 'list:str', + 'parse_columns' : 'bool', + 'deliminator' : 'str' + } + def __init__( self, source, indeces=None, column_count=None, column_types=None, parsers=None, parse_columns=True, deliminator='\t', **kwargs ): @@ -91,11 +99,11 @@ # how/whether to parse each column value self.parsers = {} if parse_columns: - self.parsers = self._get_default_parsers() + self.parsers = self.get_default_parsers() # overwrite with user desired parsers self.parsers.update( parsers or {} ) - def _get_default_parsers( self ): + def get_default_parsers( self ): """ Return parser dictionary keyed for each columnar type (as defined in datatypes). @@ -132,7 +140,7 @@ #'gffstrand': # -, +, ?, or '.' for None, etc. } - def _parse_value( self, val, type ): + def parse_value( self, val, type ): """ Attempt to parse and return the given value based on the given type. @@ -153,7 +161,7 @@ return None return val - def _get_column_type( self, index ): + def get_column_type( self, index ): """ Get the column type for the parser from `self.column_types` or `None` if the type is unavailable. @@ -165,18 +173,18 @@ except IndexError, ind_err: return None - def _parse_column_at_index( self, columns, parser_index, index ): + def parse_column_at_index( self, columns, parser_index, index ): """ Get the column type for the parser from `self.column_types` or `None` if the type is unavailable. """ try: - return self._parse_value( columns[ index ], self._get_column_type( parser_index ) ) + return self.parse_value( columns[ index ], self.get_column_type( parser_index ) ) # if a selected index is not within columns, return None except IndexError, index_err: return None - def _parse_columns_from_line( self, line ): + def parse_columns_from_line( self, line ): """ Returns a list of the desired, parsed columns. :param line: the line to parse @@ -188,13 +196,13 @@ selected_indeces = self.selected_column_indeces or list( xrange( len( all_columns ) ) ) parsed_columns = [] for parser_index, column_index in enumerate( selected_indeces ): - parsed_columns.append( self._parse_column_at_index( all_columns, parser_index, column_index ) ) + parsed_columns.append( self.parse_column_at_index( all_columns, parser_index, column_index ) ) return parsed_columns def __iter__( self ): parent_gen = super( ColumnarDataProvider, self ).__iter__() for line in parent_gen: - columns = self._parse_columns_from_line( line ) + columns = self.parse_columns_from_line( line ) yield columns #TODO: implement column filters here and not below - flatten hierarchy @@ -223,6 +231,10 @@ .. note: that the subclass constructors are passed kwargs - so they're params (limit, offset, etc.) are also applicable here. """ + settings = { + 'column_names' : 'list:str', + } + def __init__( self, source, column_names=None, **kwargs ): """ :param column_names: an ordered list of strings that will be used as the keys diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/dataproviders/dataset.py --- a/lib/galaxy/datatypes/dataproviders/dataset.py +++ b/lib/galaxy/datatypes/dataproviders/dataset.py @@ -141,7 +141,7 @@ """ # metadata columns are 1-based indeces column = getattr( self.dataset.metadata, name ) - return ( column - 1 ) if isinstance( column, int ) else None + return ( column - 1 ) if ( isinstance( column, int ) and column > 0 ) else None def get_genomic_region_indeces( self, check=False ): """ @@ -271,6 +271,12 @@ """ # dictionary keys when named_columns=True COLUMN_NAMES = [ 'chrom', 'start', 'end' ] + settings = { + 'chrom_column' : 'int', + 'start_column' : 'int', + 'end_column' : 'int', + 'named_columns' : 'bool', + } def __init__( self, dataset, chrom_column=None, start_column=None, end_column=None, named_columns=False, **kwargs ): """ @@ -333,6 +339,14 @@ 'chrom', 'start', 'end' (and 'strand' and 'name' if available). """ COLUMN_NAMES = [ 'chrom', 'start', 'end', 'strand', 'name' ] + settings = { + 'chrom_column' : 'int', + 'start_column' : 'int', + 'end_column' : 'int', + 'strand_column' : 'int', + 'name_column' : 'int', + 'named_columns' : 'bool', + } def __init__( self, dataset, chrom_column=None, start_column=None, end_column=None, strand_column=None, name_column=None, named_columns=False, **kwargs ): @@ -349,25 +363,40 @@ dataset_source = DatasetDataProvider( dataset ) # get genomic indeces and add strand and name + self.column_names = [] + indeces = [] + #TODO: this is sort of involved and oogly if chrom_column == None: chrom_column = dataset_source.get_metadata_column_index_by_name( 'chromCol' ) + if chrom_column != None: + self.column_names.append( 'chrom' ) + indeces.append( chrom_column ) if start_column == None: start_column = dataset_source.get_metadata_column_index_by_name( 'startCol' ) + if start_column != None: + self.column_names.append( 'start' ) + indeces.append( start_column ) if end_column == None: end_column = dataset_source.get_metadata_column_index_by_name( 'endCol' ) + if end_column != None: + self.column_names.append( 'end' ) + indeces.append( end_column ) if strand_column == None: strand_column = dataset_source.get_metadata_column_index_by_name( 'strandCol' ) + if strand_column != None: + self.column_names.append( 'strand' ) + indeces.append( strand_column ) if name_column == None: name_column = dataset_source.get_metadata_column_index_by_name( 'nameCol' ) - indeces = [ chrom_column, start_column, end_column, strand_column, name_column ] + if name_column != None: + self.column_names.append( 'name' ) + indeces.append( name_column ) + kwargs.update({ 'indeces' : indeces }) - if not kwargs.get( 'column_types', None ): kwargs.update({ 'column_types' : dataset_source.get_metadata_column_types( indeces=indeces ) }) self.named_columns = named_columns - if self.named_columns: - self.column_names = self.COLUMN_NAMES super( IntervalDataProvider, self ).__init__( dataset_source, **kwargs ) @@ -390,6 +419,10 @@ sequence: <joined lines of nucleotide/amino data> } """ + settings = { + 'ids' : 'list:str', + } + def __init__( self, source, ids=None, **kwargs ): """ :param ids: optionally return only ids (and sequences) that are in this list. @@ -419,6 +452,10 @@ sequence: <joined lines of nucleotide/amino data> } """ + settings = { + 'ids' : 'list:str', + } + def __init__( self, source, ids=None, **kwargs ): """ :param ids: optionally return only ids (and sequences) that are in this list. @@ -445,6 +482,10 @@ Class that returns chrom, pos, data from a wiggle source. """ COLUMN_NAMES = [ 'chrom', 'pos', 'value' ] + settings = { + 'named_columns' : 'bool', + 'column_names' : 'list:str', + } def __init__( self, source, named_columns=False, column_names=None, **kwargs ): """ @@ -483,6 +524,10 @@ Class that returns chrom, pos, data from a wiggle source. """ COLUMN_NAMES = [ 'chrom', 'pos', 'value' ] + settings = { + 'named_columns' : 'bool', + 'column_names' : 'list:str', + } def __init__( self, source, chrom, start, end, named_columns=False, column_names=None, **kwargs ): """ diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/dataproviders/decorators.py --- a/lib/galaxy/datatypes/dataproviders/decorators.py +++ b/lib/galaxy/datatypes/dataproviders/decorators.py @@ -87,17 +87,40 @@ # log.debug( '\t\t ', fn.__doc__ ) return cls -def dataprovider_factory( name ): +def dataprovider_factory( name, settings=None ): """ - Wraps a class method and marks it as a dataprovider factory. + Wraps a class method and marks it as a dataprovider factory and creates a + function to parse query strings to __init__ arguments as the + `parse_query_string_settings` attribute of the factory function. + + An example use of the `parse_query_string_settings`: + ..example:: + kwargs = dataset.datatype.dataproviders[ provider ].parse_query_string_settings( query_kwargs ) + return list( dataset.datatype.dataprovider( dataset, provider, **kwargs ) ) :param name: what name/key to register the factory under in `cls.dataproviders` - :param type: any hashable var + :type name: any hashable var + :param settings: dictionary containing key/type pairs for parsing query strings + to __init__ arguments + :type settings: dictionary """ + #TODO:?? use *args for settings allowing mulitple dictionaries + # make a function available through the name->provider dispatch to parse query strings + # callable like: + # settings_dict = dataproviders[ provider_name ].parse_query_string_settings( query_kwargs ) + #TODO: ugh - overly complicated but the best I could think of + def parse_query_string_settings( query_kwargs ): + return _parse_query_string_settings( query_kwargs, settings ) + #log.debug( 'dataprovider:', name ) def named_dataprovider_factory( func ): #log.debug( 'named_dataprovider_factory:', name, '->', func.__name__ ) setattr( func, _DATAPROVIDER_METHOD_NAME_KEY, name ) + + setattr( func, 'parse_query_string_settings', parse_query_string_settings ) + setattr( func, 'settings', settings ) + #TODO: I want a way to inherit settings from the previous provider( this_name ) instead of defining over and over + #log.debug( '\t setting:', getattr( func, _DATAPROVIDER_METHOD_NAME_KEY ) ) @wraps( func ) def wrapped_dataprovider_factory( self, *args, **kwargs ): @@ -105,3 +128,38 @@ return func( self, *args, **kwargs ) return wrapped_dataprovider_factory return named_dataprovider_factory + +def _parse_query_string_settings( query_kwargs, settings=None ): + """ + Parse the values in `query_kwargs` from strings to the proper types + listed in the same key in `settings`. + """ + def list_from_query_string( s ): + # assume csv + return s.split( ',' ) + + parsers = { + 'int' : int, + 'float' : float, + 'bool' : bool, + 'list:str' : lambda s: list_from_query_string( s ), + 'list:int' : lambda s: [ int( i ) for i in list_from_query_string( s ) ], + } + settings = settings or {} + # yay! yet another set of query string parsers! <-- sarcasm + # work through the keys in settings finding matching keys in query_kwargs + # if found in both, get the expected/needed type from settings and store the new parsed value + # if we can't parse it (no parser, bad value), delete the key from query_kwargs so the provider will use the defaults + for key in settings: + if key in query_kwargs: + #TODO: this would be the place to sanitize any strings + query_value = query_kwargs[ key ] + needed_type = settings[ key ] + try: + query_kwargs[ key ] = parsers[ needed_type ]( query_value ) + except ( KeyError, ValueError ): + del query_kwargs[ key ] + + #TODO:?? do we want to remove query_kwarg entries NOT in settings? + return query_kwargs + diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/dataproviders/line.py --- a/lib/galaxy/datatypes/dataproviders/line.py +++ b/lib/galaxy/datatypes/dataproviders/line.py @@ -27,6 +27,12 @@ to return. """ DEFAULT_COMMENT_CHAR = '#' + settings = { + 'string_lines' : 'bool', + 'provide_blank' : 'bool', + 'comment_char' : 'str', + } + def __init__( self, source, strip_lines=True, provide_blank=False, comment_char=DEFAULT_COMMENT_CHAR, **kwargs ): """ :param strip_lines: remove whitespace from the beginning an ending @@ -78,6 +84,11 @@ .. note:: the regex matches are effectively OR'd (if **any** regex matches the line it is considered valid and will be provided). """ + settings = { + 'regex_list' : 'list:str', + 'invert' : 'bool', + } + def __init__( self, source, regex_list=None, invert=False, **kwargs ): """ :param regex_list: list of strings or regular expression strings that will diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/interval.py --- a/lib/galaxy/datatypes/interval.py +++ b/lib/galaxy/datatypes/interval.py @@ -334,20 +334,24 @@ return None # ------------- Dataproviders - @dataproviders.decorators.dataprovider_factory( 'genomic-region' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_dataprovider( self, dataset, **settings ): return dataproviders.dataset.GenomicRegionDataProvider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region-map' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region-map', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_map_dataprovider( self, dataset, **settings ): settings[ 'named_columns' ] = True return self.genomic_region_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'interval' ) + @dataproviders.decorators.dataprovider_factory( 'interval', + dataproviders.dataset.IntervalDataProvider.settings ) def interval_dataprovider( self, dataset, **settings ): return dataproviders.dataset.IntervalDataProvider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'interval-map' ) + @dataproviders.decorators.dataprovider_factory( 'interval-map', + dataproviders.dataset.IntervalDataProvider.settings ) def interval_map_dataprovider( self, dataset, **settings ): settings[ 'named_columns' ] = True return self.interval_dataprovider( dataset, **settings ) @@ -809,20 +813,24 @@ # ------------- Dataproviders # redefine bc super is Tabular - @dataproviders.decorators.dataprovider_factory( 'genomic-region' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_dataprovider( self, dataset, **settings ): return dataproviders.dataset.GenomicRegionDataProvider( dataset, 0, 3, 4, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region-map' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region-map', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_map_dataprovider( self, dataset, **settings ): settings[ 'named_columns' ] = True return self.genomic_region_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'interval' ) + @dataproviders.decorators.dataprovider_factory( 'interval', + dataproviders.dataset.IntervalDataProvider.settings ) def interval_dataprovider( self, dataset, **settings ): return dataproviders.dataset.IntervalDataProvider( dataset, 0, 3, 4, 6, 2, **settings ) - @dataproviders.decorators.dataprovider_factory( 'interval-map' ) + @dataproviders.decorators.dataprovider_factory( 'interval-map', + dataproviders.dataset.IntervalDataProvider.settings ) def interval_map_dataprovider( self, dataset, **settings ): settings[ 'named_columns' ] = True return self.interval_dataprovider( dataset, **settings ) @@ -1193,12 +1201,12 @@ return resolution # ------------- Dataproviders - @dataproviders.decorators.dataprovider_factory( 'wiggle' ) + @dataproviders.decorators.dataprovider_factory( 'wiggle', dataproviders.dataset.WiggleDataProvider.settings ) def wiggle_dataprovider( self, dataset, **settings ): dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.dataset.WiggleDataProvider( dataset_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'wiggle-map' ) + @dataproviders.decorators.dataprovider_factory( 'wiggle-map', dataproviders.dataset.WiggleDataProvider.settings ) def wiggle_map_dataprovider( self, dataset, **settings ): dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) settings[ 'named_columns' ] = True diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/sequence.py --- a/lib/galaxy/datatypes/sequence.py +++ b/lib/galaxy/datatypes/sequence.py @@ -15,8 +15,6 @@ from galaxy import util from sniff import * -from galaxy.datatypes import dataproviders - import pkg_resources pkg_resources.require("simplejson") import simplejson @@ -399,15 +397,6 @@ f.close() _count_split = classmethod(_count_split) - def provider( self, dataset, data_format, **settings ): - from galaxy.dataproviders import dataset as dataset_providers - - if data_format == 'id_seq': - source = dataset_providers.DatasetDataProvider( dataset ) - return dataset_providers.FastaDataProvider( source, **settings ) - - return super( Fasta, self ).provider( dataset, data_format, **settings ) - class csFasta( Sequence ): """ Class representing the SOLID Color-Space sequence ( csfasta ) """ diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/datatypes/tabular.py --- a/lib/galaxy/datatypes/tabular.py +++ b/lib/galaxy/datatypes/tabular.py @@ -345,26 +345,25 @@ return vizs # ------------- Dataproviders - @dataproviders.decorators.dataprovider_factory( 'column' ) + @dataproviders.decorators.dataprovider_factory( 'column', dataproviders.column.ColumnarDataProvider.settings ) def column_dataprovider( self, dataset, **settings ): """Uses column settings that are passed in""" - print 'Tabular.comment_char:', settings.get( 'comment_char', None ) - dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.column.ColumnarDataProvider( dataset_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'dataset-column' ) + @dataproviders.decorators.dataprovider_factory( 'dataset-column', + dataproviders.column.ColumnarDataProvider.settings ) def dataset_column_dataprovider( self, dataset, **settings ): """Attempts to get column settings from dataset.metadata""" return dataproviders.dataset.DatasetColumnarDataProvider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'map' ) + @dataproviders.decorators.dataprovider_factory( 'map', dataproviders.column.MapDataProvider.settings ) def map_dataprovider( self, dataset, **settings ): """Uses column settings that are passed in""" dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) return dataproviders.column.MapDataProvider( dataset_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'dataset-map' ) + @dataproviders.decorators.dataprovider_factory( 'dataset-map', dataproviders.column.MapDataProvider.settings ) def dataset_map_dataprovider( self, dataset, **settings ): """Attempts to get column settings from dataset.metadata""" return dataproviders.dataset.DatasetMapDataProvider( dataset, **settings ) @@ -502,55 +501,58 @@ # ------------- Dataproviders # sam does not use '#' to indicate comments/headers - we need to strip out those headers from the std. providers #TODO:?? seems like there should be an easier way to do this - metadata.comment_char? - @dataproviders.decorators.dataprovider_factory( 'line' ) + @dataproviders.decorators.dataprovider_factory( 'line', dataproviders.line.FilteredLineDataProvider.settings ) def line_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return super( Sam, self ).line_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'regex-line' ) + @dataproviders.decorators.dataprovider_factory( 'regex-line', dataproviders.line.RegexLineDataProvider.settings ) def regex_line_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return super( Sam, self ).regex_line_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'column' ) + @dataproviders.decorators.dataprovider_factory( 'column', dataproviders.column.ColumnarDataProvider.settings ) def column_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return super( Sam, self ).column_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'dataset-column' ) + @dataproviders.decorators.dataprovider_factory( 'dataset-column', + dataproviders.column.ColumnarDataProvider.settings ) def dataset_column_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return super( Sam, self ).dataset_column_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'map' ) + @dataproviders.decorators.dataprovider_factory( 'map', dataproviders.column.MapDataProvider.settings ) def map_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return super( Sam, self ).map_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'dataset-map' ) + @dataproviders.decorators.dataprovider_factory( 'dataset-map', dataproviders.column.MapDataProvider.settings ) def dataset_map_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return super( Sam, self ).dataset_map_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'header' ) + @dataproviders.decorators.dataprovider_factory( 'header', dataproviders.line.RegexLineDataProvider.settings ) def header_dataprovider( self, dataset, **settings ): dataset_source = dataproviders.dataset.DatasetDataProvider( dataset ) headers_source = dataproviders.line.RegexLineDataProvider( dataset_source, regex_list=[ '^@' ] ) return dataproviders.line.RegexLineDataProvider( headers_source, **settings ) - @dataproviders.decorators.dataprovider_factory( 'id-seq-qual' ) + @dataproviders.decorators.dataprovider_factory( 'id-seq-qual', map_dataprovider.settings ) def id_seq_qual_dataprovider( self, dataset, **settings ): # provided as an example of a specified column map (w/o metadata) settings[ 'indeces' ] = [ 0, 9, 10 ] settings[ 'column_names' ] = [ 'id', 'seq', 'qual' ] return self.map_dataprovider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return dataproviders.dataset.GenomicRegionDataProvider( dataset, 2, 3, 3, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region-map' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region-map', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_map_dataprovider( self, dataset, **settings ): settings[ 'comment_char' ] = '@' return dataproviders.dataset.GenomicRegionDataProvider( dataset, 2, 3, 3, True, **settings ) @@ -621,11 +623,13 @@ return False # ------------- Dataproviders - @dataproviders.decorators.dataprovider_factory( 'genomic-region' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_dataprovider( self, dataset, **settings ): return dataproviders.dataset.GenomicRegionDataProvider( dataset, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region-map' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region-map', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_map_dataprovider( self, dataset, **settings ): settings[ 'named_columns' ] = True return self.genomic_region_dataprovider( dataset, **settings ) @@ -668,11 +672,13 @@ dataset.metadata.sample_names = line.split()[ 9: ] # ------------- Dataproviders - @dataproviders.decorators.dataprovider_factory( 'genomic-region' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_dataprovider( self, dataset, **settings ): return dataproviders.dataset.GenomicRegionDataProvider( dataset, 0, 1, 1, **settings ) - @dataproviders.decorators.dataprovider_factory( 'genomic-region-map' ) + @dataproviders.decorators.dataprovider_factory( 'genomic-region-map', + dataproviders.dataset.GenomicRegionDataProvider.settings ) def genomic_region_map_dataprovider( self, dataset, **settings ): settings[ 'named_columns' ] = True return self.genomic_region_dataprovider( dataset, **settings ) diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/visualization/data_providers/registry.py --- a/lib/galaxy/visualization/data_providers/registry.py +++ b/lib/galaxy/visualization/data_providers/registry.py @@ -32,7 +32,7 @@ "bigwig": genome.BigWigDataProvider, "bigbed": genome.BigBedDataProvider, - "column": ColumnDataProvider + "column_with_stats": ColumnDataProvider } def get_data_provider( self, trans, name=None, source='data', raw=False, original_dataset=None ): diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/visualization/registry.py --- a/lib/galaxy/visualization/registry.py +++ b/lib/galaxy/visualization/registry.py @@ -15,22 +15,27 @@ log = logging.getLogger( __name__ ) __TODO__ = """ - BUGS: - anon users clicking a viz link gets 'must be' msg in galaxy_main (w/ masthead) - should not show visualizations (no icon)? - newick files aren't being sniffed prop? - datatype is txt +BUGS: + anon users clicking a viz link gets 'must be' msg in galaxy_main (w/ masthead) + should not show visualizations (no icon)? + newick files aren't being sniffed prop? - datatype is txt - have parsers create objects instead of dicts - allow data_sources with no model_class but have tests (isAdmin, etc.) - maybe that's an instance of User model_class? - some confused vocabulary in docs, var names - tests: - anding, grouping, not - data_sources: - lists of - add description element to visualization. +have parsers create objects instead of dicts +allow data_sources with no model_class but have tests (isAdmin, etc.) + maybe that's an instance of User model_class? +some confused vocabulary in docs, var names +tests: + anding, grouping, not +data_sources: + lists of +add description element to visualization. + +TESTS to add: + has dataprovider + user is admin """ +# ------------------------------------------------------------------- the registry class VisualizationsRegistry( object ): """ Main responsibilities are: @@ -93,6 +98,12 @@ """ self.listings = VisualizationsConfigParser.parse( self.configuration_filepath ) + #TODO: def get_visualization( self, trans, visualization_name, target_object ): + # """ + # Is the visualization with the given `visualization_name` applicable + # to the `target_object`? + # """ + # -- building links to visualizations from objects -- def get_visualizations( self, trans, target_object ): """ @@ -151,10 +162,11 @@ # convert datatypes to their actual classes (for use with isinstance) test_result = trans.app.datatypes_registry.get_datatype_class_by_name( test_result ) if not test_result: - # warn if can't find class, but continue + # warn if can't find class, but continue (with other tests) log.warn( 'visualizations_registry cannot find class (%s) for applicability test', test_result ) continue + #NOTE: tests are OR'd, if any test passes - the visualization can be applied if test_fn( target_object, test_result ): #log.debug( 'test passed' ) return True diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 lib/galaxy/webapps/galaxy/api/datasets.py --- a/lib/galaxy/webapps/galaxy/api/datasets.py +++ b/lib/galaxy/webapps/galaxy/api/datasets.py @@ -6,6 +6,7 @@ from galaxy.web.base.controller import BaseAPIController, UsesVisualizationMixin, UsesHistoryDatasetAssociationMixin from galaxy.web.base.controller import UsesHistoryMixin from galaxy.web.framework.helpers import is_true +from galaxy.datatypes import dataproviders import logging log = logging.getLogger( __name__ ) @@ -217,10 +218,24 @@ return msg registry = trans.app.data_provider_registry + # allow the caller to specifiy which provider is used - if provider and provider in registry.dataset_type_name_to_data_provider: - data_provider = registry.dataset_type_name_to_data_provider[ provider ]( dataset ) - # or have it look up by datatype + # pulling from the original providers if possible, then the new providers + if provider: + if provider in registry.dataset_type_name_to_data_provider: + data_provider = registry.dataset_type_name_to_data_provider[ provider ]( dataset ) + + elif dataset.datatype.has_dataprovider( provider ): + kwargs = dataset.datatype.dataproviders[ provider ].parse_query_string_settings( kwargs ) + # use dictionary to allow more than the data itself to be returned (data totals, other meta, etc.) + return { + 'data': list( dataset.datatype.dataprovider( dataset, provider, **kwargs ) ) + } + + else: + raise dataproviders.exceptions.NoProviderAvailable( dataset.datatype, provider ) + + # no provider name: look up by datatype else: data_provider = registry.get_data_provider( trans, raw=True, original_dataset=dataset ) diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 static/scripts/mvc/visualizations/scatterplotControlForm.js --- a/static/scripts/mvc/visualizations/scatterplotControlForm.js +++ b/static/scripts/mvc/visualizations/scatterplotControlForm.js @@ -562,7 +562,7 @@ var params = { data_type : 'raw_data', - provider : 'column', + provider : 'column_with_stats', columns : '[' + columns + ']' }; this.log( '\t data settings (url params):', params ); diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 static/scripts/packed/mvc/data.js --- a/static/scripts/packed/mvc/data.js +++ b/static/scripts/packed/mvc/data.js @@ -1,1 +1,1 @@ -define(["libs/backbone/backbone-relational"],function(){var d=Backbone.RelationalModel.extend({});var e=Backbone.RelationalModel.extend({defaults:{id:"",type:"",name:"",hda_ldda:"hda",metadata:null},initialize:function(){this._set_metadata();this.on("change",this._set_metadata,this)},_set_metadata:function(){var i=new d();_.each(_.keys(this.attributes),function(j){if(j.indexOf("metadata_")===0){var l=j.split("metadata_")[1];i.set(l,this.attributes[j]);delete this.attributes[j]}},this);this.set("metadata",i,{silent:true})},get_metadata:function(i){return this.attributes.metadata.get(i)},urlRoot:galaxy_paths.get("datasets_url")});var c=e.extend({defaults:_.extend({},e.prototype.defaults,{chunk_url:null,first_data_chunk:null,chunk_index:-1,at_eof:false}),initialize:function(i){e.prototype.initialize.call(this);this.attributes.chunk_index=(this.attributes.first_data_chunk?1:0)},get_next_chunk:function(){if(this.attributes.at_eof){return null}var i=this,j=$.Deferred();$.getJSON(this.attributes.chunk_url,{chunk:i.attributes.chunk_index++}).success(function(k){var l;if(k.ck_data!==""){l=k}else{i.attributes.at_eof=true;l=null}j.resolve(l)});return j}});var g=Backbone.Collection.extend({model:e});var f=Backbone.View.extend({initialize:function(i){(new b(i)).render()},render:function(){var m=$("<table/>").attr({id:"content_table",cellpadding:0});this.$el.append(m);var i=this.model.get_metadata("column_names");if(i){m.append("<tr><th>"+i.join("</th><th>")+"</th></tr>")}var k=this.model.get("first_data_chunk");if(k){this._renderChunk(k)}var j=this,n=_.find(this.$el.parents(),function(o){return $(o).css("overflow")==="auto"}),l=false;if(!n){n=window}n=$(n);n.scroll(function(){if(!l&&(j.$el.height()-n.scrollTop()-n.height()<=0)){l=true;$.when(j.model.get_next_chunk()).then(function(o){if(o){j._renderChunk(o);l=false}})}});$("#loading_indicator").ajaxStart(function(){$(this).show()}).ajaxStop(function(){$(this).hide()})},_renderCell:function(k,i,l){var j=this.model.get_metadata("column_types");if(l!==undefined){return $("<td>").attr("colspan",l).addClass("stringalign").text(k)}else{if(j[i]==="str"||j==="list"){return $("<td>").addClass("stringalign").text(k)}else{return $("<td>").text(k)}}},_renderRow:function(i){var j=i.split("\t"),l=$("<tr>"),k=this.model.get_metadata("columns");if(j.length===k){_.each(j,function(n,m){l.append(this._renderCell(n,m))},this)}else{if(j.length>k){_.each(j.slice(0,k-1),function(n,m){l.append(this._renderCell(n,m))},this);l.append(this._renderCell(j.slice(k-1).join("\t"),k-1))}else{if(k>5&&j.length===k-1){_.each(j,function(n,m){l.append(this._renderCell(n,m))},this);l.append($("<td>"))}else{l.append(this._renderCell(i,0,k))}}}return l},_renderChunk:function(i){var j=this.$el.find("table");_.each(i.ck_data.split("\n"),function(k,l){j.append(this._renderRow(k))},this)}});var b=Backbone.View.extend({col:{chrom:null,start:null,end:null},url_viz:null,dataset_id:null,genome_build:null,initialize:function(i){var j=i.model.attributes.metadata.attributes;if(typeof j.chromCol==="undefined"||typeof j.startCol==="undefined"||typeof j.endCol==="undefined"){console.log("TabularButtonTrackster : Metadata for column identification is missing.")}else{this.col.chrom=j.chromCol-1;this.col.start=j.startCol-1;this.col.end=j.endCol-1}if(this.col.chrom===null){return}if(typeof i.model.attributes.id==="undefined"){console.log("TabularButtonTrackster : Dataset identification is missing.")}else{this.dataset_id=i.model.attributes.id}if(typeof i.model.attributes.url_viz==="undefined"){console.log("TabularButtonTrackster : Url for visualization controller is missing.")}else{this.url_viz=i.model.attributes.url_viz}if(typeof i.model.attributes.genome_build!=="undefined"){this.genome_build=i.model.attributes.genome_build}},events:{"mouseover tr":"btn_viz_show",mouseleave:"btn_viz_hide"},btn_viz_show:function(m){if(this.col.chrom===null){return}var q=$(m.target).parent();var n=q.children().eq(this.col.chrom).html();var i=q.children().eq(this.col.start).html();var k=q.children().eq(this.col.end).html();if(n!==""&&i!==""&&k!==""){var p={dataset_id:this.dataset_id,gene_region:n+":"+i+"-"+k};var l=q.offset();var j=l.left-10;var o=l.top;$("#btn_viz").css({position:"fixed",top:o+"px",left:j+"px"});$("#btn_viz").off("click");$("#btn_viz").click(this.create_trackster_action(this.url_viz,p,this.genome_build));$("#btn_viz").show()}},btn_viz_hide:function(){$("#btn_viz").hide()},create_trackster_action:function(i,k,j){return function(){var l={};if(j){l["f-dbkey"]=j}$.ajax({url:i+"/list_tracks?"+$.param(l),dataType:"html",error:function(){alert(("Could not add this dataset to browser")+".")},success:function(m){var n=window.parent;n.show_modal(("View Data in a New or Saved Visualization"),"",{Cancel:function(){n.hide_modal()},"View in saved visualization":function(){n.show_modal(("Add Data to Saved Visualization"),m,{Cancel:function(){n.hide_modal()},"Add to visualization":function(){$(n.document).find("input[name=id]:checked").each(function(){var o=$(this).val();k.id=o;n.location=i+"/trackster?"+$.param(k)})}})},"View in new visualization":function(){n.location=i+"/trackster?"+$.param(k)}})}});return false}},render:function(){var i=new IconButtonView({model:new IconButton({title:"Visualize",icon_class:"chart_curve",id:"btn_viz"})});this.$el.append(i.render().$el);$("#btn_viz").hide()}});var a=function(l,j,m,i){var k=new j({model:new l(m)});k.render();if(i){i.append(k.$el)}return k};var h=function(k,i){var j=$("<div/>").appendTo(i);return new f({el:j,model:new c(k)}).render()};return{Dataset:e,TabularDataset:c,DatasetCollection:g,TabularDatasetChunkedView:f,createTabularDatasetChunkedView:h}}); \ No newline at end of file +define(["libs/backbone/backbone-relational"],function(){var d=Backbone.RelationalModel.extend({});var e=Backbone.RelationalModel.extend({defaults:{id:"",type:"",name:"",hda_ldda:"hda",metadata:null},initialize:function(){this._set_metadata();this.on("change",this._set_metadata,this)},_set_metadata:function(){var i=new d();_.each(_.keys(this.attributes),function(j){if(j.indexOf("metadata_")===0){var l=j.split("metadata_")[1];i.set(l,this.attributes[j]);delete this.attributes[j]}},this);this.set("metadata",i,{silent:true})},get_metadata:function(i){return this.attributes.metadata.get(i)},urlRoot:galaxy_paths.get("datasets_url")});var c=e.extend({defaults:_.extend({},e.prototype.defaults,{chunk_url:null,first_data_chunk:null,chunk_index:-1,at_eof:false}),initialize:function(i){e.prototype.initialize.call(this);this.attributes.chunk_index=(this.attributes.first_data_chunk?1:0)},get_next_chunk:function(){if(this.attributes.at_eof){return null}var i=this,j=$.Deferred();$.getJSON(this.attributes.chunk_url,{chunk:i.attributes.chunk_index++}).success(function(k){var l;if(k.ck_data!==""){l=k}else{i.attributes.at_eof=true;l=null}j.resolve(l)});return j}});var g=Backbone.Collection.extend({model:e});var f=Backbone.View.extend({initialize:function(i){(new b(i)).render()},render:function(){var m=$("<table/>").attr({id:"content_table",cellpadding:0});this.$el.append(m);var i=this.model.get_metadata("column_names");if(i){m.append("<tr><th>"+i.join("</th><th>")+"</th></tr>")}var k=this.model.get("first_data_chunk");if(k){this._renderChunk(k)}var j=this,n=_.find(this.$el.parents(),function(o){return $(o).css("overflow")==="auto"}),l=false;if(!n){n=window}n=$(n);n.scroll(function(){if(!l&&(j.$el.height()-n.scrollTop()-n.height()<=0)){l=true;$.when(j.model.get_next_chunk()).then(function(o){if(o){j._renderChunk(o);l=false}})}});$("#loading_indicator").ajaxStart(function(){$(this).show()}).ajaxStop(function(){$(this).hide()})},_renderCell:function(k,i,l){var j=this.model.get_metadata("column_types");if(l!==undefined){return $("<td>").attr("colspan",l).addClass("stringalign").text(k)}else{if(j[i]==="str"||j==="list"){return $("<td>").addClass("stringalign").text(k)}else{return $("<td>").text(k)}}},_renderRow:function(i){var j=i.split("\t"),l=$("<tr>"),k=this.model.get_metadata("columns");if(j.length===k){_.each(j,function(n,m){l.append(this._renderCell(n,m))},this)}else{if(j.length>k){_.each(j.slice(0,k-1),function(n,m){l.append(this._renderCell(n,m))},this);l.append(this._renderCell(j.slice(k-1).join("\t"),k-1))}else{if(k>5&&j.length===k-1){_.each(j,function(n,m){l.append(this._renderCell(n,m))},this);l.append($("<td>"))}else{l.append(this._renderCell(i,0,k))}}}return l},_renderChunk:function(i){var j=this.$el.find("table");_.each(i.ck_data.split("\n"),function(k,l){j.append(this._renderRow(k))},this)}});var b=Backbone.View.extend({col:{chrom:null,start:null,end:null},url_viz:null,dataset_id:null,genome_build:null,initialize:function(i){var j=i.model.attributes.metadata.attributes;if(typeof j.chromCol==="undefined"||typeof j.startCol==="undefined"||typeof j.endCol==="undefined"){console.log("TabularButtonTrackster : Metadata for column identification is missing.")}else{this.col.chrom=j.chromCol-1;this.col.start=j.startCol-1;this.col.end=j.endCol-1}if(this.col.chrom===null){return}if(typeof i.model.attributes.id==="undefined"){console.log("TabularButtonTrackster : Dataset identification is missing.")}else{this.dataset_id=i.model.attributes.id}if(typeof i.model.attributes.url_viz==="undefined"){console.log("TabularButtonTrackster : Url for visualization controller is missing.")}else{this.url_viz=i.model.attributes.url_viz}if(typeof i.model.attributes.genome_build!=="undefined"){this.genome_build=i.model.attributes.genome_build}},events:{"mouseover tr":"btn_viz_show",mouseleave:"btn_viz_hide"},btn_viz_show:function(m){if(this.col.chrom===null){return}var q=$(m.target).parent();var n=q.children().eq(this.col.chrom).html();var i=q.children().eq(this.col.start).html();var k=q.children().eq(this.col.end).html();if(n!==""&&i!==""&&k!==""){var p={dataset_id:this.dataset_id,gene_region:n+":"+i+"-"+k};var l=q.offset();var j=l.left-10;var o=l.top;$("#btn_viz").css({position:"fixed",top:o+"px",left:j+"px"});$("#btn_viz").off("click");$("#btn_viz").click(this.create_trackster_action(this.url_viz,p,this.genome_build));$("#btn_viz").show()}},btn_viz_hide:function(){$("#btn_viz").hide()},create_trackster_action:function(i,k,j){return function(){var l={};if(j){l["f-dbkey"]=j}$.ajax({url:i+"/list_tracks?"+$.param(l),dataType:"html",error:function(){alert(("Could not add this dataset to browser")+".")},success:function(m){var n=window.parent;n.show_modal(("View Data in a New or Saved Visualization"),"",{Cancel:function(){n.hide_modal()},"View in saved visualization":function(){n.show_modal(("Add Data to Saved Visualization"),m,{Cancel:function(){n.hide_modal()},"Add to visualization":function(){$(n.document).find("input[name=id]:checked").each(function(){var o=$(this).val();k.id=o;n.frame_manager.frame_new({title:"Trackster",type:"url",content:i+"/trackster?"+$.param(k)});n.hide_modal()})}})},"View in new visualization":function(){var o=i+"/trackster?"+$.param(k);n.frame_manager.frame_new({title:"Trackster",type:"url",content:o});n.hide_modal()}})}});return false}},render:function(){var i=new IconButtonView({model:new IconButton({title:"Visualize",icon_class:"chart_curve",id:"btn_viz"})});this.$el.append(i.render().$el);$("#btn_viz").hide()}});var a=function(l,j,m,i){var k=new j({model:new l(m)});k.render();if(i){i.append(k.$el)}return k};var h=function(k,i){var j=$("<div/>").appendTo(i);return new f({el:j,model:new c(k)}).render()};return{Dataset:e,TabularDataset:c,DatasetCollection:g,TabularDatasetChunkedView:f,createTabularDatasetChunkedView:h}}); \ No newline at end of file diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 static/scripts/packed/mvc/dataset/hda-base.js --- a/static/scripts/packed/mvc/dataset/hda-base.js +++ b/static/scripts/packed/mvc/dataset/hda-base.js @@ -1,1 +1,1 @@ -var HDABaseView=Backbone.View.extend(LoggableMixin).extend({tagName:"div",className:"historyItemContainer",initialize:function(a){if(a.logger){this.logger=this.model.logger=a.logger}this.log(this+".initialize:",a);this.defaultPrimaryActionButtonRenderers=[this._render_showParamsButton];if(!a.urlTemplates){throw ("HDAView needs urlTemplates on initialize")}this.urlTemplates=a.urlTemplates;this.expanded=a.expanded||false;this.model.bind("change",function(c,d){var b=_.without(_.keys(d.changes),"display_apps","display_types");if(b.length){this.render()}else{if(this.expanded){this._render_displayApps()}}},this)},render:function(){var b=this,e=this.model.get("id"),c=this.model.get("state"),a=$("<div/>").attr("id","historyItem-"+e),d=(this.$el.children().size()===0);this.$el.attr("id","historyItemContainer-"+e);this.urls=this._renderUrls(this.urlTemplates,this.model.toJSON());a.addClass("historyItemWrapper").addClass("historyItem").addClass("historyItem-"+c);a.append(this._render_warnings());a.append(this._render_titleBar());this._setUpBehaviors(a);this.body=$(this._render_body());a.append(this.body);this.$el.fadeOut("fast",function(){b.$el.children().remove();b.$el.append(a).fadeIn("fast",function(){b.log(b+" rendered:",b.$el);var f="rendered";if(d){f+=":initial"}else{if(b.model.inReadyState()){f+=":ready"}}b.trigger(f)})});return this},_renderUrls:function(d,a){var b=this,c={};_.each(d,function(e,f){if(_.isObject(e)){c[f]=b._renderUrls(e,a)}else{if(f==="meta_download"){c[f]=b._renderMetaDownloadUrls(e,a)}else{try{c[f]=_.template(e,a)}catch(g){throw (b+"._renderUrls error: "+g+"\n rendering:"+e+"\n with "+JSON.stringify(a))}}}});return c},_renderMetaDownloadUrls:function(b,a){return _.map(a.meta_files,function(c){return{url:_.template(b,{id:a.id,file_type:c.file_type}),file_type:c.file_type}})},_setUpBehaviors:function(a){a=a||this.$el;make_popup_menus(a);a.find(".tooltip").tooltip({placement:"bottom"})},_render_warnings:function(){return $(jQuery.trim(HDABaseView.templates.messages(this.model.toJSON())))},_render_titleBar:function(){var a=$('<div class="historyItemTitleBar" style="overflow: hidden"></div>');a.append(this._render_titleButtons());a.append('<span class="state-icon"></span>');a.append(this._render_titleLink());return a},_render_titleButtons:function(){var a=$('<div class="historyItemButtons"></div>');a.append(this._render_displayButton());return a},_render_displayButton:function(){if((this.model.get("state")===HistoryDatasetAssociation.STATES.NOT_VIEWABLE)||(this.model.get("state")===HistoryDatasetAssociation.STATES.NEW)||(!this.model.get("accessible"))){this.displayButton=null;return null}var a={icon_class:"display",target:"galaxy_main"};if(this.model.get("purged")){a.enabled=false;a.title=_l("Cannot display datasets removed from disk")}else{a.title=_l("View data");a.href=this.urls.display}this.displayButton=new IconButtonView({model:new IconButton(a)});return this.displayButton.render().$el},_render_titleLink:function(){return $(jQuery.trim(HDABaseView.templates.titleLink(_.extend(this.model.toJSON(),{urls:this.urls}))))},_render_hdaSummary:function(){var a=_.extend(this.model.toJSON(),{urls:this.urls});return HDABaseView.templates.hdaSummary(a)},_render_primaryActionButtons:function(c){var a=this,b=$("<div/>").attr("id","primary-actions-"+this.model.get("id"));_.each(c,function(d){b.append(d.call(a))});return b},_render_downloadButton:function(){if(this.model.get("purged")||!this.model.hasData()){return null}var a=HDABaseView.templates.downloadLinks(_.extend(this.model.toJSON(),{urls:this.urls}));return $(a.trim())},_render_showParamsButton:function(){this.showParamsButton=new IconButtonView({model:new IconButton({title:_l("View details"),href:this.urls.show_params,target:"galaxy_main",icon_class:"information"})});return this.showParamsButton.render().$el},_render_displayAppArea:function(){return $("<div/>").addClass("display-apps")},_render_displayApps:function(c){c=c||this.$el;var d=c.find("div.display-apps"),a=this.model.get("display_types"),b=this.model.get("display_apps");if((!this.model.hasData())||(!c||!c.length)||(!d.length)){return}d.html(null);if(!_.isEmpty(a)){d.append(HDABaseView.templates.displayApps({displayApps:a}))}if(!_.isEmpty(b)){d.append(HDABaseView.templates.displayApps({displayApps:b}))}},_render_peek:function(){var a=this.model.get("peek");if(!a){return null}return $("<div/>").append($("<pre/>").attr("id","peek"+this.model.get("id")).addClass("peek").append(a))},_render_body:function(){var a=$("<div/>").attr("id","info-"+this.model.get("id")).addClass("historyItemBody").attr("style","display: none");if(this.expanded){this._render_body_html(a);a.css("display","block")}return a},_render_body_html:function(a){a.html("");switch(this.model.get("state")){case HistoryDatasetAssociation.STATES.NEW:this._render_body_new(a);break;case HistoryDatasetAssociation.STATES.NOT_VIEWABLE:this._render_body_not_viewable(a);break;case HistoryDatasetAssociation.STATES.UPLOAD:this._render_body_uploading(a);break;case HistoryDatasetAssociation.STATES.PAUSED:this._render_body_paused(a);break;case HistoryDatasetAssociation.STATES.QUEUED:this._render_body_queued(a);break;case HistoryDatasetAssociation.STATES.RUNNING:this._render_body_running(a);break;case HistoryDatasetAssociation.STATES.ERROR:this._render_body_error(a);break;case HistoryDatasetAssociation.STATES.DISCARDED:this._render_body_discarded(a);break;case HistoryDatasetAssociation.STATES.SETTING_METADATA:this._render_body_setting_metadata(a);break;case HistoryDatasetAssociation.STATES.EMPTY:this._render_body_empty(a);break;case HistoryDatasetAssociation.STATES.FAILED_METADATA:this._render_body_failed_metadata(a);break;case HistoryDatasetAssociation.STATES.OK:this._render_body_ok(a);break;default:a.append($('<div>Error: unknown dataset state "'+this.model.get("state")+'".</div>'))}a.append('<div style="clear: both"></div>');this._setUpBehaviors(a)},_render_body_new:function(b){var a=_l("This is a new dataset and not all of its data are available yet");b.append($("<div>"+_l(a)+"</div>"))},_render_body_not_viewable:function(a){a.append($("<div>"+_l("You do not have permission to view dataset")+"</div>"))},_render_body_uploading:function(a){a.append($("<div>"+_l("Dataset is uploading")+"</div>"))},_render_body_queued:function(a){a.append($("<div>"+_l("Job is waiting to run")+"</div>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_paused:function(a){a.append($("<div>"+_l("Job is paused. Use the history menu to resume")+"</div>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_running:function(a){a.append("<div>"+_l("Job is currently running")+"</div>");a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_error:function(a){if(!this.model.get("purged")){a.append($("<div>"+this.model.get("misc_blurb")+"</div>"))}a.append((_l("An error occurred with this dataset")+": <i>"+$.trim(this.model.get("misc_info"))+"</i>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers.concat([this._render_downloadButton])))},_render_body_discarded:function(a){a.append("<div>"+_l("The job creating this dataset was cancelled before completion")+".</div>");a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_setting_metadata:function(a){a.append($("<div>"+_l("Metadata is being auto-detected")+".</div>"))},_render_body_empty:function(a){a.append($("<div>"+_l("No data")+": <i>"+this.model.get("misc_blurb")+"</i></div>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_failed_metadata:function(a){a.append($(HDABaseView.templates.failedMetadata(_.extend(this.model.toJSON(),{urls:this.urls}))));this._render_body_ok(a)},_render_body_ok:function(a){a.append(this._render_hdaSummary());if(this.model.isDeletedOrPurged()){a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton]));return}a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton]));a.append('<div class="clear"/>');a.append(this._render_displayAppArea());this._render_displayApps(a);a.append(this._render_peek())},events:{"click .historyItemTitle":"toggleBodyVisibility"},toggleBodyVisibility:function(c,a){var b=this;this.expanded=(a===undefined)?(!this.body.is(":visible")):(a);if(this.expanded){b._render_body_html(b.body);this.body.slideDown("fast",function(){b.trigger("body-expanded",b.model.get("id"))})}else{this.body.slideUp("fast",function(){b.trigger("body-collapsed",b.model.get("id"))})}},remove:function(b){var a=this;this.$el.fadeOut("fast",function(){a.$el.remove();a.off();if(b){b()}})},toString:function(){var a=(this.model)?(this.model+""):("(no model)");return"HDABaseView("+a+")"}});HDABaseView.templates={warningMsg:Handlebars.templates["template-warningmessagesmall"],messages:Handlebars.templates["template-hda-warning-messages"],titleLink:Handlebars.templates["template-hda-titleLink"],hdaSummary:Handlebars.templates["template-hda-hdaSummary"],downloadLinks:Handlebars.templates["template-hda-downloadLinks"],failedMetadata:Handlebars.templates["template-hda-failedMetadata"],displayApps:Handlebars.templates["template-hda-displayApps"]}; \ No newline at end of file +var HDABaseView=Backbone.View.extend(LoggableMixin).extend({tagName:"div",className:"historyItemContainer",initialize:function(a){if(a.logger){this.logger=this.model.logger=a.logger}this.log(this+".initialize:",a);this.defaultPrimaryActionButtonRenderers=[this._render_showParamsButton];if(!a.urlTemplates){throw ("HDAView needs urlTemplates on initialize")}this.urlTemplates=a.urlTemplates;this.expanded=a.expanded||false;this.model.bind("change",function(c,d){var b=_.without(_.keys(d.changes),"display_apps","display_types");if(b.length){this.render()}else{if(this.expanded){this._render_displayApps()}}},this)},render:function(){var b=this,e=this.model.get("id"),c=this.model.get("state"),a=$("<div/>").attr("id","historyItem-"+e),d=(this.$el.children().size()===0);this.$el.attr("id","historyItemContainer-"+e);this.urls=this._renderUrls(this.urlTemplates,this.model.toJSON());a.addClass("historyItemWrapper").addClass("historyItem").addClass("historyItem-"+c);a.append(this._render_warnings());a.append(this._render_titleBar());this._setUpBehaviors(a);this.body=$(this._render_body());a.append(this.body);this.$el.fadeOut("fast",function(){b.$el.children().remove();b.$el.append(a).fadeIn("fast",function(){b.log(b+" rendered:",b.$el);var f="rendered";if(d){f+=":initial"}else{if(b.model.inReadyState()){f+=":ready"}}b.trigger(f)})});return this},_renderUrls:function(d,a){var b=this,c={};_.each(d,function(e,f){if(_.isObject(e)){c[f]=b._renderUrls(e,a)}else{if(f==="meta_download"){c[f]=b._renderMetaDownloadUrls(e,a)}else{try{c[f]=_.template(e,a)}catch(g){throw (b+"._renderUrls error: "+g+"\n rendering:"+e+"\n with "+JSON.stringify(a))}}}});return c},_renderMetaDownloadUrls:function(b,a){return _.map(a.meta_files,function(c){return{url:_.template(b,{id:a.id,file_type:c.file_type}),file_type:c.file_type}})},_setUpBehaviors:function(a){a=a||this.$el;make_popup_menus(a);a.find(".tooltip").tooltip({placement:"bottom"})},_render_warnings:function(){return $(jQuery.trim(HDABaseView.templates.messages(this.model.toJSON())))},_render_titleBar:function(){var a=$('<div class="historyItemTitleBar" style="overflow: hidden"></div>');a.append(this._render_titleButtons());a.append('<span class="state-icon"></span>');a.append(this._render_titleLink());return a},_render_titleButtons:function(){var a=$('<div class="historyItemButtons"></div>');a.append(this._render_displayButton());return a},_render_displayButton:function(){if((this.model.get("state")===HistoryDatasetAssociation.STATES.NOT_VIEWABLE)||(this.model.get("state")===HistoryDatasetAssociation.STATES.NEW)||(!this.model.get("accessible"))){this.displayButton=null;return null}var a={icon_class:"display",target:"galaxy_main"};if(this.model.get("purged")){a.enabled=false;a.title=_l("Cannot display datasets removed from disk")}else{a.title=_l("View data");a.href="javascript:parent.frame_manager.frame_new({title: 'Data Viewer', type: 'url', center: true, content: '"+this.urls.display+"'});"}this.displayButton=new IconButtonView({model:new IconButton(a)});return this.displayButton.render().$el},_render_titleLink:function(){return $(jQuery.trim(HDABaseView.templates.titleLink(_.extend(this.model.toJSON(),{urls:this.urls}))))},_render_hdaSummary:function(){var a=_.extend(this.model.toJSON(),{urls:this.urls});return HDABaseView.templates.hdaSummary(a)},_render_primaryActionButtons:function(c){var a=this,b=$("<div/>").attr("id","primary-actions-"+this.model.get("id"));_.each(c,function(d){b.append(d.call(a))});return b},_render_downloadButton:function(){if(this.model.get("purged")||!this.model.hasData()){return null}var a=HDABaseView.templates.downloadLinks(_.extend(this.model.toJSON(),{urls:this.urls}));return $(a.trim())},_render_showParamsButton:function(){this.showParamsButton=new IconButtonView({model:new IconButton({title:_l("View details"),href:this.urls.show_params,target:"galaxy_main",icon_class:"information"})});return this.showParamsButton.render().$el},_render_displayAppArea:function(){return $("<div/>").addClass("display-apps")},_render_displayApps:function(c){c=c||this.$el;var d=c.find("div.display-apps"),a=this.model.get("display_types"),b=this.model.get("display_apps");if((!this.model.hasData())||(!c||!c.length)||(!d.length)){return}d.html(null);if(!_.isEmpty(a)){d.append(HDABaseView.templates.displayApps({displayApps:a}))}if(!_.isEmpty(b)){d.append(HDABaseView.templates.displayApps({displayApps:b}))}},_render_peek:function(){var a=this.model.get("peek");if(!a){return null}return $("<div/>").append($("<pre/>").attr("id","peek"+this.model.get("id")).addClass("peek").append(a))},_render_body:function(){var a=$("<div/>").attr("id","info-"+this.model.get("id")).addClass("historyItemBody").attr("style","display: none");if(this.expanded){this._render_body_html(a);a.css("display","block")}return a},_render_body_html:function(a){a.html("");switch(this.model.get("state")){case HistoryDatasetAssociation.STATES.NEW:this._render_body_new(a);break;case HistoryDatasetAssociation.STATES.NOT_VIEWABLE:this._render_body_not_viewable(a);break;case HistoryDatasetAssociation.STATES.UPLOAD:this._render_body_uploading(a);break;case HistoryDatasetAssociation.STATES.PAUSED:this._render_body_paused(a);break;case HistoryDatasetAssociation.STATES.QUEUED:this._render_body_queued(a);break;case HistoryDatasetAssociation.STATES.RUNNING:this._render_body_running(a);break;case HistoryDatasetAssociation.STATES.ERROR:this._render_body_error(a);break;case HistoryDatasetAssociation.STATES.DISCARDED:this._render_body_discarded(a);break;case HistoryDatasetAssociation.STATES.SETTING_METADATA:this._render_body_setting_metadata(a);break;case HistoryDatasetAssociation.STATES.EMPTY:this._render_body_empty(a);break;case HistoryDatasetAssociation.STATES.FAILED_METADATA:this._render_body_failed_metadata(a);break;case HistoryDatasetAssociation.STATES.OK:this._render_body_ok(a);break;default:a.append($('<div>Error: unknown dataset state "'+this.model.get("state")+'".</div>'))}a.append('<div style="clear: both"></div>');this._setUpBehaviors(a)},_render_body_new:function(b){var a=_l("This is a new dataset and not all of its data are available yet");b.append($("<div>"+_l(a)+"</div>"))},_render_body_not_viewable:function(a){a.append($("<div>"+_l("You do not have permission to view dataset")+"</div>"))},_render_body_uploading:function(a){a.append($("<div>"+_l("Dataset is uploading")+"</div>"))},_render_body_queued:function(a){a.append($("<div>"+_l("Job is waiting to run")+"</div>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_paused:function(a){a.append($("<div>"+_l("Job is paused. Use the history menu to resume")+"</div>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_running:function(a){a.append("<div>"+_l("Job is currently running")+"</div>");a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_error:function(a){if(!this.model.get("purged")){a.append($("<div>"+this.model.get("misc_blurb")+"</div>"))}a.append((_l("An error occurred with this dataset")+": <i>"+$.trim(this.model.get("misc_info"))+"</i>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers.concat([this._render_downloadButton])))},_render_body_discarded:function(a){a.append("<div>"+_l("The job creating this dataset was cancelled before completion")+".</div>");a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_setting_metadata:function(a){a.append($("<div>"+_l("Metadata is being auto-detected")+".</div>"))},_render_body_empty:function(a){a.append($("<div>"+_l("No data")+": <i>"+this.model.get("misc_blurb")+"</i></div>"));a.append(this._render_primaryActionButtons(this.defaultPrimaryActionButtonRenderers))},_render_body_failed_metadata:function(a){a.append($(HDABaseView.templates.failedMetadata(_.extend(this.model.toJSON(),{urls:this.urls}))));this._render_body_ok(a)},_render_body_ok:function(a){a.append(this._render_hdaSummary());if(this.model.isDeletedOrPurged()){a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton]));return}a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton]));a.append('<div class="clear"/>');a.append(this._render_displayAppArea());this._render_displayApps(a);a.append(this._render_peek())},events:{"click .historyItemTitle":"toggleBodyVisibility"},toggleBodyVisibility:function(c,a){var b=this;this.expanded=(a===undefined)?(!this.body.is(":visible")):(a);if(this.expanded){b._render_body_html(b.body);this.body.slideDown("fast",function(){b.trigger("body-expanded",b.model.get("id"))})}else{this.body.slideUp("fast",function(){b.trigger("body-collapsed",b.model.get("id"))})}},remove:function(b){var a=this;this.$el.fadeOut("fast",function(){a.$el.remove();a.off();if(b){b()}})},toString:function(){var a=(this.model)?(this.model+""):("(no model)");return"HDABaseView("+a+")"}});HDABaseView.templates={warningMsg:Handlebars.templates["template-warningmessagesmall"],messages:Handlebars.templates["template-hda-warning-messages"],titleLink:Handlebars.templates["template-hda-titleLink"],hdaSummary:Handlebars.templates["template-hda-hdaSummary"],downloadLinks:Handlebars.templates["template-hda-downloadLinks"],failedMetadata:Handlebars.templates["template-hda-failedMetadata"],displayApps:Handlebars.templates["template-hda-displayApps"]}; \ No newline at end of file diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 static/scripts/packed/mvc/dataset/hda-edit.js --- a/static/scripts/packed/mvc/dataset/hda-edit.js +++ b/static/scripts/packed/mvc/dataset/hda-edit.js @@ -1,1 +1,1 @@ -var HDAEditView=HDABaseView.extend(LoggableMixin).extend({initialize:function(a){HDABaseView.prototype.initialize.call(this,a);this.defaultPrimaryActionButtonRenderers=[this._render_showParamsButton,this._render_rerunButton]},_setUpBehaviors:function(c){HDABaseView.prototype._setUpBehaviors.call(this,c);var a=this,b=this.urls.purge,d=c.find("#historyItemPurger-"+this.model.get("id"));if(d){d.attr("href",["javascript","void(0)"].join(":"));d.click(function(e){var f=jQuery.ajax(b);f.success(function(i,g,h){a.model.set("purged",true);a.trigger("purged",a)});f.error(function(h,g,i){a.trigger("error",_l("Unable to purge this dataset"),h,g,i)})})}},_render_warnings:function(){return $(jQuery.trim(HDABaseView.templates.messages(_.extend(this.model.toJSON(),{urls:this.urls}))))},_render_titleButtons:function(){var a=$('<div class="historyItemButtons"></div>');a.append(this._render_displayButton());a.append(this._render_editButton());a.append(this._render_deleteButton());return a},_render_editButton:function(){if((this.model.get("state")===HistoryDatasetAssociation.STATES.NEW)||(this.model.get("state")===HistoryDatasetAssociation.STATES.UPLOAD)||(this.model.get("state")===HistoryDatasetAssociation.STATES.NOT_VIEWABLE)||(!this.model.get("accessible"))){this.editButton=null;return null}var c=this.model.get("purged"),a=this.model.get("deleted"),b={title:_l("Edit Attributes"),href:this.urls.edit,target:"galaxy_main",icon_class:"edit"};if(a||c){b.enabled=false;if(c){b.title=_l("Cannot edit attributes of datasets removed from disk")}else{if(a){b.title=_l("Undelete dataset to edit attributes")}}}this.editButton=new IconButtonView({model:new IconButton(b)});return this.editButton.render().$el},_render_deleteButton:function(){if((this.model.get("state")===HistoryDatasetAssociation.STATES.NEW)||(this.model.get("state")===HistoryDatasetAssociation.STATES.NOT_VIEWABLE)||(!this.model.get("accessible"))){this.deleteButton=null;return null}var a=this,b=a.urls["delete"],c={title:_l("Delete"),href:b,id:"historyItemDeleter-"+this.model.get("id"),icon_class:"delete",on_click:function(){$.ajax({url:b,type:"POST",error:function(){a.$el.show()},success:function(){a.model.set({deleted:true})}})}};if(this.model.get("deleted")||this.model.get("purged")){c={title:_l("Dataset is already deleted"),icon_class:"delete",enabled:false}}this.deleteButton=new IconButtonView({model:new IconButton(c)});return this.deleteButton.render().$el},_render_hdaSummary:function(){var a=_.extend(this.model.toJSON(),{urls:this.urls});if(this.model.get("metadata_dbkey")==="?"&&!this.model.isDeletedOrPurged()){_.extend(a,{dbkey_unknown_and_editable:true})}return HDABaseView.templates.hdaSummary(a)},_render_errButton:function(){if(this.model.get("state")!==HistoryDatasetAssociation.STATES.ERROR){this.errButton=null;return null}this.errButton=new IconButtonView({model:new IconButton({title:_l("View or report this error"),href:this.urls.report_error,target:"galaxy_main",icon_class:"bug"})});return this.errButton.render().$el},_render_rerunButton:function(){this.rerunButton=new IconButtonView({model:new IconButton({title:_l("Run this job again"),href:this.urls.rerun,target:"galaxy_main",icon_class:"arrow-circle"})});return this.rerunButton.render().$el},_render_visualizationsButton:function(){var a=this.model.get("visualizations");if((!this.model.hasData())||(_.isEmpty(a))){this.visualizationsButton=null;return null}if(_.isObject(a[0])){return this._render_visualizationsFrameworkButton(a)}if(!this.urls.visualization){this.visualizationsButton=null;return null}var c=this.model.get("dbkey"),f=this.urls.visualization,d={},g={dataset_id:this.model.get("id"),hda_ldda:"hda"};if(c){g.dbkey=c}this.visualizationsButton=new IconButtonView({model:new IconButton({title:_l("Visualize"),href:this.urls.visualization,icon_class:"chart_curve"})});var b=this.visualizationsButton.render().$el;b.addClass("visualize-icon");function e(h){switch(h){case"trackster":return create_trackster_action_fn(f,g,c);case"scatterplot":return create_scatterplot_action_fn(f,g);default:return function(){window.parent.location=f+"/"+h+"?"+$.param(g)}}}if(a.length===1){b.attr("title",a[0]);b.click(e(a[0]))}else{_.each(a,function(i){var h=i.charAt(0).toUpperCase()+i.slice(1);d[_l(h)]=e(i)});make_popupmenu(b,d)}return b},_render_visualizationsFrameworkButton:function(a){if(!(this.model.hasData())||!(a&&!_.isEmpty(a))){this.visualizationsButton=null;return null}this.visualizationsButton=new IconButtonView({model:new IconButton({title:_l("Visualize"),icon_class:"chart_curve"})});var c=this.visualizationsButton.render().$el;c.addClass("visualize-icon");if(_.keys(a).length===1){c.attr("title",_.keys(a)[0]);c.attr("href",_.values(a)[0])}else{var d=[];_.each(a,function(e){d.push(e)});var b=new PopupMenu(c,d)}return c},_render_secondaryActionButtons:function(b){var c=$("<div/>"),a=this;c.attr("style","float: right;").attr("id","secondary-actions-"+this.model.get("id"));_.each(b,function(d){c.append(d.call(a))});return c},_render_tagButton:function(){if(!(this.model.hasData())||(!this.urls.tags.get)){this.tagButton=null;return null}this.tagButton=new IconButtonView({model:new IconButton({title:_l("Edit dataset tags"),target:"galaxy_main",href:this.urls.tags.get,icon_class:"tags"})});return this.tagButton.render().$el},_render_annotateButton:function(){if(!(this.model.hasData())||(!this.urls.annotation.get)){this.annotateButton=null;return null}this.annotateButton=new IconButtonView({model:new IconButton({title:_l("Edit dataset annotation"),target:"galaxy_main",icon_class:"annotate"})});return this.annotateButton.render().$el},_render_tagArea:function(){if(!this.urls.tags.set){return null}return $(HDAEditView.templates.tagArea(_.extend(this.model.toJSON(),{urls:this.urls})).trim())},_render_annotationArea:function(){if(!this.urls.annotation.get){return null}return $(HDAEditView.templates.annotationArea(_.extend(this.model.toJSON(),{urls:this.urls})).trim())},_render_body_error:function(a){HDABaseView.prototype._render_body_error.call(this,a);var b=a.find("#primary-actions-"+this.model.get("id"));b.prepend(this._render_errButton())},_render_body_ok:function(a){a.append(this._render_hdaSummary());if(this.model.isDeletedOrPurged()){a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton,this._render_rerunButton]));return}a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton,this._render_rerunButton,this._render_visualizationsButton]));a.append(this._render_secondaryActionButtons([this._render_tagButton,this._render_annotateButton]));a.append('<div class="clear"/>');a.append(this._render_tagArea());a.append(this._render_annotationArea());a.append(this._render_displayAppArea());this._render_displayApps(a);a.append(this._render_peek())},events:{"click .historyItemTitle":"toggleBodyVisibility","click a.icon-button.tags":"loadAndDisplayTags","click a.icon-button.annotate":"loadAndDisplayAnnotation"},loadAndDisplayTags:function(c){this.log(this+".loadAndDisplayTags",c);var a=this,d=this.$el.find(".tag-area"),b=d.find(".tag-elt");if(d.is(":hidden")){if(!jQuery.trim(b.html())){$.ajax({url:this.urls.tags.get,error:function(g,e,f){a.log("Tagging failed",g,e,f);a.trigger("error",_l("Tagging failed"),g,e,f)},success:function(e){b.html(e);b.find(".tooltip").tooltip();d.slideDown("fast")}})}else{d.slideDown("fast")}}else{d.slideUp("fast")}return false},loadAndDisplayAnnotation:function(b){this.log(this+".loadAndDisplayAnnotation",b);var d=this.$el.find(".annotation-area"),c=d.find(".annotation-elt"),a=this.urls.annotation.set;if(d.is(":hidden")){if(!jQuery.trim(c.html())){$.ajax({url:this.urls.annotation.get,error:function(){view.log("Annotation failed",xhr,status,error);view.trigger("error",_l("Annotation failed"),xhr,status,error)},success:function(e){if(e===""){e="<em>"+_l("Describe or add notes to dataset")+"</em>"}c.html(e);d.find(".tooltip").tooltip();async_save_text(c.attr("id"),c.attr("id"),a,"new_annotation",18,true,4);d.slideDown("fast")}})}else{d.slideDown("fast")}}else{d.slideUp("fast")}return false},toString:function(){var a=(this.model)?(this.model+""):("(no model)");return"HDAView("+a+")"}});HDAEditView.templates={tagArea:Handlebars.templates["template-hda-tagArea"],annotationArea:Handlebars.templates["template-hda-annotationArea"]};function create_scatterplot_action_fn(a,b){action=function(){var d=$(window.parent.document).find("iframe#galaxy_main"),c=a+"/scatterplot?"+$.param(b);d.attr("src",c);$("div.popmenu-wrapper").remove();return false};return action}function create_trackster_action_fn(a,c,b){return function(){var d={};if(b){d["f-dbkey"]=b}$.ajax({url:a+"/list_tracks?"+$.param(d),dataType:"html",error:function(){alert(_l("Could not add this dataset to browser")+".")},success:function(e){var f=window.parent;f.show_modal(_l("View Data in a New or Saved Visualization"),"",{Cancel:function(){f.hide_modal()},"View in saved visualization":function(){f.show_modal(_l("Add Data to Saved Visualization"),e,{Cancel:function(){f.hide_modal()},"Add to visualization":function(){$(f.document).find("input[name=id]:checked").each(function(){var g=$(this).val();c.id=g;f.location=a+"/trackster?"+$.param(c)})}})},"View in new visualization":function(){f.location=a+"/trackster?"+$.param(c)}})}});return false}}; \ No newline at end of file +var HDAEditView=HDABaseView.extend(LoggableMixin).extend({initialize:function(a){HDABaseView.prototype.initialize.call(this,a);this.defaultPrimaryActionButtonRenderers=[this._render_showParamsButton,this._render_rerunButton]},_setUpBehaviors:function(c){HDABaseView.prototype._setUpBehaviors.call(this,c);var a=this,b=this.urls.purge,d=c.find("#historyItemPurger-"+this.model.get("id"));if(d){d.attr("href",["javascript","void(0)"].join(":"));d.click(function(e){var f=jQuery.ajax(b);f.success(function(i,g,h){a.model.set("purged",true);a.trigger("purged",a)});f.error(function(h,g,i){a.trigger("error",_l("Unable to purge this dataset"),h,g,i)})})}},_render_warnings:function(){return $(jQuery.trim(HDABaseView.templates.messages(_.extend(this.model.toJSON(),{urls:this.urls}))))},_render_titleButtons:function(){var a=$('<div class="historyItemButtons"></div>');a.append(this._render_displayButton());a.append(this._render_editButton());a.append(this._render_deleteButton());return a},_render_editButton:function(){if((this.model.get("state")===HistoryDatasetAssociation.STATES.NEW)||(this.model.get("state")===HistoryDatasetAssociation.STATES.UPLOAD)||(this.model.get("state")===HistoryDatasetAssociation.STATES.NOT_VIEWABLE)||(!this.model.get("accessible"))){this.editButton=null;return null}var c=this.model.get("purged"),a=this.model.get("deleted"),b={title:_l("Edit Attributes"),href:this.urls.edit,target:"galaxy_main",icon_class:"edit"};if(a||c){b.enabled=false;if(c){b.title=_l("Cannot edit attributes of datasets removed from disk")}else{if(a){b.title=_l("Undelete dataset to edit attributes")}}}this.editButton=new IconButtonView({model:new IconButton(b)});return this.editButton.render().$el},_render_deleteButton:function(){if((this.model.get("state")===HistoryDatasetAssociation.STATES.NEW)||(this.model.get("state")===HistoryDatasetAssociation.STATES.NOT_VIEWABLE)||(!this.model.get("accessible"))){this.deleteButton=null;return null}var a=this,b=a.urls["delete"],c={title:_l("Delete"),href:b,id:"historyItemDeleter-"+this.model.get("id"),icon_class:"delete",on_click:function(){$.ajax({url:b,type:"POST",error:function(){a.$el.show()},success:function(){a.model.set({deleted:true})}})}};if(this.model.get("deleted")||this.model.get("purged")){c={title:_l("Dataset is already deleted"),icon_class:"delete",enabled:false}}this.deleteButton=new IconButtonView({model:new IconButton(c)});return this.deleteButton.render().$el},_render_hdaSummary:function(){var a=_.extend(this.model.toJSON(),{urls:this.urls});if(this.model.get("metadata_dbkey")==="?"&&!this.model.isDeletedOrPurged()){_.extend(a,{dbkey_unknown_and_editable:true})}return HDABaseView.templates.hdaSummary(a)},_render_errButton:function(){if(this.model.get("state")!==HistoryDatasetAssociation.STATES.ERROR){this.errButton=null;return null}this.errButton=new IconButtonView({model:new IconButton({title:_l("View or report this error"),href:this.urls.report_error,target:"galaxy_main",icon_class:"bug"})});return this.errButton.render().$el},_render_rerunButton:function(){this.rerunButton=new IconButtonView({model:new IconButton({title:_l("Run this job again"),href:this.urls.rerun,target:"galaxy_main",icon_class:"arrow-circle"})});return this.rerunButton.render().$el},_render_visualizationsButton:function(){var a=this.model.get("visualizations");if((!this.model.hasData())||(_.isEmpty(a))){this.visualizationsButton=null;return null}if(_.isObject(a[0])){return this._render_visualizationsFrameworkButton(a)}if(!this.urls.visualization){this.visualizationsButton=null;return null}var c=this.model.get("dbkey"),f=this.urls.visualization,d={},g={dataset_id:this.model.get("id"),hda_ldda:"hda"};if(c){g.dbkey=c}this.visualizationsButton=new IconButtonView({model:new IconButton({title:_l("Visualize"),href:this.urls.visualization,icon_class:"chart_curve"})});var b=this.visualizationsButton.render().$el;b.addClass("visualize-icon");function e(h){switch(h){case"trackster":return create_trackster_action_fn(f,g,c);case"scatterplot":return create_scatterplot_action_fn(f,g);default:return function(){parent.frame_manager.frame_new({title:"Visualization",type:"url",content:f+"/"+h+"?"+$.param(g)})}}}if(a.length===1){b.attr("title",a[0]);b.click(e(a[0]))}else{_.each(a,function(i){var h=i.charAt(0).toUpperCase()+i.slice(1);d[_l(h)]=e(i)});make_popupmenu(b,d)}return b},_render_visualizationsFrameworkButton:function(a){if(!(this.model.hasData())||!(a&&!_.isEmpty(a))){this.visualizationsButton=null;return null}this.visualizationsButton=new IconButtonView({model:new IconButton({title:_l("Visualize"),icon_class:"chart_curve"})});var c=this.visualizationsButton.render().$el;c.addClass("visualize-icon");if(_.keys(a).length===1){c.attr("title",_.keys(a)[0]);c.attr("href",_.values(a)[0])}else{var d=[];_.each(a,function(e){d.push(e)});var b=new PopupMenu(c,d)}return c},_render_secondaryActionButtons:function(b){var c=$("<div/>"),a=this;c.attr("style","float: right;").attr("id","secondary-actions-"+this.model.get("id"));_.each(b,function(d){c.append(d.call(a))});return c},_render_tagButton:function(){if(!(this.model.hasData())||(!this.urls.tags.get)){this.tagButton=null;return null}this.tagButton=new IconButtonView({model:new IconButton({title:_l("Edit dataset tags"),target:"galaxy_main",href:this.urls.tags.get,icon_class:"tags"})});return this.tagButton.render().$el},_render_annotateButton:function(){if(!(this.model.hasData())||(!this.urls.annotation.get)){this.annotateButton=null;return null}this.annotateButton=new IconButtonView({model:new IconButton({title:_l("Edit dataset annotation"),target:"galaxy_main",icon_class:"annotate"})});return this.annotateButton.render().$el},_render_tagArea:function(){if(!this.urls.tags.set){return null}return $(HDAEditView.templates.tagArea(_.extend(this.model.toJSON(),{urls:this.urls})).trim())},_render_annotationArea:function(){if(!this.urls.annotation.get){return null}return $(HDAEditView.templates.annotationArea(_.extend(this.model.toJSON(),{urls:this.urls})).trim())},_render_body_error:function(a){HDABaseView.prototype._render_body_error.call(this,a);var b=a.find("#primary-actions-"+this.model.get("id"));b.prepend(this._render_errButton())},_render_body_ok:function(a){a.append(this._render_hdaSummary());if(this.model.isDeletedOrPurged()){a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton,this._render_rerunButton]));return}a.append(this._render_primaryActionButtons([this._render_downloadButton,this._render_showParamsButton,this._render_rerunButton,this._render_visualizationsButton]));a.append(this._render_secondaryActionButtons([this._render_tagButton,this._render_annotateButton]));a.append('<div class="clear"/>');a.append(this._render_tagArea());a.append(this._render_annotationArea());a.append(this._render_displayAppArea());this._render_displayApps(a);a.append(this._render_peek())},events:{"click .historyItemTitle":"toggleBodyVisibility","click a.icon-button.tags":"loadAndDisplayTags","click a.icon-button.annotate":"loadAndDisplayAnnotation"},loadAndDisplayTags:function(c){this.log(this+".loadAndDisplayTags",c);var a=this,d=this.$el.find(".tag-area"),b=d.find(".tag-elt");if(d.is(":hidden")){if(!jQuery.trim(b.html())){$.ajax({url:this.urls.tags.get,error:function(g,e,f){a.log("Tagging failed",g,e,f);a.trigger("error",_l("Tagging failed"),g,e,f)},success:function(e){b.html(e);b.find(".tooltip").tooltip();d.slideDown("fast")}})}else{d.slideDown("fast")}}else{d.slideUp("fast")}return false},loadAndDisplayAnnotation:function(b){this.log(this+".loadAndDisplayAnnotation",b);var d=this.$el.find(".annotation-area"),c=d.find(".annotation-elt"),a=this.urls.annotation.set;if(d.is(":hidden")){if(!jQuery.trim(c.html())){$.ajax({url:this.urls.annotation.get,error:function(){view.log("Annotation failed",xhr,status,error);view.trigger("error",_l("Annotation failed"),xhr,status,error)},success:function(e){if(e===""){e="<em>"+_l("Describe or add notes to dataset")+"</em>"}c.html(e);d.find(".tooltip").tooltip();async_save_text(c.attr("id"),c.attr("id"),a,"new_annotation",18,true,4);d.slideDown("fast")}})}else{d.slideDown("fast")}}else{d.slideUp("fast")}return false},toString:function(){var a=(this.model)?(this.model+""):("(no model)");return"HDAView("+a+")"}});HDAEditView.templates={tagArea:Handlebars.templates["template-hda-tagArea"],annotationArea:Handlebars.templates["template-hda-annotationArea"]};function create_scatterplot_action_fn(a,b){action=function(){parent.frame_manager.frame_new({title:"Scatterplot",type:"url",content:a+"/scatterplot?"+$.param(b),center:true});$("div.popmenu-wrapper").remove();return false};return action}function create_trackster_action_fn(a,c,b){return function(){var d={};if(b){d["f-dbkey"]=b}$.ajax({url:a+"/list_tracks?"+$.param(d),dataType:"html",error:function(){alert(_l("Could not add this dataset to browser")+".")},success:function(e){var f=window.parent;f.show_modal(_l("View Data in a New or Saved Visualization"),"",{Cancel:function(){f.hide_modal()},"View in saved visualization":function(){f.show_modal(_l("Add Data to Saved Visualization"),e,{Cancel:function(){f.hide_modal()},"Add to visualization":function(){$(f.document).find("input[name=id]:checked").each(function(){var g=$(this).val();c.id=g;f.hide_modal();f.frame_manager.frame_new({title:"Trackster",type:"url",content:a+"/trackster?"+$.param(c)})})}})},"View in new visualization":function(){f.hide_modal();f.frame_manager.frame_new({title:"Trackster",type:"url",content:a+"/trackster?"+$.param(c)})}})}});return false}}; \ No newline at end of file diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 static/scripts/packed/mvc/visualizations/scatterplotControlForm.js --- a/static/scripts/packed/mvc/visualizations/scatterplotControlForm.js +++ b/static/scripts/packed/mvc/visualizations/scatterplotControlForm.js @@ -1,1 +1,1 @@ -var ScatterplotControlForm=BaseView.extend(LoggableMixin).extend({className:"scatterplot-control-form",dataLoadDelay:4000,dataLoadSize:5000,loadingIndicatorImage:"loading_small_white_bg.gif",fetchMsg:"Fetching data...",renderMsg:"Rendering...",initialize:function(a){this.log(this+".initialize, attributes:",a);this.dataset=null;this.chartConfig=null;this.chart=null;this.loader=null;this.$dataControl=null;this.$chartControl=null;this.$statsDisplay=null;this.$chartDisplay=null;this.dataFetch=null;this.initializeFromAttributes(a);this.initializeChart(a);this.initializeDataLoader(a)},initializeFromAttributes:function(a){if(!a||!a.dataset){throw ("ScatterplotView requires a dataset")}else{this.dataset=a.dataset}if(jQuery.type(this.dataset.metadata_column_types)==="string"){this.dataset.metadata_column_types=this.dataset.metadata_column_types.split(", ")}this.log("\t dataset:",this.dataset);if(this.dataset.comment_lines&&this.dataset.comment_lines.length){var b=this.dataset.comment_lines[0],c=b.split("\t");if(c.length===this.dataset.metadata_column_types.length){this.possibleHeaders=c}}if(!a.apiDatasetsURL){throw ("ScatterplotView requires a apiDatasetsURL")}else{this.dataURL=a.apiDatasetsURL+"/"+this.dataset.id+"?"}this.log("\t dataURL:",this.dataURL)},initializeChart:function(a){this.chartConfig=a.chartConfig||{};this.log("\t initial chartConfig:",this.chartConfig);this.chart=new TwoVarScatterplot(this.chartConfig);this.chartConfig=this.chart.config},initializeDataLoader:function(b){var a=this;this.loader=new LazyDataLoader({url:null,start:b.start||0,total:b.total||this.dataset.metadata_data_lines,delay:this.dataLoadDelay,size:this.dataLoadSize,buildUrl:function(d,c){return this.url+"&"+jQuery.param({start_val:d,max_vals:c})}});$(this.loader).bind("error",function(e,c,d){a.log("ERROR:",c,d);alert("ERROR fetching data:\n"+c+"\n"+d);a.hideLoadingIndicator()})},render:function(){this.log(this+".render");this.$el.append(ScatterplotControlForm.templates.mainLayout({loadingIndicatorImagePath:galaxy_paths.get("image_path")+"/"+this.loadingIndicatorImage,message:""}));this.$dataControl=this._render_dataControl();this.$chartControl=this._render_chartControl();this.$statsDisplay=this.$el.find(".tab-pane#stats-display");this.$chartDisplay=this._render_chartDisplay();if(this.chartConfig.xColumn&&this.chartConfig.yColumn){this.renderChart()}this.$el.find(".tooltip").tooltip();return this},_render_dataControl:function(){var b=this,a=[],e=[],c=(this.possibleHeaders&&this.$dataControl)?(this.$dataControl.find("#first-line-header-checkbox").is(":checked")):(false);_.each(this.dataset.metadata_column_types,function(i,g){var h=g+1,f="column "+h;if(b.dataset.metadata_column_names){f=b.dataset.metadata_column_names[g]}else{if(c){f=b.possibleHeaders[g]}}a.push({index:h,name:f});if(i==="int"||i==="float"){e.push({index:h,name:f})}});var d=this.$el.find(".tab-pane#data-control");d.html(ScatterplotControlForm.templates.dataControl({allColumns:a,numericColumns:e,possibleHeaders:(this.possibleHeaders)?(this.possibleHeaders.join(", ")):(""),usePossibleHeaders:c}));if(!this.dataset.metadata_column_names&&this.possibleHeaders){d.find("#first-line-header").show()}d.find("#X-select").val(this.chartConfig.xColumn);d.find("#Y-select").val(this.chartConfig.yColumn);if(this.chartConfig.idColumn!==undefined){d.find("#include-id-checkbox").attr("checked",true).trigger("change");d.find("#ID-select").val(this.chartConfig.idColumn)}return d},_render_chartControl:function(){var a=this,b=this.$el.find(".tab-pane#chart-control"),c={datapointSize:{min:2,max:10,step:1},width:{min:200,max:800,step:20},height:{min:200,max:800,step:20}};b.append(ScatterplotControlForm.templates.chartControl(this.chartConfig));b.find(".numeric-slider-input").each(function(){var f=$(this),e=f.find(".slider-output"),g=f.find(".slider"),h=f.attr("id");function d(){var j=$(this),i=j.slider("value");e.text(i)}g.slider(_.extend(c[h],{value:a.chartConfig[h],change:d,slide:d}))});return b},_render_chartDisplay:function(){var a=this.$el.find(".tab-pane#chart-display");a.append(ScatterplotControlForm.templates.chartDisplay(this.chartConfig));return a},events:{"change #include-id-checkbox":"toggleThirdColumnSelector","change #first-line-header-checkbox":"rerenderDataControl","click #data-control #render-button":"renderChart","click #chart-control #render-button":"changeChartSettings"},toggleThirdColumnSelector:function(){this.$el.find('select[name="ID"]').parent().toggle()},rerenderDataControl:function(){this.$dataControl=this._render_dataControl()},showLoadingIndicator:function(b,c){b=b||"";var a=this.$el.find("div#loading-indicator");messageBox=a.find(".loading-message");if(a.is(":visible")){if(b){messageBox.fadeOut("fast",function(){messageBox.text(b);messageBox.fadeIn("fast",c)})}else{c()}}else{if(b){messageBox.text(b)}a.fadeIn("fast",c)}},hideLoadingIndicator:function(a){this.$el.find("div#loading-indicator").fadeOut("fast",a)},renderChart:function(){this.log(this+".renderChart");this.data=null;this.meta=null;_.extend(this.chartConfig,this.getChartSettings());this.log("\t chartConfig:",this.chartConfig);this.chart.updateConfig(this.chartConfig,false);this.loader.url=this.dataURL+"&"+jQuery.param(this.getDataSettings());this.log("\t loader: total lines:",this.loader.total," url:",this.loader.url);var a=this;$(this.loader).bind("loaded.new",function(c,b){a.log(a+" loaded.new",b);a.postProcessDataFetchResponse(b);a.log("\t postprocessed data:",a.data);a.log("\t postprocessed meta:",a.meta);a.showLoadingIndicator(a.renderMsg,function(){a.chart.render(a.data,a.meta);a.renderStats(a.data,a.meta);a.hideLoadingIndicator()})});$(this.loader).bind("complete",function(b,c){a.log(a+" complete",c);$(a.loader).unbind()});a.showLoadingIndicator(a.fetchMsg,function(){a.$el.find("ul.nav").find('a[href="#chart-display"]').tab("show");a.loader.load()})},renderStats:function(){this.log(this+".renderStats");this.$statsDisplay.html(ScatterplotControlForm.templates.statsDisplay({stats:[{name:"Count",xval:this.meta[0].count,yval:this.meta[1].count},{name:"Min",xval:this.meta[0].min,yval:this.meta[1].min},{name:"Max",xval:this.meta[0].max,yval:this.meta[1].max},{name:"Sum",xval:this.meta[0].sum,yval:this.meta[1].sum},{name:"Mean",xval:this.meta[0].mean,yval:this.meta[1].mean},{name:"Median",xval:this.meta[0].median,yval:this.meta[1].median}]}))},changeChartSettings:function(){var a=this;newChartSettings=this.getChartSettings();_.extend(this.chartConfig,newChartSettings);this.log("this.chartConfig:",this.chartConfig);this.chart.updateConfig(this.chartConfig,false);if(a.data&&a.meta){a.showLoadingIndicator(a.renderMsg,function(){a.$el.find("ul.nav").find('a[href="#chart-display"]').tab("show");a.chart.render(a.data,a.meta);a.hideLoadingIndicator()})}else{this.renderChart()}},postProcessDataFetchResponse:function(a){this.postProcessData(a.data);this.postProcessMeta(a.meta)},postProcessData:function(b){var a=this;if(a.data){_.each(b,function(d,c){a.data[c]=a.data[c].concat(d)})}else{a.data=b}},postProcessMeta:function(c){var a=this,b=this.dataset.metadata_column_types;if(a.meta){_.each(c,function(e,d){var i=a.meta[d],g=b[d];i.count+=(e.count)?(e.count):(0);if((g==="int")||(g==="float")){i.min=Math.min(e.min,i.min);i.max=Math.max(e.max,i.max);i.sum=e.sum+i.sum;i.mean=(i.count)?(i.sum/i.count):(null);var f=a.data[d].slice().sort(),h=Math.floor(f.length/2);if(f.length%2===0){i.median=((f[h]+f[(h+1)])/2)}else{i.median=f[h]}}})}else{a.meta=c}},getDataSettings:function(){var b=this.getColumnSelections(),a=[];this.log("\t columnSelections:",b);a=[b.X.colIndex-1,b.Y.colIndex-1];if(this.$dataControl.find("#include-id-checkbox").attr("checked")){a.push(b.ID.colIndex-1)}var c={data_type:"raw_data",provider:"column",columns:"["+a+"]"};this.log("\t data settings (url params):",c);return c},getColumnSelections:function(){var a={};this.$dataControl.find("div.column-select select").each(function(){var b=$(this),c=b.val();a[b.attr("name")]={colIndex:c,colName:b.children('[value="'+c+'"]').text()}});return a},getChartSettings:function(){var c={},d=this.getColumnSelections();c.datapointSize=this.$chartControl.find("#datapointSize.numeric-slider-input").find(".slider").slider("value");c.width=this.$chartControl.find("#width.numeric-slider-input").find(".slider").slider("value");c.height=this.$chartControl.find("#height.numeric-slider-input").find(".slider").slider("value");var b=this.$chartControl.find("input#X-axis-label").val(),a=this.$chartControl.find("input#Y-axis-label").val();c.xLabel=(b==="X")?(d.X.colName):(b);c.yLabel=(a==="Y")?(d.Y.colName):(a);c.animDuration=(this.$chartControl.find("#animate-chart").is(":checked"))?(this.chart.defaults.animDuration):(0);this.log("\t chartSettings:",c);return c},toString:function(){return"ScatterplotControlForm("+((this.dataset)?(this.dataset.id):(""))+")"}});ScatterplotControlForm.templates={mainLayout:Handlebars.templates["template-visualization-scatterplotControlForm"],dataControl:Handlebars.templates["template-visualization-dataControl"],chartControl:Handlebars.templates["template-visualization-chartControl"],statsDisplay:Handlebars.templates["template-visualization-statsDisplay"],chartDisplay:Handlebars.templates["template-visualization-chartDisplay"]}; \ No newline at end of file +var ScatterplotControlForm=BaseView.extend(LoggableMixin).extend({className:"scatterplot-control-form",dataLoadDelay:4000,dataLoadSize:5000,loadingIndicatorImage:"loading_small_white_bg.gif",fetchMsg:"Fetching data...",renderMsg:"Rendering...",initialize:function(a){this.log(this+".initialize, attributes:",a);this.dataset=null;this.chartConfig=null;this.chart=null;this.loader=null;this.$dataControl=null;this.$chartControl=null;this.$statsDisplay=null;this.$chartDisplay=null;this.dataFetch=null;this.initializeFromAttributes(a);this.initializeChart(a);this.initializeDataLoader(a)},initializeFromAttributes:function(a){if(!a||!a.dataset){throw ("ScatterplotView requires a dataset")}else{this.dataset=a.dataset}if(jQuery.type(this.dataset.metadata_column_types)==="string"){this.dataset.metadata_column_types=this.dataset.metadata_column_types.split(", ")}this.log("\t dataset:",this.dataset);if(this.dataset.comment_lines&&this.dataset.comment_lines.length){var b=this.dataset.comment_lines[0],c=b.split("\t");if(c.length===this.dataset.metadata_column_types.length){this.possibleHeaders=c}}if(!a.apiDatasetsURL){throw ("ScatterplotView requires a apiDatasetsURL")}else{this.dataURL=a.apiDatasetsURL+"/"+this.dataset.id+"?"}this.log("\t dataURL:",this.dataURL)},initializeChart:function(a){this.chartConfig=a.chartConfig||{};this.log("\t initial chartConfig:",this.chartConfig);this.chart=new TwoVarScatterplot(this.chartConfig);this.chartConfig=this.chart.config},initializeDataLoader:function(b){var a=this;this.loader=new LazyDataLoader({url:null,start:b.start||0,total:b.total||this.dataset.metadata_data_lines,delay:this.dataLoadDelay,size:this.dataLoadSize,buildUrl:function(d,c){return this.url+"&"+jQuery.param({start_val:d,max_vals:c})}});$(this.loader).bind("error",function(e,c,d){a.log("ERROR:",c,d);alert("ERROR fetching data:\n"+c+"\n"+d);a.hideLoadingIndicator()})},render:function(){this.log(this+".render");this.$el.append(ScatterplotControlForm.templates.mainLayout({loadingIndicatorImagePath:galaxy_paths.get("image_path")+"/"+this.loadingIndicatorImage,message:""}));this.$dataControl=this._render_dataControl();this.$chartControl=this._render_chartControl();this.$statsDisplay=this.$el.find(".tab-pane#stats-display");this.$chartDisplay=this._render_chartDisplay();if(this.chartConfig.xColumn&&this.chartConfig.yColumn){this.renderChart()}this.$el.find(".tooltip").tooltip();return this},_render_dataControl:function(){var b=this,a=[],e=[],c=(this.possibleHeaders&&this.$dataControl)?(this.$dataControl.find("#first-line-header-checkbox").is(":checked")):(false);_.each(this.dataset.metadata_column_types,function(i,g){var h=g+1,f="column "+h;if(b.dataset.metadata_column_names){f=b.dataset.metadata_column_names[g]}else{if(c){f=b.possibleHeaders[g]}}a.push({index:h,name:f});if(i==="int"||i==="float"){e.push({index:h,name:f})}});var d=this.$el.find(".tab-pane#data-control");d.html(ScatterplotControlForm.templates.dataControl({allColumns:a,numericColumns:e,possibleHeaders:(this.possibleHeaders)?(this.possibleHeaders.join(", ")):(""),usePossibleHeaders:c}));if(!this.dataset.metadata_column_names&&this.possibleHeaders){d.find("#first-line-header").show()}d.find("#X-select").val(this.chartConfig.xColumn);d.find("#Y-select").val(this.chartConfig.yColumn);if(this.chartConfig.idColumn!==undefined){d.find("#include-id-checkbox").attr("checked",true).trigger("change");d.find("#ID-select").val(this.chartConfig.idColumn)}return d},_render_chartControl:function(){var a=this,b=this.$el.find(".tab-pane#chart-control"),c={datapointSize:{min:2,max:10,step:1},width:{min:200,max:800,step:20},height:{min:200,max:800,step:20}};b.append(ScatterplotControlForm.templates.chartControl(this.chartConfig));b.find(".numeric-slider-input").each(function(){var f=$(this),e=f.find(".slider-output"),g=f.find(".slider"),h=f.attr("id");function d(){var j=$(this),i=j.slider("value");e.text(i)}g.slider(_.extend(c[h],{value:a.chartConfig[h],change:d,slide:d}))});return b},_render_chartDisplay:function(){var a=this.$el.find(".tab-pane#chart-display");a.append(ScatterplotControlForm.templates.chartDisplay(this.chartConfig));return a},events:{"change #include-id-checkbox":"toggleThirdColumnSelector","change #first-line-header-checkbox":"rerenderDataControl","click #data-control #render-button":"renderChart","click #chart-control #render-button":"changeChartSettings"},toggleThirdColumnSelector:function(){this.$el.find('select[name="ID"]').parent().toggle()},rerenderDataControl:function(){this.$dataControl=this._render_dataControl()},showLoadingIndicator:function(b,c){b=b||"";var a=this.$el.find("div#loading-indicator");messageBox=a.find(".loading-message");if(a.is(":visible")){if(b){messageBox.fadeOut("fast",function(){messageBox.text(b);messageBox.fadeIn("fast",c)})}else{c()}}else{if(b){messageBox.text(b)}a.fadeIn("fast",c)}},hideLoadingIndicator:function(a){this.$el.find("div#loading-indicator").fadeOut("fast",a)},renderChart:function(){this.log(this+".renderChart");this.data=null;this.meta=null;_.extend(this.chartConfig,this.getChartSettings());this.log("\t chartConfig:",this.chartConfig);this.chart.updateConfig(this.chartConfig,false);this.loader.url=this.dataURL+"&"+jQuery.param(this.getDataSettings());this.log("\t loader: total lines:",this.loader.total," url:",this.loader.url);var a=this;$(this.loader).bind("loaded.new",function(c,b){a.log(a+" loaded.new",b);a.postProcessDataFetchResponse(b);a.log("\t postprocessed data:",a.data);a.log("\t postprocessed meta:",a.meta);a.showLoadingIndicator(a.renderMsg,function(){a.chart.render(a.data,a.meta);a.renderStats(a.data,a.meta);a.hideLoadingIndicator()})});$(this.loader).bind("complete",function(b,c){a.log(a+" complete",c);$(a.loader).unbind()});a.showLoadingIndicator(a.fetchMsg,function(){a.$el.find("ul.nav").find('a[href="#chart-display"]').tab("show");a.loader.load()})},renderStats:function(){this.log(this+".renderStats");this.$statsDisplay.html(ScatterplotControlForm.templates.statsDisplay({stats:[{name:"Count",xval:this.meta[0].count,yval:this.meta[1].count},{name:"Min",xval:this.meta[0].min,yval:this.meta[1].min},{name:"Max",xval:this.meta[0].max,yval:this.meta[1].max},{name:"Sum",xval:this.meta[0].sum,yval:this.meta[1].sum},{name:"Mean",xval:this.meta[0].mean,yval:this.meta[1].mean},{name:"Median",xval:this.meta[0].median,yval:this.meta[1].median}]}))},changeChartSettings:function(){var a=this;newChartSettings=this.getChartSettings();_.extend(this.chartConfig,newChartSettings);this.log("this.chartConfig:",this.chartConfig);this.chart.updateConfig(this.chartConfig,false);if(a.data&&a.meta){a.showLoadingIndicator(a.renderMsg,function(){a.$el.find("ul.nav").find('a[href="#chart-display"]').tab("show");a.chart.render(a.data,a.meta);a.hideLoadingIndicator()})}else{this.renderChart()}},postProcessDataFetchResponse:function(a){this.postProcessData(a.data);this.postProcessMeta(a.meta)},postProcessData:function(b){var a=this;if(a.data){_.each(b,function(d,c){a.data[c]=a.data[c].concat(d)})}else{a.data=b}},postProcessMeta:function(c){var a=this,b=this.dataset.metadata_column_types;if(a.meta){_.each(c,function(e,d){var i=a.meta[d],g=b[d];i.count+=(e.count)?(e.count):(0);if((g==="int")||(g==="float")){i.min=Math.min(e.min,i.min);i.max=Math.max(e.max,i.max);i.sum=e.sum+i.sum;i.mean=(i.count)?(i.sum/i.count):(null);var f=a.data[d].slice().sort(),h=Math.floor(f.length/2);if(f.length%2===0){i.median=((f[h]+f[(h+1)])/2)}else{i.median=f[h]}}})}else{a.meta=c}},getDataSettings:function(){var b=this.getColumnSelections(),a=[];this.log("\t columnSelections:",b);a=[b.X.colIndex-1,b.Y.colIndex-1];if(this.$dataControl.find("#include-id-checkbox").attr("checked")){a.push(b.ID.colIndex-1)}var c={data_type:"raw_data",provider:"column_with_stats",columns:"["+a+"]"};this.log("\t data settings (url params):",c);return c},getColumnSelections:function(){var a={};this.$dataControl.find("div.column-select select").each(function(){var b=$(this),c=b.val();a[b.attr("name")]={colIndex:c,colName:b.children('[value="'+c+'"]').text()}});return a},getChartSettings:function(){var c={},d=this.getColumnSelections();c.datapointSize=this.$chartControl.find("#datapointSize.numeric-slider-input").find(".slider").slider("value");c.width=this.$chartControl.find("#width.numeric-slider-input").find(".slider").slider("value");c.height=this.$chartControl.find("#height.numeric-slider-input").find(".slider").slider("value");var b=this.$chartControl.find("input#X-axis-label").val(),a=this.$chartControl.find("input#Y-axis-label").val();c.xLabel=(b==="X")?(d.X.colName):(b);c.yLabel=(a==="Y")?(d.Y.colName):(a);c.animDuration=(this.$chartControl.find("#animate-chart").is(":checked"))?(this.chart.defaults.animDuration):(0);this.log("\t chartSettings:",c);return c},toString:function(){return"ScatterplotControlForm("+((this.dataset)?(this.dataset.id):(""))+")"}});ScatterplotControlForm.templates={mainLayout:Handlebars.templates["template-visualization-scatterplotControlForm"],dataControl:Handlebars.templates["template-visualization-dataControl"],chartControl:Handlebars.templates["template-visualization-chartControl"],statsDisplay:Handlebars.templates["template-visualization-statsDisplay"],chartDisplay:Handlebars.templates["template-visualization-chartDisplay"]}; \ No newline at end of file diff -r 8ea772733c979a4d5578ba4c8c31dd3f47cc32ba -r 72b02995c8b188b8efe9b3ac4c5996e972e596f1 visualizations_conf.xml.sample --- a/visualizations_conf.xml.sample +++ b/visualizations_conf.xml.sample @@ -84,30 +84,30 @@ (e.g. hda_ldda can be 'hda' or 'ldda' and modifies/informs dataset_id to fetch an HDA or LDDA) --><!ELEMENT param (#PCDATA)> - <!-- param tells the registry how to parse the query string param back into a resource/data_source. - For example, if a query string has "dataset_id=NNN" and the type is 'dataset', the registry - will attempt to fetch the hda with id of NNN from the database and pass it to the template. - (text): the query string param key this source will be parsed from (e.g. dataset_id) - REQUIRED - type: the type of the resource. - Can be: str (DEFAULT), bool, int, float, json, visualization, dbkey, dataset, or hda_ldda. - default: if a param is not passed on the query string (and is not required) OR the given param - fails to parse, this value is used instead. - DEFAULT: None - required: set this to true if the param is required for the template. Rendering will with an error - if the param hasn't been sent. - DEFAULT: false - csv: set this to true if the param is a comma separated list. The registry will attempt to - parse each value as the given type and send the result as a list to the template. - DEFAULT: false - constrain_to: (currently unused) constain a param to a set of values, error if not valid. - DEFAULT: don't constrain - var_name_in_template: a new name for the resource/variable to use in the template. E.g. an initial - query string param key might be 'dataset_id' in the URL, the registry parses it into an HDA, - and if var_name_in_template is set to 'hda', the template will be able to access the HDA - with the variable name 'hda' (as in hda.title). - DEFAULT: keep the original query string name - --> + <!-- param tells the registry how to parse the query string param back into a resource/data_source. + For example, if a query string has "dataset_id=NNN" and the type is 'dataset', the registry + will attempt to fetch the hda with id of NNN from the database and pass it to the template. + (text): the query string param key this source will be parsed from (e.g. dataset_id) + REQUIRED + type: the type of the resource. + Can be: str (DEFAULT), bool, int, float, json, visualization, dbkey, dataset, or hda_ldda. + default: if a param is not passed on the query string (and is not required) OR the given param + fails to parse, this value is used instead. + DEFAULT: None + required: set this to true if the param is required for the template. Rendering will with an error + if the param hasn't been sent. + DEFAULT: false + csv: set this to true if the param is a comma separated list. The registry will attempt to + parse each value as the given type and send the result as a list to the template. + DEFAULT: false + constrain_to: (currently unused) constain a param to a set of values, error if not valid. + DEFAULT: don't constrain + var_name_in_template: a new name for the resource/variable to use in the template. E.g. an initial + query string param key might be 'dataset_id' in the URL, the registry parses it into an HDA, + and if var_name_in_template is set to 'hda', the template will be able to access the HDA + with the variable name 'hda' (as in hda.title). + DEFAULT: keep the original query string name + --><!ATTLIST param type CDATA #IMPLIED default CDATA #IMPLIED Repository URL: https://bitbucket.org/galaxy/galaxy-central/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email.
participants (1)
-
commits-noreply@bitbucket.org