| 1 |
# -------------------------------- WebLogo -------------------------------- |
| 2 |
|
| 3 |
# Copyright (c) 2003-2004 The Regents of the University of California. |
| 4 |
# Copyright (c) 2005 Gavin E. Crooks |
| 5 |
# Copyright (c) 2006-2015, The Regents of the University of California, through |
| 6 |
# Lawrence Berkeley National Laboratory (subject to receipt of any required |
| 7 |
# approvals from the U.S. Dept. of Energy). All rights reserved. |
| 8 |
|
| 9 |
# This software is distributed under the new BSD Open Source License. |
| 10 |
# <http://www.opensource.org/licenses/bsd-license.html> |
| 11 |
# |
| 12 |
# Redistribution and use in source and binary forms, with or without |
| 13 |
# modification, are permitted provided that the following conditions are met: |
| 14 |
# |
| 15 |
# (1) Redistributions of source code must retain the above copyright notice, |
| 16 |
# this list of conditions and the following disclaimer. |
| 17 |
# |
| 18 |
# (2) Redistributions in binary form must reproduce the above copyright |
| 19 |
# notice, this list of conditions and the following disclaimer in the |
| 20 |
# documentation and or other materials provided with the distribution. |
| 21 |
# |
| 22 |
# (3) Neither the name of the University of California, Lawrence Berkeley |
| 23 |
# National Laboratory, U.S. Dept. of Energy nor the names of its contributors |
| 24 |
# may be used to endorse or promote products derived from this software |
| 25 |
# without specific prior written permission. |
| 26 |
# |
| 27 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 28 |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 29 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 30 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
| 31 |
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 32 |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 33 |
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 34 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 35 |
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 36 |
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 37 |
# POSSIBILITY OF SUCH DAMAGE. |
| 38 |
|
| 39 |
""" """ |
| 40 |
|
| 41 |
import os |
| 42 |
import sys |
| 43 |
from datetime import datetime |
| 44 |
from io import StringIO, TextIOWrapper |
| 45 |
from math import log, sqrt |
| 46 |
from typing import Any, Callable, Dict, List, Optional, Union |
| 47 |
from urllib.parse import urlparse, urlunparse |
| 48 |
from urllib.request import Request, urlopen |
| 49 |
|
| 50 |
import numpy as np |
| 51 |
|
| 52 |
# Avoid 'from numpy import *' since numpy has lots of names defined |
| 53 |
from numpy import any, array, asarray, float64, ones, zeros |
| 54 |
from scipy.stats import entropy |
| 55 |
|
| 56 |
from . import __version__, seq_io |
| 57 |
from .color import Color |
| 58 |
from .colorscheme import ( |
| 59 |
ColorScheme, |
| 60 |
SymbolColor, |
| 61 |
base_pairing, |
| 62 |
charge, |
| 63 |
chemistry, |
| 64 |
hydrophobicity, |
| 65 |
monochrome, |
| 66 |
) |
| 67 |
from .data import amino_acid_composition |
| 68 |
from .logomath import Dirichlet |
| 69 |
from .seq import ( |
| 70 |
Alphabet, |
| 71 |
SeqList, |
| 72 |
unambiguous_dna_alphabet, |
| 73 |
unambiguous_protein_alphabet, |
| 74 |
unambiguous_rna_alphabet, |
| 75 |
) |
| 76 |
from .utils import ArgumentError, isfloat, stdrepr |
| 77 |
|
| 78 |
# Shorten development version string of the form weblogo-3.6.1.dev43+g64d9f12.d20190304 |
| 79 |
|
| 80 |
if __version__.find("+") != -1: |
| 81 |
__version__ = __version__[: __version__.find("+")] # pragma: no cover |
| 82 |
|
| 83 |
|
| 84 |
# from .logo_formatter import (GhostscriptAPI, pdf_formatter, jpeg_formatter, png_formatter, |
| 85 |
# png_print_formatter, |
| 86 |
# txt_formatter, eps_formatter, formatters, default_formatter) |
| 87 |
# ------ META DATA ------ |
| 88 |
|
| 89 |
|
| 90 |
# __all__ = ['LogoOptions', |
| 91 |
# 'description', |
| 92 |
# '__version__', |
| 93 |
# 'LogoFormat', |
| 94 |
# 'LogoData', |
| 95 |
# 'GhostscriptAPI', |
| 96 |
# 'std_color_schemes', |
| 97 |
# 'default_color_schemes', |
| 98 |
# 'classic', |
| 99 |
# 'std_units', |
| 100 |
# 'std_sizes', |
| 101 |
# 'std_alphabets', |
| 102 |
# 'std_percentCG', |
| 103 |
# 'pdf_formatter', |
| 104 |
# 'jpeg_formatter', |
| 105 |
# 'png_formatter', |
| 106 |
# 'png_print_formatter', |
| 107 |
# 'txt_formatter', |
| 108 |
# 'eps_formatter', |
| 109 |
# 'formatters', |
| 110 |
# 'default_formatter', |
| 111 |
# 'base_distribution', |
| 112 |
# 'equiprobable_distribution', |
| 113 |
# 'read_seq_data', |
| 114 |
# 'Color', |
| 115 |
# 'ColorScheme', |
| 116 |
# 'parse_prior', |
| 117 |
# 'release_description', |
| 118 |
# 'description' |
| 119 |
# ] |
| 120 |
|
| 121 |
description = "Create sequence logos from biological sequence alignments." |
| 122 |
|
| 123 |
release_description = "WebLogo %s" % (__version__) |
| 124 |
|
| 125 |
|
| 126 |
def cgi(htdocs_directory: str) -> None: # pragma: no cover |
| 127 |
import weblogo._cgi |
| 128 |
|
| 129 |
weblogo._cgi.main(htdocs_directory) |
| 130 |
|
| 131 |
|
| 132 |
aa_composition = [amino_acid_composition[_k] for _k in unambiguous_protein_alphabet] |
| 133 |
|
| 134 |
# ------ DATA ------ |
| 135 |
|
| 136 |
classic = ColorScheme( |
| 137 |
[ |
| 138 |
SymbolColor("G", "orange"), |
| 139 |
SymbolColor("TU", "red"), |
| 140 |
SymbolColor("C", "blue"), |
| 141 |
SymbolColor("A", "green"), |
| 142 |
] |
| 143 |
) |
| 144 |
|
| 145 |
std_color_schemes = { |
| 146 |
"auto": None, # Depends on sequence type |
| 147 |
"monochrome": monochrome, |
| 148 |
"base pairing": base_pairing, |
| 149 |
"classic": classic, |
| 150 |
"hydrophobicity": hydrophobicity, |
| 151 |
"chemistry": chemistry, |
| 152 |
"charge": charge, |
| 153 |
} |
| 154 |
|
| 155 |
default_color_schemes = { |
| 156 |
unambiguous_protein_alphabet: hydrophobicity, |
| 157 |
unambiguous_rna_alphabet: base_pairing, |
| 158 |
unambiguous_dna_alphabet: base_pairing, |
| 159 |
} |
| 160 |
|
| 161 |
std_units = { |
| 162 |
"bits": 1.0 / log(2), |
| 163 |
"nats": 1.0, |
| 164 |
"digits": 1.0 / log(10), |
| 165 |
"kT": 1.0, |
| 166 |
"kJ/mol": 8.314472 * 298.15 / 1000.0, |
| 167 |
"kcal/mol": 1.987 * 298.15 / 1000.0, |
| 168 |
"probability": None, |
| 169 |
} |
| 170 |
|
| 171 |
# The base stack width is set equal to 9pt Courier. |
| 172 |
# (Courier has a width equal to 3/5 of the point size.) |
| 173 |
# Check that can get 80 characters in journal page @small |
| 174 |
# 40 characters in a journal column |
| 175 |
std_sizes = {"small": 5.4, "medium": 5.4 * 2, "large": 5.4 * 3} |
| 176 |
|
| 177 |
std_alphabets = { |
| 178 |
"protein": unambiguous_protein_alphabet, |
| 179 |
"rna": unambiguous_rna_alphabet, |
| 180 |
"dna": unambiguous_dna_alphabet, |
| 181 |
} |
| 182 |
|
| 183 |
std_percentCG = { |
| 184 |
"H. sapiens": 40.0, |
| 185 |
"E. coli": 50.5, |
| 186 |
"S. cerevisiae": 38.0, |
| 187 |
"C. elegans": 36.0, |
| 188 |
"D. melanogaster": 43.0, |
| 189 |
"M. musculus": 42.0, |
| 190 |
"T. thermophilus": 69.4, |
| 191 |
} |
| 192 |
|
| 193 |
|
| 194 |
# Thermus thermophilus: Henne A, Bruggemann H, Raasch C, Wiezer A, Hartsch T, |
| 195 |
# Liesegang H, Johann A, Lienard T, Gohl O, Martinez-Arias R, Jacobi C, |
| 196 |
# Starkuviene V, Schlenczeck S, Dencker S, Huber R, Klenk HP, Kramer W, |
| 197 |
# Merkl R, Gottschalk G, Fritz HJ: The genome sequence of the extreme |
| 198 |
# thermophile Thermus thermophilus. |
| 199 |
# Nat Biotechnol 2004, 22:547-53 |
| 200 |
|
| 201 |
|
| 202 |
class LogoOptions: |
| 203 |
"""A container for all logo formatting options. Not all of these |
| 204 |
are directly accessible through the CLI or web interfaces. |
| 205 |
|
| 206 |
To display LogoOption defaults:: |
| 207 |
|
| 208 |
>>> from weblogo import * |
| 209 |
>>> LogoOptions() |
| 210 |
|
| 211 |
All physical lengths are measured in points. (72 points per inch, 28.3 points per cm) |
| 212 |
|
| 213 |
Args: |
| 214 |
creator_text: Embedded as comment in figures. |
| 215 |
logo_title: Creates title for the sequence logo |
| 216 |
logo_label: An optional figure label, added to the top left (e.g. '(a)'). |
| 217 |
unit_name: See std_units for options. (Default 'bits') |
| 218 |
yaxis_label: Defaults to unit_name |
| 219 |
xaxis_label: Add a label to the x-axis, or hide x-axis altogether. |
| 220 |
fineprint: Defaults to WebLogo name and version |
| 221 |
|
| 222 |
show_yaxis: Display entropy scale along y-axis (default: True) |
| 223 |
show_xaxis: Display sequence numbers along x-axis (default: True) |
| 224 |
show_ends: Display label at the ends of the sequence (default: False) |
| 225 |
show_fineprint: Toggle display of the WebLogo version information in the lower |
| 226 |
right corner. Optional, but we appreciate the acknowledgment. |
| 227 |
show_errorbars: Draw errorbars (default: False) |
| 228 |
show_boxes: Draw boxes around stack characters (default: True) |
| 229 |
debug: Draw extra graphics debugging information. |
| 230 |
rotate_numbers: Draw xaxis numbers with vertical orientation? |
| 231 |
scale_width: boolean, scale width of characters proportional to ungaps |
| 232 |
pad_right: Make a single line logo the same width as multiline logos |
| 233 |
(default: False) |
| 234 |
|
| 235 |
stacks_per_line: Maximum number of logo stacks per logo line. (Default: 40) |
| 236 |
yaxis_tic_interval: Distance between ticmarks on y-axis(default: 1.0) |
| 237 |
yaxis_minor_tic_ratio: Distance between minor tic ratio |
| 238 |
yaxis_scale: Sets height of the y-axis in designated units |
| 239 |
xaxis_tic_interval: Distance between ticmarks on x-axis(default: 1.0) |
| 240 |
number_interval: Distance between ticmarks (default: 1.0) |
| 241 |
|
| 242 |
shrink_fraction: Proportional shrinkage of characters if show_boxes is true. |
| 243 |
|
| 244 |
errorbar_fraction: Sets error bars display proportion |
| 245 |
errorbar_width_fraction: Sets error bars display |
| 246 |
errorbar_gray: Sets error bars' gray scale percentage (default .75) |
| 247 |
|
| 248 |
resolution: Dots per inch (default: 96). Used for bitmapped output |
| 249 |
formats |
| 250 |
|
| 251 |
default_color: Symbol color if not otherwise specified |
| 252 |
color_scheme: A custom color scheme can be specified using CSS2 (Cascading |
| 253 |
Style Sheet) syntax. |
| 254 |
E.g. 'red', '#F00', '#FF0000', 'rgb(255, 0, 0)', |
| 255 |
'rgb(100%, 0%, 0%)' or 'hsl(0, 100%, 50%)' for the color red. |
| 256 |
|
| 257 |
stack_width: Scale the visible stack width by the fraction of symbols in |
| 258 |
the column (I.e. columns with many gaps of unknowns are |
| 259 |
narrow.) (Default: yes) |
| 260 |
stack_aspect_ratio: Ratio of stack height to width (default: 5) |
| 261 |
|
| 262 |
logo_margin: Default: 2 pts |
| 263 |
stroke_width: Default: 0.5 pts |
| 264 |
tic_length: Default: 5 pts |
| 265 |
stack_margin: Default: 0.5 pts |
| 266 |
|
| 267 |
small_fontsize: Small text font size in points |
| 268 |
fontsize: Regular text font size in points |
| 269 |
title_fontsize: Title text font size in points |
| 270 |
number_fontsize: Font size for axis-numbers, in points. |
| 271 |
|
| 272 |
text_font: Select font for labels |
| 273 |
logo_font: Select font for Logo |
| 274 |
title_font: Select font for Logo's title |
| 275 |
|
| 276 |
first_index: Index of first position in sequence data |
| 277 |
logo_start: Lower bound of sequence to display |
| 278 |
logo_end: Upper bound of sequence to display |
| 279 |
|
| 280 |
""" |
| 281 |
|
| 282 |
def __init__(self, **kwargs: dict) -> None: |
| 283 |
"""Create a new LogoOptions instance. |
| 284 |
|
| 285 |
>>> logooptions = LogoOptions(logo_title = "Some Title String") |
| 286 |
>>> logooptions.show_yaxis = False |
| 287 |
>>> repr(logooptions) |
| 288 |
|
| 289 |
""" |
| 290 |
|
| 291 |
self.alphabet: Optional[Alphabet] = None |
| 292 |
|
| 293 |
self.creator_text = release_description |
| 294 |
|
| 295 |
self.logo_title = "" |
| 296 |
self.logo_label = "" |
| 297 |
self.stacks_per_line = 40 |
| 298 |
|
| 299 |
self.unit_name = "bits" |
| 300 |
|
| 301 |
self.show_yaxis = True |
| 302 |
# yaxis_lable default depends on other settings. See LogoFormat |
| 303 |
self.yaxis_label: Optional[str] = None |
| 304 |
self.yaxis_tic_interval = 1.0 |
| 305 |
self.yaxis_minor_tic_ratio = 5 |
| 306 |
self.yaxis_scale: Optional[float] = None |
| 307 |
|
| 308 |
self.show_xaxis = True |
| 309 |
self.xaxis_label = "" |
| 310 |
self.xaxis_tic_interval = 1 |
| 311 |
self.rotate_numbers = False |
| 312 |
self.number_interval = 5 |
| 313 |
self.show_ends = False |
| 314 |
self.annotate = None |
| 315 |
|
| 316 |
self.show_fineprint = True |
| 317 |
self.fineprint: str = "WebLogo " + ".".join(__version__.split(".")[0:3]) |
| 318 |
|
| 319 |
self.show_boxes = False |
| 320 |
self.shrink_fraction = 0.5 |
| 321 |
|
| 322 |
self.show_errorbars = True |
| 323 |
self.errorbar_fraction = 0.90 |
| 324 |
self.errorbar_width_fraction = 0.25 |
| 325 |
self.errorbar_gray = 0.75 |
| 326 |
|
| 327 |
self.resolution: int = 96 # Dots per inch |
| 328 |
|
| 329 |
self.default_color = Color.by_name("black") |
| 330 |
self.color_scheme: Optional[ColorScheme] = None |
| 331 |
# self.show_color_key = False # NOT yet implemented |
| 332 |
|
| 333 |
self.debug = False |
| 334 |
|
| 335 |
self.logo_margin = 2 |
| 336 |
self.stroke_width = 0.5 |
| 337 |
self.tic_length = 5 |
| 338 |
|
| 339 |
self.stack_width = std_sizes["medium"] |
| 340 |
self.stack_aspect_ratio = 5 |
| 341 |
|
| 342 |
self.stack_margin = 0.5 |
| 343 |
self.pad_right = False |
| 344 |
|
| 345 |
self.small_fontsize = 6 |
| 346 |
self.fontsize = 10 |
| 347 |
self.title_fontsize = 12 |
| 348 |
self.number_fontsize = 8 |
| 349 |
|
| 350 |
self.text_font = "ArialMT" |
| 351 |
self.logo_font = "Arial-BoldMT" |
| 352 |
self.title_font = "ArialMT" |
| 353 |
|
| 354 |
self.first_index = 1 |
| 355 |
self.logo_start: Optional[int] = None |
| 356 |
self.logo_end: Optional[int] = None |
| 357 |
self.scale_width = True |
| 358 |
|
| 359 |
self.reverse_stacks = True # If true, draw stacks with largest letters on top. |
| 360 |
|
| 361 |
for k, v in kwargs.items(): |
| 362 |
setattr(self, k, v) |
| 363 |
|
| 364 |
def __repr__(self) -> str: |
| 365 |
attributes = list(vars(self).keys()) |
| 366 |
attributes.sort() |
| 367 |
return stdrepr(self, attributes) |
| 368 |
|
| 369 |
|
| 370 |
# End class LogoOptions |
| 371 |
|
| 372 |
|
| 373 |
class LogoFormat(LogoOptions): |
| 374 |
"""Specifies the format of the logo. Requires LogoData and LogoOptions |
| 375 |
objects. |
| 376 |
|
| 377 |
>>> logodata = LogoData.from_seqs(seqs) |
| 378 |
>>> logooptions = LogoOptions() |
| 379 |
|
| 380 |
>>> logooptions.title = "A Logo Title" |
| 381 |
>>> format = LogoFormat(logodata, logooptions) |
| 382 |
|
| 383 |
Raises: |
| 384 |
ArgumentError: if arguments are invalid. |
| 385 |
""" |
| 386 |
|
| 387 |
def __init__( |
| 388 |
self, logodata: "LogoData", logooptions: Optional[LogoOptions] = None |
| 389 |
) -> None: |
| 390 |
"""Create a new LogoFormat instance.""" |
| 391 |
|
| 392 |
if logooptions is not None: |
| 393 |
self.__dict__.update(logooptions.__dict__) |
| 394 |
|
| 395 |
self.alphabet: Optional[Alphabet] = logodata.alphabet |
| 396 |
self.seqlen: Optional[int] = logodata.length |
| 397 |
|
| 398 |
# Derived parameters. |
| 399 |
self.show_title = False |
| 400 |
self.show_xaxis_label = False |
| 401 |
self.yaxis_minor_tic_interval = None |
| 402 |
self.lines_per_logo = None |
| 403 |
self.char_width = None # Maximum character width. Stack width minus margins. |
| 404 |
self.line_margin_left = None |
| 405 |
self.line_margin_right = None |
| 406 |
self.line_margin_bottom = None |
| 407 |
self.line_margin_top = None |
| 408 |
self.title_height = None |
| 409 |
self.xaxis_label_height = None |
| 410 |
self.line_height = None |
| 411 |
self.line_width = None |
| 412 |
self.logo_height: Optional[int] = None |
| 413 |
self.logo_width: Optional[int] = None |
| 414 |
self.creation_date = None |
| 415 |
self.end_type = None |
| 416 |
|
| 417 |
self.stack_height = self.stack_width * self.stack_aspect_ratio |
| 418 |
|
| 419 |
# Attribute to test, test, error message |
| 420 |
arg_conditions = ( |
| 421 |
("stacks_per_line", lambda x: x > 0, "Stacks per line must be positive."), |
| 422 |
( |
| 423 |
"stack_width", |
| 424 |
lambda x: x > 0.0, |
| 425 |
"Stack width must be greater than zero.", |
| 426 |
), |
| 427 |
( |
| 428 |
"stack_aspect_ratio", |
| 429 |
lambda x: x > 0, |
| 430 |
"Stack aspect ratio must be greater than zero.", |
| 431 |
), |
| 432 |
("fontsize", lambda x: x > 0, "Font sizes must be positive."), |
| 433 |
("small_fontsize", lambda x: x > 0, "Font sizes must be positive."), |
| 434 |
("title_fontsize", lambda x: x > 0, "Font sizes must be positive."), |
| 435 |
( |
| 436 |
"errorbar_fraction", |
| 437 |
lambda x: x >= 0.0 and x <= 1.0, |
| 438 |
"The visible fraction of the error bar must be between zero and one.", |
| 439 |
), |
| 440 |
( |
| 441 |
"yaxis_tic_interval", |
| 442 |
lambda x: x >= 0.0, |
| 443 |
"The yaxis tic interval cannot be negative.", |
| 444 |
), |
| 445 |
( |
| 446 |
"yaxis_minor_tic_interval", |
| 447 |
lambda x: not (x and x < 0.0), |
| 448 |
"Distances cannot be negative.", |
| 449 |
), |
| 450 |
( |
| 451 |
"xaxis_tic_interval", |
| 452 |
lambda x: x > 0.0, |
| 453 |
"Tic interval must be greater than zero.", |
| 454 |
), |
| 455 |
("number_interval", lambda x: x > 0.0, "Invalid interval between numbers."), |
| 456 |
( |
| 457 |
"shrink_fraction", |
| 458 |
lambda x: x >= 0.0 and x <= 1.0, |
| 459 |
"Invalid shrink fraction.", |
| 460 |
), |
| 461 |
("stack_margin", lambda x: x > 0.0, "Invalid stack margin."), |
| 462 |
("logo_margin", lambda x: x > 0.0, "Invalid logo margin."), |
| 463 |
("stroke_width", lambda x: x > 0.0, "Invalid stroke width."), |
| 464 |
("tic_length", lambda x: x > 0.0, "Invalid tic length."), |
| 465 |
) |
| 466 |
|
| 467 |
# Run arguments tests. The second, attribute argument to the ArgumentError is |
| 468 |
# used by the UI to provide user feedback. |
| 469 |
# FIXME: More validation |
| 470 |
for test in arg_conditions: |
| 471 |
if not test[1](getattr(self, test[0])): |
| 472 |
raise ArgumentError(test[2], test[0]) |
| 473 |
|
| 474 |
# Inclusive upper and lower bounds |
| 475 |
# FIXME: Validate here. Move from eps_formatter |
| 476 |
|
| 477 |
# asserts checks that defaults that were initialized to None have been set |
| 478 |
assert self.first_index is not None |
| 479 |
assert self.seqlen is not None |
| 480 |
|
| 481 |
if self.logo_start is None: |
| 482 |
self.logo_start = self.first_index |
| 483 |
|
| 484 |
assert self.logo_start is not None |
| 485 |
|
| 486 |
if self.logo_end is None: |
| 487 |
self.logo_end = self.seqlen + self.first_index - 1 |
| 488 |
|
| 489 |
assert self.logo_end is not None |
| 490 |
assert self.logo_start is not None |
| 491 |
self.total_stacks = self.logo_end - self.logo_start + 1 |
| 492 |
|
| 493 |
if self.total_stacks <= 0: |
| 494 |
raise ArgumentError("Logo must contain at least one stack", "logo_end") |
| 495 |
|
| 496 |
if self.logo_start - self.first_index < 0: |
| 497 |
raise ArgumentError( |
| 498 |
"Logo range extends before start of available sequence.", "logo_range" |
| 499 |
) |
| 500 |
|
| 501 |
if self.logo_end - self.first_index >= self.seqlen: |
| 502 |
raise ArgumentError( |
| 503 |
"Logo range extends beyond end of available sequence.", "logo_range" |
| 504 |
) |
| 505 |
|
| 506 |
if self.logo_title: |
| 507 |
self.show_title = True |
| 508 |
if not self.fineprint: |
| 509 |
self.show_fineprint = False |
| 510 |
if self.xaxis_label: |
| 511 |
self.show_xaxis_label = True |
| 512 |
|
| 513 |
if self.yaxis_label is None: |
| 514 |
self.yaxis_label = self.unit_name |
| 515 |
|
| 516 |
assert self.yaxis_label is not None |
| 517 |
if self.yaxis_label: |
| 518 |
self.show_yaxis_label = True |
| 519 |
else: |
| 520 |
self.show_yaxis_label = False |
| 521 |
self.show_ends = False |
| 522 |
|
| 523 |
if not self.yaxis_scale: |
| 524 |
conversion_factor = std_units[self.unit_name] |
| 525 |
if conversion_factor: |
| 526 |
if self.alphabet is None: |
| 527 |
raise ArgumentError("Need an alphabet", "alphabet") |
| 528 |
|
| 529 |
assert self.alphabet is not None |
| 530 |
self.yaxis_scale = log(len(self.alphabet)) * conversion_factor |
| 531 |
else: |
| 532 |
self.yaxis_scale = 1.0 # probability units |
| 533 |
|
| 534 |
if self.yaxis_scale <= 0.0: |
| 535 |
raise ArgumentError( |
| 536 |
"Invalid yaxis scale", |
| 537 |
"yaxis_scale", |
| 538 |
) |
| 539 |
|
| 540 |
if self.yaxis_tic_interval >= self.yaxis_scale: |
| 541 |
self.yaxis_tic_interval /= 2.0 |
| 542 |
|
| 543 |
self.yaxis_minor_tic_interval = ( |
| 544 |
float(self.yaxis_tic_interval) / self.yaxis_minor_tic_ratio |
| 545 |
) |
| 546 |
|
| 547 |
if self.color_scheme is None: |
| 548 |
if self.alphabet in default_color_schemes: |
| 549 |
self.color_scheme = default_color_schemes[self.alphabet] |
| 550 |
else: |
| 551 |
self.color_scheme = monochrome |
| 552 |
|
| 553 |
self.lines_per_logo = 1 + ((self.total_stacks - 1) // self.stacks_per_line) |
| 554 |
|
| 555 |
if self.lines_per_logo == 1 and not self.pad_right: |
| 556 |
self.stacks_per_line = min(self.stacks_per_line, self.total_stacks) |
| 557 |
|
| 558 |
self.char_width = self.stack_width - 2 * self.stack_margin |
| 559 |
|
| 560 |
if self.show_yaxis: |
| 561 |
self.line_margin_left = self.fontsize * 3.0 |
| 562 |
else: |
| 563 |
if self.show_ends and self.show_xaxis: |
| 564 |
self.line_margin_left = self.fontsize * 1.5 |
| 565 |
else: |
| 566 |
self.line_margin_left = 4 |
| 567 |
|
| 568 |
if self.show_ends and self.show_xaxis: |
| 569 |
self.line_margin_right = self.fontsize * 1.5 |
| 570 |
else: |
| 571 |
self.line_margin_right = 4 |
| 572 |
|
| 573 |
if self.show_xaxis: |
| 574 |
if self.rotate_numbers: |
| 575 |
self.line_margin_bottom = self.number_fontsize * 2.5 |
| 576 |
else: |
| 577 |
self.line_margin_bottom = self.number_fontsize * 1.5 |
| 578 |
else: |
| 579 |
self.line_margin_bottom = 4 |
| 580 |
|
| 581 |
self.line_margin_top = 4 |
| 582 |
|
| 583 |
if self.show_title: |
| 584 |
self.title_height = self.title_fontsize |
| 585 |
else: |
| 586 |
self.title_height = 0 |
| 587 |
|
| 588 |
self.xaxis_label_height = 0.0 |
| 589 |
if self.show_xaxis_label: |
| 590 |
self.xaxis_label_height += self.fontsize |
| 591 |
if self.show_fineprint: |
| 592 |
if len(self.fineprint) != 0: |
| 593 |
self.xaxis_label_height += self.small_fontsize |
| 594 |
|
| 595 |
self.line_height = ( |
| 596 |
self.stack_height + self.line_margin_top + self.line_margin_bottom |
| 597 |
) |
| 598 |
self.line_width = ( |
| 599 |
self.stack_width * self.stacks_per_line |
| 600 |
+ self.line_margin_left |
| 601 |
+ self.line_margin_right |
| 602 |
) |
| 603 |
|
| 604 |
self.logo_height = int( |
| 605 |
2 * self.logo_margin |
| 606 |
+ self.title_height |
| 607 |
+ self.xaxis_label_height |
| 608 |
+ self.line_height * self.lines_per_logo |
| 609 |
) |
| 610 |
self.logo_width = int(2 * self.logo_margin + self.line_width) |
| 611 |
|
| 612 |
self.creation_date = datetime.now().isoformat(" ") |
| 613 |
|
| 614 |
end_type = "-" |
| 615 |
end_types = { |
| 616 |
unambiguous_protein_alphabet: "p", |
| 617 |
unambiguous_rna_alphabet: "-", |
| 618 |
unambiguous_dna_alphabet: "d", |
| 619 |
} |
| 620 |
if self.show_ends and self.alphabet in end_types: |
| 621 |
end_type = end_types[self.alphabet] |
| 622 |
self.end_type = end_type |
| 623 |
|
| 624 |
if self.annotate is None: |
| 625 |
self.annotate: list = [] |
| 626 |
|
| 627 |
for i in range(self.seqlen): |
| 628 |
index = i + self.first_index |
| 629 |
if index % self.number_interval == 0: |
| 630 |
self.annotate.append("%d" % index) |
| 631 |
else: |
| 632 |
self.annotate.append("") |
| 633 |
|
| 634 |
if len(self.annotate) != self.seqlen: |
| 635 |
raise ArgumentError( |
| 636 |
"Annotations must be same length as sequences.", "annotate" |
| 637 |
) |
| 638 |
|
| 639 |
# End __init__ |
| 640 |
|
| 641 |
|
| 642 |
# End class LogoFormat |
| 643 |
|
| 644 |
|
| 645 |
def parse_prior( |
| 646 |
composition: Any, alphabet: Alphabet, weight: Optional[float] = None |
| 647 |
) -> Optional[np.ndarray]: |
| 648 |
"""Parse a description of the expected monomer distribution of a sequence. |
| 649 |
|
| 650 |
Valid compositions: |
| 651 |
|
| 652 |
* None or 'none' |
| 653 |
No composition specified |
| 654 |
* 'auto' or 'automatic' |
| 655 |
Use the typical average distribution |
| 656 |
for proteins and an equiprobable distribution for |
| 657 |
everything else. |
| 658 |
* 'equiprobable' |
| 659 |
All monomers have the same probability. |
| 660 |
* a percentage, e.g. '45%' or a fraction '0.45' |
| 661 |
The fraction of CG bases for nucleotide alphabets |
| 662 |
* a species name, e.g. 'E. coli', 'H. sapiens', |
| 663 |
Use the average CG percentage for the species's genome. |
| 664 |
* An explicit distribution |
| 665 |
e.g. {'A':10, 'C':40, 'G':40, 'T':10} |
| 666 |
|
| 667 |
returns a dict of {monomer: probability} pairs. |
| 668 |
""" |
| 669 |
if composition is None: |
| 670 |
return None |
| 671 |
|
| 672 |
comp = composition.strip() |
| 673 |
|
| 674 |
if comp.lower() == "none": |
| 675 |
return None |
| 676 |
|
| 677 |
if weight is None and alphabet is not None: |
| 678 |
weight = sqrt(float(len(alphabet))) |
| 679 |
|
| 680 |
if weight < 0: |
| 681 |
raise ValueError("Weight cannot be negative.") |
| 682 |
|
| 683 |
if comp.lower() == "equiprobable": |
| 684 |
prior: np.ndarray |
| 685 |
prior = weight * equiprobable_distribution(len(alphabet)) |
| 686 |
|
| 687 |
elif comp.lower() == "auto" or comp.lower() == "automatic": |
| 688 |
if alphabet == unambiguous_protein_alphabet: |
| 689 |
prior = weight * asarray(aa_composition, float64) |
| 690 |
else: |
| 691 |
prior = weight * equiprobable_distribution(len(alphabet)) |
| 692 |
|
| 693 |
elif comp in std_percentCG: |
| 694 |
prior = weight * base_distribution(std_percentCG[comp]) |
| 695 |
|
| 696 |
elif comp[-1] == "%": |
| 697 |
prior = weight * base_distribution(float(comp[:-1])) |
| 698 |
|
| 699 |
elif isfloat(comp): |
| 700 |
prior = weight * base_distribution(float(comp) * 100.0) |
| 701 |
|
| 702 |
elif composition[0] == "{" and composition[-1] == "}": |
| 703 |
explicit = composition[1:-1] |
| 704 |
explicit = ( |
| 705 |
explicit.replace(",", " ") |
| 706 |
.replace("'", " ") |
| 707 |
.replace('"', " ") |
| 708 |
.replace(":", " ") |
| 709 |
.split() |
| 710 |
) |
| 711 |
|
| 712 |
if len(explicit) != len(alphabet) * 2: |
| 713 |
raise ValueError("Explicit prior does not match length of alphabet") |
| 714 |
prior = -ones(len(alphabet), float64) |
| 715 |
try: |
| 716 |
for r in range(len(explicit) // 2): |
| 717 |
letter = explicit[r * 2] |
| 718 |
index = alphabet.ord(letter) |
| 719 |
value = float(explicit[r * 2 + 1]) |
| 720 |
prior[index] = value |
| 721 |
except ValueError: |
| 722 |
raise ValueError("Cannot parse explicit composition") |
| 723 |
|
| 724 |
if any(prior == -1.0): |
| 725 |
raise ValueError( |
| 726 |
"Explicit prior does not match alphabet" |
| 727 |
) # pragma: no cover |
| 728 |
prior /= sum(prior) |
| 729 |
prior *= weight |
| 730 |
|
| 731 |
else: |
| 732 |
raise ValueError("Unknown or malformed composition: %s" % composition) |
| 733 |
|
| 734 |
if len(prior) != len(alphabet): |
| 735 |
raise ValueError( |
| 736 |
"The sequence alphabet and composition are incompatible." |
| 737 |
) # pragma: no cover |
| 738 |
return prior |
| 739 |
|
| 740 |
|
| 741 |
def base_distribution(percentCG: float) -> np.ndarray: |
| 742 |
A = (1.0 - (percentCG / 100.0)) / 2.0 |
| 743 |
C = (percentCG / 100.0) / 2.0 |
| 744 |
G = (percentCG / 100.0) / 2.0 |
| 745 |
T = (1.0 - (percentCG / 100)) / 2.0 |
| 746 |
return asarray((A, C, G, T), float64) |
| 747 |
|
| 748 |
|
| 749 |
def equiprobable_distribution(length: int) -> np.ndarray: |
| 750 |
return ones((length), float64) / length |
| 751 |
|
| 752 |
|
| 753 |
def _seq_formats() -> Dict[str, str]: |
| 754 |
"""Return a dictionary mapping between the names of formats for the sequence data |
| 755 |
and the corresponding parsers. |
| 756 |
""" |
| 757 |
# Add position weight matrix formats to input parsers by hand |
| 758 |
fin_choices = dict(seq_io.format_names()) |
| 759 |
fin_choices["transfac"] = "transfac" |
| 760 |
del fin_choices["plain"] |
| 761 |
return fin_choices |
| 762 |
|
| 763 |
|
| 764 |
def _seq_names() -> List[str]: |
| 765 |
"""Returns a list of the names of accepted sequence data formats.""" |
| 766 |
fin_names = [f.names[0] for f in seq_io.formats] # type: ignore |
| 767 |
fin_names.remove("plain") |
| 768 |
fin_names.append("transfac") |
| 769 |
return fin_names |
| 770 |
|
| 771 |
|
| 772 |
def read_seq_data( |
| 773 |
fin: Union[StringIO, TextIOWrapper, None], |
| 774 |
input_parser: Callable = seq_io.read, |
| 775 |
alphabet: Optional[Alphabet] = None, |
| 776 |
ignore_lower_case: bool = False, |
| 777 |
max_file_size: int = 0, |
| 778 |
) -> SeqList: |
| 779 |
"""Read sequence data from the input stream and return a seqs object. |
| 780 |
|
| 781 |
The environment variable WEBLOGO_MAX_FILE_SIZE overides the max_file_size argument. |
| 782 |
Used to limit the load on the WebLogo webserver. |
| 783 |
""" |
| 784 |
|
| 785 |
max_file_size = int(os.environ.get("WEBLOGO_MAX_FILE_SIZE", max_file_size)) |
| 786 |
|
| 787 |
# If max_file_size is set, or if fin==stdin (which is non-seekable), we |
| 788 |
# read the data and replace fin with a StringIO object. |
| 789 |
assert fin is not None |
| 790 |
|
| 791 |
if max_file_size > 0: |
| 792 |
data = fin.read(max_file_size) |
| 793 |
|
| 794 |
more_data = fin.read(2) |
| 795 |
if more_data != "": |
| 796 |
raise IOError("File exceeds maximum allowed size: %d bytes" % max_file_size) |
| 797 |
fin = StringIO(data) |
| 798 |
elif fin == sys.stdin: |
| 799 |
fin = StringIO(fin.read()) |
| 800 |
|
| 801 |
fin.seek(0) |
| 802 |
seqs = input_parser(fin) |
| 803 |
|
| 804 |
if seqs is None or len(seqs) == 0: |
| 805 |
raise ValueError("Please provide a multiple sequence alignment") |
| 806 |
|
| 807 |
if ignore_lower_case: |
| 808 |
# Case is significant. Do not count lower case letters. |
| 809 |
for i, s in enumerate(seqs): |
| 810 |
seqs[i] = s.mask() |
| 811 |
|
| 812 |
# Add alphabet to seqs. |
| 813 |
if alphabet: |
| 814 |
seqs.alphabet = Alphabet(str(alphabet)) |
| 815 |
else: |
| 816 |
seqs.alphabet = Alphabet.which(seqs) |
| 817 |
return seqs |
| 818 |
|
| 819 |
|
| 820 |
class LogoData: |
| 821 |
"""The data needed to generate a sequence logo. |
| 822 |
|
| 823 |
Args: |
| 824 |
alphabet: The set of symbols to count. |
| 825 |
See also --sequence-type, --ignore-lower-case |
| 826 |
length: All sequences must be the same length, else WebLogo will return an error |
| 827 |
counts: An array of character counts |
| 828 |
entropy: The relative entropy of each column |
| 829 |
entropy_interval: entropy confidence interval |
| 830 |
""" |
| 831 |
|
| 832 |
def __init__( |
| 833 |
self, |
| 834 |
length: Optional[int] = None, |
| 835 |
alphabet: Optional[Alphabet] = None, |
| 836 |
counts: Optional[np.ndarray] = None, |
| 837 |
entropy: Optional[np.ndarray] = None, |
| 838 |
entropy_interval: Optional[np.ndarray] = None, |
| 839 |
weight: Optional[np.ndarray] = None, |
| 840 |
) -> None: |
| 841 |
"""Creates a new LogoData object""" |
| 842 |
self.length = length |
| 843 |
self.alphabet = alphabet |
| 844 |
self.counts = counts |
| 845 |
self.entropy = entropy |
| 846 |
self.entropy_interval = entropy_interval |
| 847 |
self.weight = weight |
| 848 |
|
| 849 |
@classmethod |
| 850 |
def from_counts( |
| 851 |
cls, |
| 852 |
alphabet: Optional[Alphabet], |
| 853 |
counts: np.ndarray, |
| 854 |
prior: Optional[np.ndarray] = None, |
| 855 |
) -> "LogoData": |
| 856 |
"""Build a LogoData object from counts.""" |
| 857 |
# Counts is a Motif object? |
| 858 |
# counts = counts.array |
| 859 |
|
| 860 |
seq_length, A = counts.shape |
| 861 |
|
| 862 |
if prior is not None: |
| 863 |
prior = array(prior, float64) |
| 864 |
|
| 865 |
if prior is None or sum(prior) == 0.0: |
| 866 |
R = log(A) |
| 867 |
ent = zeros(seq_length, float64) |
| 868 |
entropy_interval = None |
| 869 |
for i in range(0, seq_length): |
| 870 |
C = sum(counts[i]) |
| 871 |
# FIXME: fixup .moremath.entropy()? |
| 872 |
if C == 0: |
| 873 |
ent[i] = 0.0 |
| 874 |
else: |
| 875 |
ent[i] = R - entropy(counts[i]) |
| 876 |
else: |
| 877 |
ent = zeros(seq_length, float64) |
| 878 |
entropy_interval = zeros((seq_length, 2), float64) |
| 879 |
|
| 880 |
R = log(A) |
| 881 |
|
| 882 |
for i in range(0, seq_length): |
| 883 |
alpha = array(counts[i], float64) |
| 884 |
alpha += prior |
| 885 |
|
| 886 |
posterior = Dirichlet(alpha) |
| 887 |
ent[i] = posterior.mean_relative_entropy(prior / sum(prior)) |
| 888 |
( |
| 889 |
entropy_interval[i][0], |
| 890 |
entropy_interval[i][1], |
| 891 |
) = posterior.interval_relative_entropy(prior / sum(prior), 0.95) |
| 892 |
|
| 893 |
weight = array(np.sum(counts, axis=1), float) |
| 894 |
max_weight = max(weight) |
| 895 |
if max_weight == 0.0: |
| 896 |
raise ValueError("No counts.") |
| 897 |
weight /= max_weight |
| 898 |
|
| 899 |
return cls(seq_length, alphabet, counts, ent, entropy_interval, weight) |
| 900 |
|
| 901 |
@classmethod |
| 902 |
def from_seqs(cls, seqs: SeqList, prior: Optional[np.ndarray] = None) -> "LogoData": |
| 903 |
"""Build a LogoData object from a SeqList, a list of sequences.""" |
| 904 |
# --- VALIDATE DATA --- |
| 905 |
# check that at least one sequence of length at least 1 long |
| 906 |
if len(seqs) == 0 or len(seqs[0]) == 0: |
| 907 |
raise ValueError("No sequence data found.") |
| 908 |
|
| 909 |
# Check sequence lengths |
| 910 |
seq_length = len(seqs[0]) |
| 911 |
for i, s in enumerate(seqs): |
| 912 |
# print(i, s, len(s)) |
| 913 |
# TODO: Redundant? Should be checked in SeqList? |
| 914 |
if seq_length != len(s): |
| 915 |
raise ArgumentError( |
| 916 |
"Sequence number %d differs in length from the previous sequences" |
| 917 |
% (i + 1), |
| 918 |
"sequences", |
| 919 |
) |
| 920 |
|
| 921 |
# FIXME: Check seqs.alphabet? |
| 922 |
|
| 923 |
counts = seqs.profile() |
| 924 |
return cls.from_counts(seqs.alphabet, counts, prior) |
| 925 |
|
| 926 |
def __str__(self) -> str: |
| 927 |
out = StringIO() |
| 928 |
print("## LogoData", file=out) |
| 929 |
print("# First column is position number, counting from zero", file=out) |
| 930 |
print("# Subsequent columns are raw symbol counts", file=out) |
| 931 |
print("# Entropy is mean entropy measured in nats.", file=out) |
| 932 |
print("# Low and High are the 95% confidence limits.", file=out) |
| 933 |
print("# Weight is the fraction of non-gap symbols in the column.", file=out) |
| 934 |
print("#\t", file=out) |
| 935 |
# Show column names |
| 936 |
print("#", end="\t", file=out) |
| 937 |
|
| 938 |
# asserts checks that defaults that were initialized to None have been set |
| 939 |
assert self.alphabet is not None |
| 940 |
assert self.length is not None |
| 941 |
assert self.counts is not None |
| 942 |
assert self.entropy is not None |
| 943 |
|
| 944 |
for a in self.alphabet: |
| 945 |
print(a, end=" \t", file=out) |
| 946 |
print("Entropy\tLow\tHigh\tWeight", file=out) |
| 947 |
|
| 948 |
# Write the data table |
| 949 |
|
| 950 |
for i in range(self.length): |
| 951 |
print(i + 1, end=" \t", file=out) |
| 952 |
|
| 953 |
for c in self.counts[i]: |
| 954 |
print(c, end=" \t", file=out) |
| 955 |
print("%6.4f" % self.entropy[i], end=" \t", file=out) |
| 956 |
if self.entropy_interval is not None: |
| 957 |
print("%6.4f" % self.entropy_interval[i][0], end=" \t", file=out) |
| 958 |
print("%6.4f" % self.entropy_interval[i][1], end=" \t", file=out) |
| 959 |
else: |
| 960 |
print("\t", "\t", end="", file=out) |
| 961 |
if self.weight is not None: |
| 962 |
print("%6.4f" % self.weight[i], end="", file=out) |
| 963 |
print("", file=out) |
| 964 |
print("# End LogoData", file=out) |
| 965 |
|
| 966 |
return out.getvalue() |
| 967 |
|
| 968 |
def csv(self) -> str: |
| 969 |
"""Return logodata as a csv formatted string""" |
| 970 |
out = StringIO() |
| 971 |
|
| 972 |
# asserts checks that defaults that were initialized to None have been set |
| 973 |
assert self.alphabet is not None |
| 974 |
assert self.length is not None |
| 975 |
assert self.counts is not None |
| 976 |
assert self.entropy is not None |
| 977 |
|
| 978 |
# Show column names |
| 979 |
print("Position", end=",", file=out) |
| 980 |
|
| 981 |
for a in self.alphabet: |
| 982 |
print(a, end=",", file=out) |
| 983 |
print("Entropy,Low,High,Weight", file=out) |
| 984 |
|
| 985 |
# Write the data table |
| 986 |
|
| 987 |
for i in range(self.length): |
| 988 |
print(i + 1, end=",", file=out) |
| 989 |
|
| 990 |
for c in self.counts[i]: |
| 991 |
print(c, end=",", file=out) |
| 992 |
print("%6.4f" % self.entropy[i], end=",", file=out) |
| 993 |
if self.entropy_interval is not None: |
| 994 |
print("%6.4f" % self.entropy_interval[i][0], end=",", file=out) |
| 995 |
print("%6.4f" % self.entropy_interval[i][1], end=",", file=out) |
| 996 |
else: |
| 997 |
print(",", ",", end="", file=out) |
| 998 |
if self.weight is not None: |
| 999 |
print("%6.4f" % self.weight[i], end="", file=out) |
| 1000 |
print("", file=out) |
| 1001 |
return out.getvalue() |
| 1002 |
|
| 1003 |
|
| 1004 |
def _from_URL_fileopen(target_url: str) -> StringIO: # pragma: no cover |
| 1005 |
"""opens files from a remote URL location""" |
| 1006 |
|
| 1007 |
# parsing url in component parts |
| 1008 |
(scheme, net_location, path, param, query, frag) = urlparse(target_url) |
| 1009 |
|
| 1010 |
# checks if string is URL link |
| 1011 |
if scheme != "http" and scheme != "https" and scheme != "ftp": |
| 1012 |
raise ValueError("Cannot open url: %s", target_url) |
| 1013 |
|
| 1014 |
# checks for dropbox link |
| 1015 |
if net_location == "www.dropbox.com": |
| 1016 |
# changes dropbox http link into download link |
| 1017 |
if query == "dl=0": |
| 1018 |
query2 = "dl=1" |
| 1019 |
|
| 1020 |
# rebuild download URL, with new query2 variable |
| 1021 |
target_url = urlunparse((scheme, net_location, path, param, query2, "")) |
| 1022 |
|
| 1023 |
# checks for google drive link |
| 1024 |
if net_location == "drive.google.com": |
| 1025 |
# link configuration for direct download instead of html frame |
| 1026 |
google_directdl_frag = "https://docs.google.com/uc?export=download&id=" |
| 1027 |
|
| 1028 |
# pull file id |
| 1029 |
(scheme, net_location, path_raw, param, query, frag) = urlparse(target_url) |
| 1030 |
id_file = path_raw.split("/")[3] |
| 1031 |
|
| 1032 |
# rebuild URL for direct download |
| 1033 |
target_url = google_directdl_frag + id_file |
| 1034 |
|
| 1035 |
# save url to temporary file |
| 1036 |
req = Request(target_url) |
| 1037 |
res = urlopen(req) |
| 1038 |
|
| 1039 |
return StringIO(str(res.read())) |