def main(htdocs_directory=None): logooptions = weblogolib.LogoOptions() # A list of form fields. # The default for checkbox values must be False (irrespective of # the default in logooptions) since a checked checkbox returns 'true' # but an unchecked checkbox returns nothing. controls = [ Field('sequences', ''), Field( 'format', 'png', weblogolib.formatters.get, options=[ 'png_print', 'png', 'jpeg', 'eps', 'pdf', 'svg', 'logodata' ], #TODO: Should copy list from __init__.formatters errmsg="Unknown format option."), Field('stacks_per_line', logooptions.stacks_per_line, int, errmsg='Invalid number of stacks per line.'), Field('stack_width', 'medium', weblogolib.std_sizes.get, options=['small', 'medium', 'large'], errmsg='Invalid logo size.'), Field('alphabet', 'alphabet_auto', alphabets.get, options=[ 'alphabet_auto', 'alphabet_protein', 'alphabet_dna', 'alphabet_rna' ], errmsg="Unknown sequence type."), Field('unit_name', 'bits', options=[ 'probability', 'bits', 'nats', 'kT', 'kJ/mol', 'kcal/mol' ]), Field('first_index', 1, int_or_none), Field('logo_start', '', int_or_none), Field('logo_end', '', int_or_none), Field('composition', 'comp_auto', composition.get, options=[ 'comp_none', 'comp_auto', 'comp_equiprobable', 'comp_CG', 'comp_Celegans', 'comp_Dmelanogaster', 'comp_Ecoli', 'comp_Hsapiens', 'comp_Mmusculus', 'comp_Scerevisiae' ], errmsg="Illegal sequence composition."), Field('percentCG', '', float_or_none, errmsg="Invalid CG percentage."), Field('show_errorbars', False, truth), Field('logo_title', logooptions.logo_title), Field('logo_label', logooptions.logo_label), Field('show_xaxis', False, truth), Field('xaxis_label', logooptions.xaxis_label), Field('show_yaxis', False, truth), Field('yaxis_label', logooptions.yaxis_label, string_or_none), Field('yaxis_scale', logooptions.yaxis_scale, float_or_none, errmsg="The yaxis scale must be a positive number."), Field('yaxis_tic_interval', logooptions.yaxis_tic_interval, float_or_none), Field('show_ends', False, truth), Field('show_fineprint', False, truth), Field('color_scheme', 'color_auto', color_schemes.get, options=color_schemes.keys(), errmsg='Unknown color scheme'), Field('color0', ''), Field('symbols0', ''), Field('desc0', ''), Field('color1', ''), Field('symbols1', ''), Field('desc1', ''), Field('color2', ''), Field('symbols2', ''), Field('desc2', ''), Field('color3', ''), Field('symbols3', ''), Field('desc3', ''), Field('color4', ''), Field('symbols4', ''), Field('desc4', ''), Field('ignore_lower_case', False, truth), Field('scale_width', False, truth), ] form = {} for c in controls: form[c.name] = c form_values = cgilib.FieldStorage() # Send default form? if len(form_values) == 0 or "cmd_reset" in form_values: # Load default truth values now. form['show_errorbars'].value = logooptions.show_errorbars form['show_xaxis'].value = logooptions.show_xaxis form['show_yaxis'].value = logooptions.show_yaxis form['show_ends'].value = logooptions.show_ends form['show_fineprint'].value = logooptions.show_fineprint form['scale_width'].value = logooptions.scale_width send_form(controls, htdocs_directory=htdocs_directory) return # Get form content for c in controls: c.value = form_values.getfirst(c.name, c.default) options_from_form = [ 'format', 'stacks_per_line', 'stack_width', 'alphabet', 'unit_name', 'first_index', 'logo_start', 'logo_end', 'composition', 'show_errorbars', 'logo_title', 'logo_label', 'show_xaxis', 'xaxis_label', 'show_yaxis', 'yaxis_label', 'yaxis_scale', 'yaxis_tic_interval', 'show_ends', 'show_fineprint', 'scale_width' ] errors = [] for optname in options_from_form: try: value = form[optname].get_value() if value != None: setattr(logooptions, optname, value) except ValueError as err: errors.append(err.args) # Construct custom color scheme custom = ColorScheme() for i in range(0, 5): color = form["color%d" % i].get_value() symbols = form["symbols%d" % i].get_value() desc = form["desc%d" % i].get_value() if color: try: custom.groups.append( weblogolib.ColorGroup(symbols, color, desc)) except ValueError as e: errors.append(('color%d' % i, "Invalid color: %s" % color)) if form["color_scheme"].value == 'color_custom': logooptions.color_scheme = custom else: try: logooptions.color_scheme = form["color_scheme"].get_value() except ValueError as err: errors.append(err.args) sequences = None # FIXME: Ugly fix: Must check that sequence_file key exists # FIXME: Sending malformed or missing form keys should not cause a crash # sequences_file = form["sequences_file"] if "sequences_file" in form_values: sequences = form_values.getvalue("sequences_file") #assert type(sequences) == str if not sequences or len(sequences) == 0: sequences = form["sequences"].get_value() if not sequences or len(sequences) == 0: errors.append(( "sequences", "Please enter a multiple-sequence alignment in the box above, or select a file to upload." )) # If we have uncovered errors or we want the chance to edit the logo # ("cmd_edit" command from examples page) then we return the form now. # We do not proceed to the time consuming logo creation step unless # required by a 'create' or 'validate' command, and no errors have been # found yet. if errors or "cmd_edit" in form_values: send_form(controls, errors, htdocs_directory) return try: comp = form["composition"].get_value() percentCG = form["percentCG"].get_value() ignore_lower_case = ("ignore_lower_case" in form_values) if comp == 'percentCG': comp = str(percentCG / 100) from corebio.matrix import Motif try: # Try reading data in transfac format first. # TODO Refactor this code motif = Motif.read_transfac(StringIO(sequences), alphabet=logooptions.alphabet) prior = weblogolib.parse_prior(comp, motif.alphabet) data = weblogolib.LogoData.from_counts(motif.alphabet, motif, prior) except ValueError as motif_err: seqs = weblogolib.read_seq_data( StringIO(sequences), alphabet=logooptions.alphabet, ignore_lower_case=ignore_lower_case) prior = weblogolib.parse_prior(comp, seqs.alphabet) data = weblogolib.LogoData.from_seqs(seqs, prior) logoformat = weblogolib.LogoFormat(data, logooptions) format = form["format"].value logo = weblogolib.formatters[format](data, logoformat) except ValueError as err: errors.append(err.args) except IOError as err: errors.append(err.args) except RuntimeError as err: errors.append(err.args) if errors or "cmd_validate" in form_values: send_form(controls, errors, htdocs_directory) return # # RETURN LOGO OVER HTTP # print("Content-Type:", mime_type[format]) # Content-Disposition: inline Open logo in browser window # Content-Disposition: attachment Download logo if "download" in form_values: print('Content-Disposition: attachment; ' \ 'filename="logo.%s"' % extension[format]) else: print('Content-Disposition: inline; ' \ 'filename="logo.%s"' % extension[format]) # Separate header from data print() # Finally, and at last, send the logo. if sys.version_info[0] >= 3: sys.stdout.buffer.write(logo) else: sys.stdout.write(logo)
def main(htdocs_directory=None): logooptions = weblogolib.LogoOptions() # A list of form fields. # The default for checkbox values must be False (irrespective of # the default in logooptions) since a checked checkbox returns 'true' # but an unchecked checkbox returns nothing. controls = [ Field('sequences', ''), Field('sequences_url', ''), Field( 'format', 'png', weblogolib.formatters.get, options=[ 'png_print', 'png', 'jpeg', 'eps', 'pdf', 'svg', 'logodata' ], #TODO: Should copy list from __init__.formatters errmsg="Unknown format option."), Field('stacks_per_line', logooptions.stacks_per_line, int, errmsg='Invalid number of stacks per line.'), Field('stack_width', 'medium', weblogolib.std_sizes.get, options=['small', 'medium', 'large'], errmsg='Invalid logo size.'), Field('alphabet', 'alphabet_auto', alphabets.get, options=[ 'alphabet_auto', 'alphabet_protein', 'alphabet_dna', 'alphabet_rna' ], errmsg="Unknown sequence type."), Field('unit_name', 'bits', options=[ 'probability', 'bits', 'nats', 'kT', 'kJ/mol', 'kcal/mol' ]), Field('first_index', 1, int_or_none), Field('logo_start', '', int_or_none), Field('logo_end', '', int_or_none), Field('composition', 'comp_auto', composition.get, options=[ 'comp_none', 'comp_auto', 'comp_equiprobable', 'comp_CG', 'comp_Celegans', 'comp_Dmelanogaster', 'comp_Ecoli', 'comp_Hsapiens', 'comp_Mmusculus', 'comp_Scerevisiae' ], errmsg="Illegal sequence composition."), Field('percentCG', '', float_or_none, errmsg="Invalid CG percentage."), Field('show_errorbars', False, truth), Field('logo_title', logooptions.logo_title), Field('logo_label', logooptions.logo_label), Field('show_xaxis', False, truth), Field('xaxis_label', logooptions.xaxis_label), Field('show_yaxis', False, truth), Field('yaxis_label', logooptions.yaxis_label, string_or_none), Field('yaxis_scale', logooptions.yaxis_scale, float_or_none, errmsg="The yaxis scale must be a positive number."), Field('yaxis_tic_interval', logooptions.yaxis_tic_interval, float_or_none), Field('show_ends', False, truth), Field('show_fineprint', False, truth), Field('color_scheme', 'color_auto', color_schemes.get, options=color_schemes.keys(), errmsg='Unknown color scheme'), Field('color0', ''), Field('symbols0', ''), Field('desc0', ''), Field('color1', ''), Field('symbols1', ''), Field('desc1', ''), Field('color2', ''), Field('symbols2', ''), Field('desc2', ''), Field('color3', ''), Field('symbols3', ''), Field('desc3', ''), Field('color4', ''), Field('symbols4', ''), Field('desc4', ''), Field('ignore_lower_case', False, truth), Field('scale_width', False, truth), ] form = {} for c in controls: form[c.name] = c form_values = cgilib.FieldStorage() # Send default form? if len(form_values) == 0 or "cmd_reset" in form_values: # Load default truth values now. form['show_errorbars'].value = logooptions.show_errorbars form['show_xaxis'].value = logooptions.show_xaxis form['show_yaxis'].value = logooptions.show_yaxis form['show_ends'].value = logooptions.show_ends form['show_fineprint'].value = logooptions.show_fineprint form['scale_width'].value = logooptions.scale_width send_form(controls, htdocs_directory=htdocs_directory) return # Get form content for c in controls: c.value = form_values.getfirst(c.name, c.default) options_from_form = [ 'format', 'stacks_per_line', 'stack_width', 'alphabet', 'unit_name', 'first_index', 'logo_start', 'logo_end', 'composition', 'show_errorbars', 'logo_title', 'logo_label', 'show_xaxis', 'xaxis_label', 'show_yaxis', 'yaxis_label', 'yaxis_scale', 'yaxis_tic_interval', 'show_ends', 'show_fineprint', 'scale_width' ] errors = [] for optname in options_from_form: try: value = form[optname].get_value() if value != None: setattr(logooptions, optname, value) except ValueError as err: errors.append(err.args) # Construct custom color scheme custom = ColorScheme() for i in range(0, 5): color = form["color%d" % i].get_value() symbols = form["symbols%d" % i].get_value() desc = form["desc%d" % i].get_value() if color: try: custom.groups.append( weblogolib.ColorGroup(symbols, color, desc)) except ValueError as e: errors.append(('color%d' % i, "Invalid color: %s" % color)) if form["color_scheme"].value == 'color_custom': logooptions.color_scheme = custom else: try: logooptions.color_scheme = form["color_scheme"].get_value() except ValueError as err: errors.append(err.args) # FIXME: Ugly fix: Must check that sequence_file key exists # FIXME: Sending malformed or missing form keys should not cause a crash # sequences_file = form["sequences_file"] sequences_from_file = None if "sequences_file" in form_values: sequences_from_file = form_values.getvalue("sequences_file") sequences_from_textfield = form["sequences"].get_value() sequences_url = form["sequences_url"].get_value() sequences = None seq_file = None if sequences_from_file: if sequences_from_textfield or sequences_url: errors.append( ("sequences_file", "Cannot upload, sequence source conflict")) else: sequences = sequences_from_file seq_file = StringIO(sequences) elif sequences_from_textfield: if sequences_url: errors.append( ("sequences", "Cannot upload, sequence source conflict")) else: # check SEQUENCES_MAXLENGT # If a user tries to paste a very large file into sequence textarea, # then WebLogo runs very slow for no apparently good reason. (Might be client side bug?) # So we limit the maximum sequence size. # Form field also limits size, but not necessarly respected. Also can truncate data # without warning, so we'll set textarea maximum to be larger than MAX_SEQUENCE_SIZE SEQUENCES_MAXLENGTH = 100000 if len(sequences_from_textfield) > SEQUENCES_MAXLENGTH: errors.append(( "sequences", "Sequence data too large for text input. Use file upload instead." )) controls[0] = Field('sequences', '') else: sequences = sequences_from_textfield seq_file = StringIO(sequences) elif sequences_url: from . import _from_URL_fileopen try: seq_file = _from_URL_fileopen(sequences_url) except ValueError, e: errors.append(("sequences_url", "Cannot parse URL")) except IOError, e: errors.append(("sequences_url", "Cannot load sequences from URL"))
'ovline', 'score_method', 'dmnumber', ] errors = [] for optname in options_from_form: try: value = form[optname].get_value() if value is not None: setattr(logooptions, optname, value) except ValueError, err: errors.append(err.args) # Construct custom color scheme custom = ColorScheme() for i in range(0, 5): color = form["color%d" % i].get_value() symbols = form["symbols%d" % i].get_value() desc = form["desc%d" % i].get_value() if color: try: custom.groups.append(ColorGroup(symbols, color, desc)) except ValueError, e: errors.append(('color%d' % i, "Invalid color: %s" % color)) if form["color_scheme"].value == 'color_custom': logooptions.color_scheme = custom else: try:
def _build_logoformat( logodata, opts) : """ Extract and process relevant option values and return a LogoFormat object.""" args = {} direct_from_opts = [ "stacks_per_line", "logo_title", "yaxis_label", "show_xaxis", "show_yaxis", "xaxis_label", "show_ends", "fineprint", "show_errorbars", "show_boxes", "yaxis_tic_interval", "resolution", "alphabet", "debug", "show_ends", "default_color", #"show_color_key", "color_scheme", "unit_name", "logo_label", "yaxis_scale", "first_index", "logo_start", "logo_end", "scale_width", "annotate", "stack_width", "stack_aspect_ratio", "score_method", "reverse_stacks" ] for k in direct_from_opts: args[k] = opts.__dict__[k] # logo_size = copy.copy(opts.__dict__['logo_size']) # size_from_opts = ["stack_width", "stack_height"] # for k in size_from_opts : # length = getattr(opts, k) # if length : setattr( logo_size, k, length ) # args["size"] = logo_size if opts.colors: color_scheme = ColorScheme() for color, symbols, desc in opts.colors: try : #c = Color.from_string(color) color_scheme.groups.append( ColorGroup(symbols, color, desc) ) except ValueError : raise ValueError( "error: option --color: invalid value: '%s'" % color ) args["color_scheme"] = color_scheme if opts.annotate: args["annotate"] = opts.annotate.split(',') logooptions = LogoOptions() for a, v in args.iteritems() : setattr(logooptions,a,v) theformat = LogoFormat(logodata, logooptions ) return theformat