| 1 |
""" |
| 2 |
Core models used in the ToolContract and Resolved ToolContract |
| 3 |
Large parts of this are pulled from pbsmrtpipe. |
| 4 |
|
| 5 |
Author: Michael Kocher |
| 6 |
""" |
| 7 |
|
| 8 |
import datetime |
| 9 |
import functools |
| 10 |
import json |
| 11 |
import logging |
| 12 |
import os |
| 13 |
import re |
| 14 |
import traceback |
| 15 |
import types |
| 16 |
import uuid |
| 17 |
import warnings |
| 18 |
from collections import namedtuple, OrderedDict |
| 19 |
|
| 20 |
from pbcommand import to_ascii |
| 21 |
|
| 22 |
log = logging.getLogger(__name__) |
| 23 |
|
| 24 |
REGISTERED_FILE_TYPES = {} |
| 25 |
|
| 26 |
|
| 27 |
DataSetMetaData = namedtuple("DataSetMetaData", 'uuid metatype name') |
| 28 |
|
| 29 |
|
| 30 |
class PacBioNamespaces: |
| 31 |
|
| 32 |
|
| 33 |
NEW_FILE_PREFIX = "PacBio.FileTypes" |
| 34 |
|
| 35 |
DATASET_FILE_PREFIX = "PacBio.DataSet" |
| 36 |
|
| 37 |
PB_INDEX = "PacBio.Index" |
| 38 |
|
| 39 |
|
| 40 |
def __to_type(prefix, name): |
| 41 |
return ".".join([prefix, name]) |
| 42 |
|
| 43 |
|
| 44 |
to_file_ns = functools.partial(__to_type, PacBioNamespaces.NEW_FILE_PREFIX) |
| 45 |
to_ds_ns = functools.partial(__to_type, PacBioNamespaces.DATASET_FILE_PREFIX) |
| 46 |
to_index_ns = functools.partial(__to_type, PacBioNamespaces.PB_INDEX) |
| 47 |
|
| 48 |
|
| 49 |
class TaskOptionTypes: |
| 50 |
"""Core Task Option type id type""" |
| 51 |
|
| 52 |
INT = "integer" |
| 53 |
BOOL = "boolean" |
| 54 |
STR = "string" |
| 55 |
FLOAT = "float" |
| 56 |
FILE = "file" |
| 57 |
|
| 58 |
CHOICE_STR = "choice_string" |
| 59 |
CHOICE_INT = "choice_integer" |
| 60 |
CHOICE_FLOAT = "choice_float" |
| 61 |
|
| 62 |
@classmethod |
| 63 |
def ALL(cls): |
| 64 |
"""Return a set of all Task Option Types""" |
| 65 |
return {cls.INT, cls.BOOL, cls.STR, cls.FLOAT, cls.CHOICE_STR, |
| 66 |
cls.CHOICE_INT, cls.CHOICE_FLOAT, cls.FILE} |
| 67 |
|
| 68 |
@classmethod |
| 69 |
def _raise_value_error(cls, value, allowed, option_type_name): |
| 70 |
raise ValueError("Incompatible task {o} option type id '{s}'. " |
| 71 |
"Allowed values {v}".format(o=option_type_name, |
| 72 |
s=value, |
| 73 |
v=",".join(allowed))) |
| 74 |
|
| 75 |
@classmethod |
| 76 |
def ALL_SIMPLE(cls): |
| 77 |
"""Returns a set of 'simple' task option types (e.g., boolean, string, int, float)""" |
| 78 |
return {cls.STR, cls.BOOL, cls.INT, cls.FLOAT, cls.FILE} |
| 79 |
|
| 80 |
@classmethod |
| 81 |
def from_simple_str(cls, sx): |
| 82 |
"""Validates a string is a validate task option type id or raise ValueError |
| 83 |
|
| 84 |
:raises ValueError |
| 85 |
""" |
| 86 |
if sx in cls.ALL_SIMPLE(): |
| 87 |
return sx |
| 88 |
else: |
| 89 |
cls._raise_value_error(sx, cls.ALL_SIMPLE(), "simple") |
| 90 |
|
| 91 |
@classmethod |
| 92 |
def ALL_CHOICES(cls): |
| 93 |
"""Returns a set of choice task option types""" |
| 94 |
return {cls.CHOICE_INT, cls.CHOICE_FLOAT, cls.CHOICE_STR} |
| 95 |
|
| 96 |
@classmethod |
| 97 |
def is_choice(cls, sx): |
| 98 |
return sx in cls.ALL_CHOICES() |
| 99 |
|
| 100 |
@classmethod |
| 101 |
def from_choice_str(cls, sx): |
| 102 |
"""Validates and returns a task choice option type or raises ValueError""" |
| 103 |
if sx in cls.ALL_CHOICES(): |
| 104 |
return sx |
| 105 |
else: |
| 106 |
cls._raise_value_error(sx, cls.ALL_CHOICES(), "choice") |
| 107 |
|
| 108 |
@classmethod |
| 109 |
def from_str(cls, sx): |
| 110 |
"""Validates and returns a valid type option type id or raises ValueError, |
| 111 |
|
| 112 |
:note: For legacy reasons, "number" will be mapped to "float" |
| 113 |
""" |
| 114 |
|
| 115 |
if sx == "number": |
| 116 |
sx = TaskOptionTypes.FLOAT |
| 117 |
|
| 118 |
if sx in TaskOptionTypes.ALL(): |
| 119 |
return sx |
| 120 |
else: |
| 121 |
cls._raise_value_error(sx, cls.ALL(), "") |
| 122 |
|
| 123 |
@classmethod |
| 124 |
def from_any(cls, val): |
| 125 |
if isinstance(val, bool): |
| 126 |
return cls.BOOL |
| 127 |
elif isinstance(val, int): |
| 128 |
return cls.INT |
| 129 |
elif isinstance(val, float): |
| 130 |
return cls.FLOAT |
| 131 |
elif val is None: |
| 132 |
return cls.FILE |
| 133 |
return cls.STR |
| 134 |
|
| 135 |
|
| 136 |
class SymbolTypes: |
| 137 |
""" |
| 138 |
*Symbols* that are understood during resolving, such as max number of |
| 139 |
processors, Max Chunks. Used when defining a Tool Contract |
| 140 |
""" |
| 141 |
MAX_NPROC = '$max_nproc' |
| 142 |
MAX_NCHUNKS = '$max_nchunks' |
| 143 |
TASK_TYPE = '$task_type' |
| 144 |
RESOLVED_OPTS = '$ropts' |
| 145 |
SCHEMA_OPTS = '$opts_schema' |
| 146 |
OPTS = '$opts' |
| 147 |
NCHUNKS = '$nchunks' |
| 148 |
NPROC = '$nproc' |
| 149 |
|
| 150 |
|
| 151 |
class ResourceTypes: |
| 152 |
""" |
| 153 |
Resources such as tmp dirs and files, log files. Used when defining |
| 154 |
a Tool Contract |
| 155 |
""" |
| 156 |
TMP_DIR = '$tmpdir' |
| 157 |
TMP_FILE = '$tmpfile' |
| 158 |
LOG_FILE = '$logfile' |
| 159 |
|
| 160 |
OUTPUT_DIR = '$outputdir' |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
@classmethod |
| 165 |
def ALL(cls): |
| 166 |
return cls.TMP_DIR, cls.TMP_FILE, cls.LOG_FILE, cls.OUTPUT_DIR |
| 167 |
|
| 168 |
@classmethod |
| 169 |
def is_tmp_resource(cls, name): |
| 170 |
return name in (cls.TMP_FILE, cls.TMP_DIR) |
| 171 |
|
| 172 |
@classmethod |
| 173 |
def is_valid(cls, attr_name): |
| 174 |
return attr_name in cls.ALL() |
| 175 |
|
| 176 |
|
| 177 |
class _RegisteredFileType(type): |
| 178 |
|
| 179 |
def __init__(cls, name, bases, dct): |
| 180 |
super().__init__(name, bases, dct) |
| 181 |
|
| 182 |
def __call__(cls, *args, **kwargs): |
| 183 |
if len(args) != 4: |
| 184 |
log.error(args) |
| 185 |
raise ValueError( |
| 186 |
"Incorrect initialization for {c}".format( |
| 187 |
c=cls.__name__)) |
| 188 |
|
| 189 |
file_type_id, base_name, file_ext, mime_type = args |
| 190 |
file_type = REGISTERED_FILE_TYPES.get(file_type_id, None) |
| 191 |
|
| 192 |
if file_type is None: |
| 193 |
file_type = super().__call__(*args) |
| 194 |
|
| 195 |
REGISTERED_FILE_TYPES[file_type_id] = file_type |
| 196 |
else: |
| 197 |
|
| 198 |
attrs_names = [('base_name', base_name), |
| 199 |
('ext', file_ext), |
| 200 |
('mime_type', mime_type)] |
| 201 |
|
| 202 |
for attrs_name, value in attrs_names: |
| 203 |
v = getattr(file_type, attrs_name) |
| 204 |
if v != value: |
| 205 |
_msg = "Attempting to register a file with a different '{x}' -> {v} (expected {y})".format( |
| 206 |
x=attrs_name, v=v, y=value) |
| 207 |
log.warn(_msg) |
| 208 |
warnings.warn(_msg) |
| 209 |
|
| 210 |
return file_type |
| 211 |
|
| 212 |
|
| 213 |
class FileType(metaclass=_RegisteredFileType): |
| 214 |
def __init__(self, file_type_id, base_name, ext, mime_type): |
| 215 |
""" |
| 216 |
Core File Type data model |
| 217 |
|
| 218 |
:param file_type_id: unique file string |
| 219 |
:param base_name: default base name of the file (without extension) |
| 220 |
:param ext: file extension |
| 221 |
:param mime_type: file mimetype |
| 222 |
:return: |
| 223 |
""" |
| 224 |
self.file_type_id = file_type_id |
| 225 |
self.base_name = base_name |
| 226 |
self.ext = ext |
| 227 |
self.mime_type = mime_type |
| 228 |
|
| 229 |
if file_type_id not in REGISTERED_FILE_TYPES: |
| 230 |
REGISTERED_FILE_TYPES[file_type_id] = self |
| 231 |
|
| 232 |
@property |
| 233 |
def default_name(self): |
| 234 |
""" Default name of file alias for base_name""" |
| 235 |
return self.base_name |
| 236 |
|
| 237 |
def __eq__(self, other): |
| 238 |
if isinstance(other, self.__class__): |
| 239 |
if self.file_type_id == other.file_type_id: |
| 240 |
if self.base_name == other.base_name: |
| 241 |
if self.ext == other.ext: |
| 242 |
return True |
| 243 |
return False |
| 244 |
|
| 245 |
def __repr__(self): |
| 246 |
_d = dict(k=self.__class__.__name__, |
| 247 |
i=self.file_type_id, |
| 248 |
n=self.default_name) |
| 249 |
return "<{k} id={i} name={n} >".format(**_d) |
| 250 |
|
| 251 |
|
| 252 |
class DataSetFileType(FileType): |
| 253 |
"""File types that are a DataSet Type""" |
| 254 |
pass |
| 255 |
|
| 256 |
|
| 257 |
class MimeTypes: |
| 258 |
"""Supported Mime types""" |
| 259 |
JSON = 'application/json' |
| 260 |
|
| 261 |
SVG = 'image/svg+xml' |
| 262 |
TXT = 'text/plain' |
| 263 |
CSV = 'text/csv' |
| 264 |
HTML = 'text/html' |
| 265 |
XML = 'application/xml' |
| 266 |
BINARY = 'application/octet-stream' |
| 267 |
PICKLE = 'application/python-pickle' |
| 268 |
GZIP = 'application/x-gzip' |
| 269 |
ZIP = 'application/zip' |
| 270 |
|
| 271 |
|
| 272 |
class FileTypes: |
| 273 |
|
| 274 |
"""Registry of all PacBio Files types |
| 275 |
|
| 276 |
This needs to be cleaned up and solidified. The old pre-SA3 file types need to be deleted. |
| 277 |
|
| 278 |
""" |
| 279 |
|
| 280 |
|
| 281 |
TXT = FileType(to_file_ns('txt'), 'file', 'txt', MimeTypes.TXT) |
| 282 |
|
| 283 |
LOG = FileType(to_file_ns('log'), 'file', 'log', MimeTypes.TXT) |
| 284 |
|
| 285 |
CFG = FileType(to_file_ns('cfg'), 'config', 'cfg', MimeTypes.TXT) |
| 286 |
|
| 287 |
SVG = FileType(to_file_ns('svg'), "file", 'svg', MimeTypes.SVG) |
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
REPORT = FileType( |
| 293 |
to_file_ns('JsonReport'), |
| 294 |
"report", |
| 295 |
"json", |
| 296 |
MimeTypes.JSON) |
| 297 |
DATASTORE = FileType( |
| 298 |
to_file_ns("Datastore"), |
| 299 |
"file", |
| 300 |
"datastore.json", |
| 301 |
MimeTypes.JSON) |
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
CHUNK = FileType(to_file_ns("CHUNK"), "chunk", "json", MimeTypes.JSON) |
| 306 |
GCHUNK = FileType( |
| 307 |
to_file_ns("GCHUNK"), |
| 308 |
'gather_chunk', |
| 309 |
"json", |
| 310 |
MimeTypes.JSON) |
| 311 |
SCHUNK = FileType( |
| 312 |
to_file_ns("SCHUNK"), |
| 313 |
"scatter_chunk", |
| 314 |
"json", |
| 315 |
MimeTypes.JSON) |
| 316 |
|
| 317 |
FASTA = FileType(to_file_ns('Fasta'), "file", "fasta", MimeTypes.TXT) |
| 318 |
FASTQ = FileType(to_file_ns('Fastq'), "file", "fastq", MimeTypes.TXT) |
| 319 |
|
| 320 |
|
| 321 |
INPUT_XML = FileType( |
| 322 |
to_file_ns('input_xml'), |
| 323 |
"input", |
| 324 |
"xml", |
| 325 |
MimeTypes.XML) |
| 326 |
FOFN = FileType( |
| 327 |
to_file_ns("generic_fofn"), |
| 328 |
"generic", |
| 329 |
"fofn", |
| 330 |
MimeTypes.TXT) |
| 331 |
MOVIE_FOFN = FileType( |
| 332 |
to_file_ns('movie_fofn'), |
| 333 |
"movie", |
| 334 |
"fofn", |
| 335 |
MimeTypes.TXT) |
| 336 |
RGN_FOFN = FileType( |
| 337 |
to_file_ns('rgn_fofn'), |
| 338 |
"region", |
| 339 |
"fofn", |
| 340 |
MimeTypes.TXT) |
| 341 |
|
| 342 |
RS_MOVIE_XML = FileType( |
| 343 |
to_file_ns("rs_movie_metadata"), |
| 344 |
"file", |
| 345 |
"rs_movie.metadata.xml", |
| 346 |
MimeTypes.XML) |
| 347 |
REF_ENTRY_XML = FileType( |
| 348 |
to_file_ns('reference_info_xml'), |
| 349 |
"reference.info.xml", |
| 350 |
"xml", |
| 351 |
MimeTypes.XML) |
| 352 |
|
| 353 |
ALIGNMENT_CMP_H5 = FileType( |
| 354 |
to_file_ns('alignment_cmp_h5'), |
| 355 |
"alignments", |
| 356 |
"cmp.h5", |
| 357 |
MimeTypes.BINARY) |
| 358 |
|
| 359 |
BLASR_M4 = FileType(to_file_ns('blasr_file'), 'blasr', 'm4', MimeTypes.TXT) |
| 360 |
BAM = FileType(to_file_ns('bam'), "alignments", "bam", MimeTypes.BINARY) |
| 361 |
BAMBAI = FileType( |
| 362 |
to_file_ns('bam_bai'), |
| 363 |
"alignments", |
| 364 |
"bam.bai", |
| 365 |
MimeTypes.BINARY) |
| 366 |
|
| 367 |
BED = FileType(to_file_ns('bed'), "file", "bed", MimeTypes.TXT) |
| 368 |
SAM = FileType(to_file_ns('sam'), "alignments", "sam", MimeTypes.BINARY) |
| 369 |
VCF = FileType(to_file_ns('vcf'), "file", "vcf", MimeTypes.TXT) |
| 370 |
GFF = FileType(to_file_ns('gff'), "file", "gff", MimeTypes.TXT) |
| 371 |
GTF = FileType(to_file_ns('gtf'), "file", "gtf", MimeTypes.TXT) |
| 372 |
BIGWIG = FileType( |
| 373 |
to_file_ns('bigwig'), |
| 374 |
"annotations", |
| 375 |
"bw", |
| 376 |
MimeTypes.BINARY) |
| 377 |
CSV = FileType(to_file_ns('csv'), "file", "csv", MimeTypes.CSV) |
| 378 |
TSV = FileType(to_file_ns('tsv'), "file", "tsv", MimeTypes.TXT) |
| 379 |
XML = FileType(to_file_ns('xml'), "file", "xml", MimeTypes.XML) |
| 380 |
HTML = FileType(to_file_ns('html'), "file", "html", MimeTypes.HTML) |
| 381 |
|
| 382 |
JSON = FileType(to_file_ns("json"), "file", "json", MimeTypes.JSON) |
| 383 |
|
| 384 |
H5 = FileType(to_file_ns("h5"), "file", "h5", MimeTypes.BINARY) |
| 385 |
|
| 386 |
PICKLE = FileType(to_file_ns("pickle"), "file", "pickle", MimeTypes.PICKLE) |
| 387 |
|
| 388 |
GZIP = FileType(to_file_ns("gzip"), "file", "gz", MimeTypes.GZIP) |
| 389 |
TGZ = FileType(to_file_ns("tgz"), "file", "tar.gz", MimeTypes.GZIP) |
| 390 |
ZIP = FileType(to_file_ns("zip"), "file", "zip", MimeTypes.ZIP) |
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
DS_SUBREADS_H5 = DataSetFileType( |
| 397 |
to_ds_ns("HdfSubreadSet"), |
| 398 |
"file", |
| 399 |
"hdfsubreadset.xml", |
| 400 |
MimeTypes.XML) |
| 401 |
DS_SUBREADS = DataSetFileType( |
| 402 |
to_ds_ns("SubreadSet"), |
| 403 |
"file", |
| 404 |
"subreadset.xml", |
| 405 |
MimeTypes.XML) |
| 406 |
DS_CCS = DataSetFileType( |
| 407 |
to_ds_ns("ConsensusReadSet"), |
| 408 |
"file", |
| 409 |
"consensusreadset.xml", |
| 410 |
MimeTypes.XML) |
| 411 |
DS_REF = DataSetFileType( |
| 412 |
to_ds_ns("ReferenceSet"), |
| 413 |
"file", |
| 414 |
"referenceset.xml", |
| 415 |
MimeTypes.XML) |
| 416 |
DS_ALIGN = DataSetFileType( |
| 417 |
to_ds_ns("AlignmentSet"), |
| 418 |
"file", |
| 419 |
"alignmentset.xml", |
| 420 |
MimeTypes.XML) |
| 421 |
DS_CONTIG = DataSetFileType( |
| 422 |
to_ds_ns("ContigSet"), |
| 423 |
"file", |
| 424 |
"contigset.xml", |
| 425 |
MimeTypes.XML) |
| 426 |
DS_BARCODE = DataSetFileType( |
| 427 |
to_ds_ns("BarcodeSet"), |
| 428 |
"file", |
| 429 |
"barcodeset.xml", |
| 430 |
MimeTypes.XML) |
| 431 |
DS_ALIGN_CCS = DataSetFileType(to_ds_ns("ConsensusAlignmentSet"), "file", |
| 432 |
"consensusalignmentset.xml", MimeTypes.XML) |
| 433 |
DS_GMAP_REF = DataSetFileType(to_ds_ns("GmapReferenceSet"), "file", |
| 434 |
"gmapreferenceset.xml", MimeTypes.XML) |
| 435 |
DS_TRANSCRIPT = DataSetFileType(to_ds_ns("TranscriptSet"), "file", |
| 436 |
"transcriptset.xml", MimeTypes.XML) |
| 437 |
DS_ALIGN_TRANSCRIPT = DataSetFileType( |
| 438 |
to_ds_ns("TranscriptAlignmentSet"), |
| 439 |
"file", |
| 440 |
"transcriptalignmentset.xml", |
| 441 |
MimeTypes.XML) |
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
I_SAM = FileType( |
| 448 |
to_index_ns("SamIndex"), |
| 449 |
"file", |
| 450 |
"sam.index", |
| 451 |
MimeTypes.BINARY) |
| 452 |
I_SAW = FileType( |
| 453 |
to_index_ns("SaWriterIndex"), |
| 454 |
"file", |
| 455 |
"sa", |
| 456 |
MimeTypes.BINARY) |
| 457 |
|
| 458 |
|
| 459 |
I_INDEXER = FileType( |
| 460 |
to_index_ns("Indexer"), |
| 461 |
"file", |
| 462 |
"fasta.index", |
| 463 |
MimeTypes.TXT) |
| 464 |
I_FCI = FileType( |
| 465 |
to_index_ns("FastaContigIndex"), |
| 466 |
"file", |
| 467 |
"fasta.contig.index", |
| 468 |
MimeTypes.TXT) |
| 469 |
|
| 470 |
|
| 471 |
I_PBI = FileType( |
| 472 |
to_index_ns("PacBioIndex"), |
| 473 |
"file", |
| 474 |
"pbi", |
| 475 |
MimeTypes.BINARY) |
| 476 |
|
| 477 |
I_BAI = FileType( |
| 478 |
to_index_ns("BamIndex"), |
| 479 |
"file", |
| 480 |
"bam.bai", |
| 481 |
MimeTypes.BINARY) |
| 482 |
|
| 483 |
|
| 484 |
I_NGMLR_ENC = FileType( |
| 485 |
to_index_ns("NgmlrRefEncoded"), |
| 486 |
"file", |
| 487 |
".ngm", |
| 488 |
MimeTypes.BINARY) |
| 489 |
I_NGMLR_TAB = FileType( |
| 490 |
to_index_ns("NgmlrRefTable"), |
| 491 |
"file", |
| 492 |
".ngm", |
| 493 |
MimeTypes.BINARY) |
| 494 |
|
| 495 |
I_TABIX = FileType(to_index_ns("Tabix"), "file", "tbi", MimeTypes.BINARY) |
| 496 |
|
| 497 |
|
| 498 |
I_PGI = FileType(to_index_ns("PigeonIndex"), "file", "pgi", MimeTypes.TXT) |
| 499 |
|
| 500 |
|
| 501 |
GTF_ANNOTATION = FileType( |
| 502 |
"PacBio.ReferenceFile.ReferenceAnnotationFile", |
| 503 |
"file", |
| 504 |
"gtf", |
| 505 |
MimeTypes.TXT) |
| 506 |
POLYA_MOTIF = FileType( |
| 507 |
"PacBio.ReferenceFile.PolyAMotifFile", |
| 508 |
"file", |
| 509 |
"txt", |
| 510 |
MimeTypes.TXT) |
| 511 |
BED_POLYA_PEAK = FileType( |
| 512 |
"PacBio.ReferenceFile.PolyAPeakFile", |
| 513 |
"file", |
| 514 |
"bed", |
| 515 |
MimeTypes.TXT) |
| 516 |
BED_CAGE_PEAK = FileType( |
| 517 |
"PacBio.ReferenceFile.CagePeakFile", |
| 518 |
"file", |
| 519 |
"bed", |
| 520 |
MimeTypes.TXT) |
| 521 |
INTROPOLIS = FileType( |
| 522 |
"PacBio.ReferenceFile.IntropolisFile", |
| 523 |
"file", |
| 524 |
"tsv", |
| 525 |
MimeTypes.TXT) |
| 526 |
|
| 527 |
|
| 528 |
FASTA_BC = FileType( |
| 529 |
"PacBio.BarcodeFile.BarcodeFastaFile", |
| 530 |
"file", |
| 531 |
"barcode.fasta", |
| 532 |
MimeTypes.TXT) |
| 533 |
|
| 534 |
FASTA_REF = FileType( |
| 535 |
"PacBio.ReferenceFile.ReferenceFastaFile", |
| 536 |
"file", |
| 537 |
"pbreference.fasta", |
| 538 |
MimeTypes.TXT) |
| 539 |
CONTIG_FA = FileType( |
| 540 |
"PacBio.ContigFile.ContigFastaFile", |
| 541 |
"file", |
| 542 |
"contig.fasta", |
| 543 |
MimeTypes.TXT) |
| 544 |
|
| 545 |
|
| 546 |
FASTA_ADAPTER = FileType( |
| 547 |
"PacBio.SubreadFile.AdapterFastaFile", |
| 548 |
"file", |
| 549 |
"adapters.fasta", |
| 550 |
MimeTypes.TXT) |
| 551 |
FASTA_CONTROL = FileType( |
| 552 |
"PacBio.SubreadFile.ControlFastaFile", |
| 553 |
"file", |
| 554 |
"control.fasta", |
| 555 |
MimeTypes.TXT) |
| 556 |
|
| 557 |
|
| 558 |
BAM_ALN = FileType( |
| 559 |
"PacBio.AlignmentFile.AlignmentBamFile", |
| 560 |
"file", |
| 561 |
"alignment.bam", |
| 562 |
MimeTypes.BINARY) |
| 563 |
BAM_SUB = FileType( |
| 564 |
"PacBio.SubreadFile.SubreadBamFile", |
| 565 |
"file", |
| 566 |
"subread.bam", |
| 567 |
MimeTypes.BINARY) |
| 568 |
BAM_CCS = FileType( |
| 569 |
"PacBio.ConsensusReadFile.ConsensusReadBamFile", |
| 570 |
"file", |
| 571 |
"ccs.bam", |
| 572 |
MimeTypes.BINARY) |
| 573 |
BAM_CCS_ALN = FileType( |
| 574 |
"PacBio.AlignmentFile.ConsensusAlignmentBamFile", |
| 575 |
"file", |
| 576 |
"ccs_align.bam", |
| 577 |
MimeTypes.BINARY) |
| 578 |
BAM_TRANSCRIPT = FileType( |
| 579 |
"PacBio.TranscriptFile.TranscriptBamFile", |
| 580 |
"file", |
| 581 |
"transcripts.bam", |
| 582 |
MimeTypes.BINARY) |
| 583 |
BAM_TRANSCRIPT_ALN = FileType( |
| 584 |
"PacBio.AlignmentFile.TranscriptAlignmentBamFile", |
| 585 |
"file", |
| 586 |
"transcripts_align.bam", |
| 587 |
MimeTypes.BINARY) |
| 588 |
|
| 589 |
|
| 590 |
BAZ = FileType("PacBio.ReadFile.BazFile", "file", "baz", MimeTypes.BINARY) |
| 591 |
TRC = FileType( |
| 592 |
"PacBio.ReadFile.TraceFile", |
| 593 |
"file", |
| 594 |
"trc", |
| 595 |
MimeTypes.BINARY) |
| 596 |
PLS = FileType( |
| 597 |
"PacBio.ReadFile.PulseFile", |
| 598 |
"file", |
| 599 |
"pls", |
| 600 |
MimeTypes.BINARY) |
| 601 |
|
| 602 |
BAX = FileType( |
| 603 |
"PacBio.SubreadFile.BaxFile", |
| 604 |
"file", |
| 605 |
"bax.h5", |
| 606 |
MimeTypes.BINARY) |
| 607 |
|
| 608 |
|
| 609 |
STS_XML = FileType("PacBio.SubreadFile.ChipStatsFile", |
| 610 |
"file", "sts.xml", MimeTypes.XML) |
| 611 |
STS_H5 = FileType("PacBio.SubreadFile.ChipStatsH5File", |
| 612 |
"file", "sts.h5", MimeTypes.BINARY) |
| 613 |
|
| 614 |
|
| 615 |
COND_RESEQ = FileType( |
| 616 |
to_file_ns("COND_RESEQ"), |
| 617 |
"file", |
| 618 |
"conditions-reseq.json", |
| 619 |
MimeTypes.JSON) |
| 620 |
|
| 621 |
@staticmethod |
| 622 |
def is_valid_id(file_type_id): |
| 623 |
return file_type_id in REGISTERED_FILE_TYPES |
| 624 |
|
| 625 |
@staticmethod |
| 626 |
def ALL_DATASET_TYPES(): |
| 627 |
return {i: f for i, f in REGISTERED_FILE_TYPES.items() |
| 628 |
if isinstance(f, DataSetFileType)} |
| 629 |
|
| 630 |
@staticmethod |
| 631 |
def ALL(): |
| 632 |
"""Returns a Dict of id->FileType |
| 633 |
|
| 634 |
:rtype dict[str, FileType] |
| 635 |
""" |
| 636 |
return REGISTERED_FILE_TYPES |
| 637 |
|
| 638 |
|
| 639 |
def _get_timestamp_or_now(path, func): |
| 640 |
if os.path.exists(path): |
| 641 |
return func(path) |
| 642 |
else: |
| 643 |
return datetime.datetime.now() |
| 644 |
|
| 645 |
|
| 646 |
def _get_file_path(path, base_path=None): |
| 647 |
if base_path is None or os.path.isabs(path): |
| 648 |
return path |
| 649 |
else: |
| 650 |
return os.path.join(base_path, path) |
| 651 |
|
| 652 |
|
| 653 |
class DataStoreFile: |
| 654 |
|
| 655 |
def __init__(self, uuid, source_id, type_id, path, is_chunked=False, |
| 656 |
name="", description=""): |
| 657 |
""" |
| 658 |
|
| 659 |
:param uuid: UUID of the datstore file |
| 660 |
:param source_id: source id of the DataStore file |
| 661 |
:param type_id: File Type id of |
| 662 |
:param path: Absolute path to the datastore file |
| 663 |
:param is_chunked: is the datastore file a "chunked" file from a scatter/chunking task |
| 664 |
:param name: Display name of datastore file |
| 665 |
:param description: Description of the datastore file |
| 666 |
|
| 667 |
""" |
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
self.uuid = uuid |
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
self.file_id = source_id |
| 677 |
|
| 678 |
self.file_type_id = type_id |
| 679 |
self.path = path |
| 680 |
|
| 681 |
self.file_size = os.path.getsize(path) if os.path.exists(path) else 0 |
| 682 |
self.created_at = _get_timestamp_or_now( |
| 683 |
path, lambda px: datetime.datetime.fromtimestamp( |
| 684 |
os.path.getctime(px))) |
| 685 |
self.modified_at = _get_timestamp_or_now( |
| 686 |
path, lambda px: datetime.datetime.fromtimestamp( |
| 687 |
os.path.getmtime(px))) |
| 688 |
|
| 689 |
self.is_chunked = is_chunked |
| 690 |
self.name = name |
| 691 |
self.description = description |
| 692 |
|
| 693 |
@property |
| 694 |
def source_id(self): |
| 695 |
"""This is the consistent form that is used in the code base""" |
| 696 |
return self.file_id |
| 697 |
|
| 698 |
@property |
| 699 |
def file_type(self): |
| 700 |
return REGISTERED_FILE_TYPES[self.file_type_id] |
| 701 |
|
| 702 |
def __repr__(self): |
| 703 |
u = str(self.uuid)[:6] |
| 704 |
_d = dict(k=self.__class__.__name__, |
| 705 |
i=self.file_id, |
| 706 |
t=self.file_type_id, |
| 707 |
p=os.path.basename(self.path), u=u) |
| 708 |
return "<{k} {i} type:{t} filename:{p} uuid:{u} ... >".format(**_d) |
| 709 |
|
| 710 |
def to_dict(self): |
| 711 |
return dict(sourceId=self.file_id, |
| 712 |
uniqueId=str(self.uuid), |
| 713 |
fileTypeId=self.file_type_id, |
| 714 |
path=self.path, |
| 715 |
fileSize=self.file_size, |
| 716 |
createdAt=_datetime_to_string(self.created_at), |
| 717 |
modifiedAt=_datetime_to_string(self.modified_at), |
| 718 |
isChunked=self.is_chunked, |
| 719 |
name=self.name, |
| 720 |
description=self.description) |
| 721 |
|
| 722 |
@staticmethod |
| 723 |
def from_dict(d, base_path=None): |
| 724 |
|
| 725 |
to_a = to_ascii |
| 726 |
|
| 727 |
def to_k(x): |
| 728 |
return to_a(d[x]) |
| 729 |
|
| 730 |
is_chunked = d.get('isChunked', False) |
| 731 |
return DataStoreFile(to_k('uniqueId'), |
| 732 |
to_k('sourceId'), |
| 733 |
to_k('fileTypeId'), |
| 734 |
_get_file_path(to_k('path'), base_path), |
| 735 |
is_chunked=is_chunked, |
| 736 |
name=to_a(d.get("name", "")), |
| 737 |
description=to_a(d.get("description", ""))) |
| 738 |
|
| 739 |
|
| 740 |
def _datetime_to_string(dt): |
| 741 |
return dt.strftime('%Y-%m-%dT%H:%M:%S') |
| 742 |
|
| 743 |
|
| 744 |
class DataStore: |
| 745 |
version = "0.2.2" |
| 746 |
|
| 747 |
def __init__(self, ds_files, created_at=None): |
| 748 |
""" |
| 749 |
:param ds_files: list of datastore file instances |
| 750 |
:param created_at: Date the datastore was created. if None, will use the current datetime |
| 751 |
|
| 752 |
:type ds_files: list[DataStoreFile] |
| 753 |
""" |
| 754 |
self.files = OrderedDict([(f.uuid, f) for f in ds_files]) |
| 755 |
self.created_at = datetime.datetime.now() if created_at is None else created_at |
| 756 |
self.updated_at = datetime.datetime.now() |
| 757 |
|
| 758 |
def __repr__(self): |
| 759 |
_d = dict(n=len(self.files), k=self.__class__.__name__) |
| 760 |
return "<{k} nfiles={n} >".format(**_d) |
| 761 |
|
| 762 |
def add(self, ds_file): |
| 763 |
if isinstance(ds_file, DataStoreFile): |
| 764 |
if ds_file.uuid in self.files: |
| 765 |
log.warn("UUID {u} in file {s} already present in datastore (source: {f})".format( |
| 766 |
u=ds_file.uuid, s=ds_file.file_id, f=self.files[ds_file.uuid].file_id)) |
| 767 |
self.files[ds_file.uuid] = ds_file |
| 768 |
self.updated_at = datetime.datetime.now() |
| 769 |
else: |
| 770 |
raise TypeError( |
| 771 |
"DataStoreFile expected. Got type {t} for {d}".format( |
| 772 |
t=type(ds_file), d=ds_file)) |
| 773 |
|
| 774 |
def to_dict(self): |
| 775 |
fs = [f.to_dict() for i, f in self.files.items()] |
| 776 |
_d = dict(version=self.version, |
| 777 |
createdAt=_datetime_to_string(self.created_at), |
| 778 |
updatedAt=_datetime_to_string(self.updated_at), files=fs) |
| 779 |
return _d |
| 780 |
|
| 781 |
def write_json(self, file_name): |
| 782 |
write_dict_to_json(self.to_dict(), file_name, "w") |
| 783 |
|
| 784 |
def write_update_json(self, file_name): |
| 785 |
"""Overwrite Datastore with current state""" |
| 786 |
write_dict_to_json(self.to_dict(), file_name, "w+") |
| 787 |
|
| 788 |
@staticmethod |
| 789 |
def load_from_d(d, base_path=None): |
| 790 |
"""Load DataStore from a dict""" |
| 791 |
ds_files = [DataStoreFile.from_dict(x, base_path) for x in d['files']] |
| 792 |
return DataStore(ds_files) |
| 793 |
|
| 794 |
@staticmethod |
| 795 |
def load_from_json(path): |
| 796 |
"""Load DataStore from a JSON file""" |
| 797 |
base_path = os.path.dirname(os.path.abspath(path)) |
| 798 |
with open(path, 'r') as reader: |
| 799 |
d = json.loads(reader.read()) |
| 800 |
return DataStore.load_from_d(d, base_path) |
| 801 |
|
| 802 |
|
| 803 |
def _is_chunk_key(k): |
| 804 |
return k.startswith(PipelineChunk.CHUNK_KEY_PREFIX) |
| 805 |
|
| 806 |
|
| 807 |
class MalformedChunkKeyError(ValueError): |
| 808 |
|
| 809 |
"""Chunk Key does NOT adhere to the spec""" |
| 810 |
pass |
| 811 |
|
| 812 |
|
| 813 |
class PipelineChunk: |
| 814 |
|
| 815 |
CHUNK_KEY_PREFIX = "$chunk." |
| 816 |
RX_CHUNK_KEY = re.compile(r'^\$chunk\.([A-z0-9_]*)') |
| 817 |
|
| 818 |
def __init__(self, chunk_id, **kwargs): |
| 819 |
""" |
| 820 |
|
| 821 |
kwargs is a key-value store. keys that begin "$chunk." are considered |
| 822 |
to be semantically understood by workflow and can be "routed" to |
| 823 |
chunked task inputs. |
| 824 |
|
| 825 |
Values that don't begin with "$chunk." are considered metadata. |
| 826 |
|
| 827 |
|
| 828 |
:param chunk_id: Chunk id |
| 829 |
:type chunk_id: str |
| 830 |
|
| 831 |
""" |
| 832 |
if self.RX_CHUNK_KEY.match(chunk_id) is not None: |
| 833 |
raise MalformedChunkKeyError( |
| 834 |
"'{c}' expected {p}".format( |
| 835 |
c=chunk_id, p=self.RX_CHUNK_KEY.pattern)) |
| 836 |
|
| 837 |
self.chunk_id = chunk_id |
| 838 |
|
| 839 |
self._datum = kwargs |
| 840 |
|
| 841 |
def __repr__(self): |
| 842 |
_d = dict( |
| 843 |
k=self.__class__.__name__, |
| 844 |
i=self.chunk_id, |
| 845 |
c=",".join( |
| 846 |
self.chunk_keys)) |
| 847 |
return "<{k} id='{i}' chunk keys={c} >".format(**_d) |
| 848 |
|
| 849 |
def set_chunk_key(self, chunk_key, value): |
| 850 |
"""Overwrite or add a chunk_key => value to the Chunk datum |
| 851 |
|
| 852 |
the chunk-key can be provided with or without the '$chunk:' prefix |
| 853 |
""" |
| 854 |
if not chunk_key.startswith(PipelineChunk.CHUNK_KEY_PREFIX): |
| 855 |
chunk_key = PipelineChunk.CHUNK_KEY_PREFIX + chunk_key |
| 856 |
self._datum[chunk_key] = value |
| 857 |
|
| 858 |
def set_metadata_key(self, metadata_key, value): |
| 859 |
"""Set chunk metadata key => value |
| 860 |
|
| 861 |
metadata key must NOT begin with $chunk. format |
| 862 |
""" |
| 863 |
if metadata_key.startswith(PipelineChunk.CHUNK_KEY_PREFIX): |
| 864 |
raise ValueError( |
| 865 |
"Cannot set chunk-key values. {i}".format(i=metadata_key)) |
| 866 |
self._datum[metadata_key] = value |
| 867 |
|
| 868 |
@property |
| 869 |
def chunk_d(self): |
| 870 |
return {k: v for k, v in self._datum.items() if _is_chunk_key(k)} |
| 871 |
|
| 872 |
@property |
| 873 |
def chunk_keys(self): |
| 874 |
return list(self.chunk_d.keys()) |
| 875 |
|
| 876 |
@property |
| 877 |
def chunk_metadata(self): |
| 878 |
return {k: v for k, v in self._datum.items() if not _is_chunk_key(k)} |
| 879 |
|
| 880 |
def to_dict(self): |
| 881 |
return {'chunk_id': self.chunk_id, 'chunk': self._datum} |
| 882 |
|
| 883 |
|
| 884 |
class DataStoreViewRule: |
| 885 |
""" |
| 886 |
Rule specifying if and how the UI should display a datastore file. |
| 887 |
""" |
| 888 |
|
| 889 |
def __init__(self, source_id, file_type_id, is_hidden, name="", |
| 890 |
description="", type_name=None): |
| 891 |
""" |
| 892 |
:param source_id: Unique source id of the datastore file |
| 893 |
:param file_type_id: File Type id of the datastore file |
| 894 |
:param is_hidden: Mark the file has hidden |
| 895 |
:param name: Display name of the file |
| 896 |
:param description: Description of the file |
| 897 |
:param type_name: Name of file type to display |
| 898 |
""" |
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
if isinstance(file_type_id, FileType): |
| 903 |
file_type_id = file_type_id.file_type_id |
| 904 |
assert FileTypes.is_valid_id(file_type_id), file_type_id |
| 905 |
self.source_id = source_id |
| 906 |
self.file_type_id = file_type_id |
| 907 |
self.is_hidden = is_hidden |
| 908 |
self.name = name |
| 909 |
self.description = description |
| 910 |
self.type_name = type_name |
| 911 |
|
| 912 |
def to_dict(self): |
| 913 |
d = {"sourceId": self.source_id, "fileTypeId": self.file_type_id, |
| 914 |
"isHidden": self.is_hidden, "name": self.name, |
| 915 |
"description": self.description} |
| 916 |
if self.type_name is not None: |
| 917 |
d["typeName"] = self.type_name |
| 918 |
return d |
| 919 |
|
| 920 |
@staticmethod |
| 921 |
def from_dict(d): |
| 922 |
return DataStoreViewRule(d['sourceId'], d['fileTypeId'], d['isHidden'], |
| 923 |
d.get('name', ''), d.get('description', ''), |
| 924 |
d.get('typeName', None)) |
| 925 |
|
| 926 |
|
| 927 |
class PipelineDataStoreViewRules: |
| 928 |
""" |
| 929 |
A collection of DataStoreViewRule objects associated with a pipeline. |
| 930 |
""" |
| 931 |
|
| 932 |
def __init__(self, pipeline_id, smrtlink_version, rules=()): |
| 933 |
self.pipeline_id = pipeline_id |
| 934 |
self.smrtlink_version = smrtlink_version |
| 935 |
self.rules = list(rules) |
| 936 |
|
| 937 |
def to_dict(self): |
| 938 |
return {"pipelineId": self.pipeline_id, |
| 939 |
"smrtlinkVersion": self.smrtlink_version, |
| 940 |
"rules": [r.to_dict() for r in self.rules]} |
| 941 |
|
| 942 |
@staticmethod |
| 943 |
def from_dict(d): |
| 944 |
return PipelineDataStoreViewRules( |
| 945 |
pipeline_id=d['pipelineId'], |
| 946 |
smrtlink_version=d['smrtlinkVersion'], |
| 947 |
rules=[DataStoreViewRule.from_dict(r) for r in d['rules']]) |
| 948 |
|
| 949 |
@staticmethod |
| 950 |
def load_from_json(path): |
| 951 |
with open(path, 'r') as reader: |
| 952 |
d = json.loads(reader.read()) |
| 953 |
return PipelineDataStoreViewRules.from_dict(d) |
| 954 |
|
| 955 |
def write_json(self, file_name): |
| 956 |
write_dict_to_json(self.to_dict(), file_name) |
| 957 |
|
| 958 |
|
| 959 |
def write_dict_to_json(d, file_name, permission="w"): |
| 960 |
with open(file_name, permission) as f: |
| 961 |
s = json.dumps(d, indent=4, sort_keys=True, |
| 962 |
separators=(',', ': ')) |
| 963 |
f.write(s) |
| 964 |
|
| 965 |
|
| 966 |
RX_TASK_ID = re.compile(r'^([A-z0-9_]*)\.tasks\.([A-z0-9_]*)$') |
| 967 |
RX_TASK_OPTION_ID = re.compile(r'^([A-z0-9_\.]*)') |
| 968 |
|
| 969 |
|
| 970 |
def _validate_id(prog, idtype, tid): |
| 971 |
if prog.match(tid): |
| 972 |
return tid |
| 973 |
else: |
| 974 |
raise ValueError( |
| 975 |
"Invalid format {t}: '{i}' {p}".format( |
| 976 |
t=idtype, i=tid, p=repr( |
| 977 |
prog.pattern))) |
| 978 |
|
| 979 |
|
| 980 |
validate_task_id = functools.partial(_validate_id, RX_TASK_ID, 'task id') |
| 981 |
validate_task_option_id = functools.partial(_validate_id, RX_TASK_OPTION_ID, |
| 982 |
'task option id') |
| 983 |
|
| 984 |
|
| 985 |
class BasePacBioOption: |
| 986 |
|
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
OPTION_TYPE_ID = "UNKNOWN" |
| 991 |
|
| 992 |
@classmethod |
| 993 |
def validate_core_type(cls, value): |
| 994 |
""" |
| 995 |
Every Option has a "core" type that needs to validated in the |
| 996 |
constructor. The function should return the value |
| 997 |
|
| 998 |
Subclasses should implement |
| 999 |
|
| 1000 |
:param value: Option value |
| 1001 |
:return: validated value |
| 1002 |
""" |
| 1003 |
|
| 1004 |
raise NotImplementedError |
| 1005 |
|
| 1006 |
def validate_option(self, value): |
| 1007 |
"""Core method used externally (e.g., resolvers) to validate option |
| 1008 |
|
| 1009 |
The default implementation will only validate that the "core" type |
| 1010 |
is consistent with definition. |
| 1011 |
|
| 1012 |
Subclasses should override this to leverage internal state (e.g, self.choices) |
| 1013 |
""" |
| 1014 |
return self.validate_core_type(value) |
| 1015 |
|
| 1016 |
def __init__(self, option_id, name, default, description): |
| 1017 |
""" |
| 1018 |
Core constructor for the PacBio Task Option. |
| 1019 |
|
| 1020 |
:param option_id: PacBio Task Option type id. Must adhere to the A-z0-9_ |
| 1021 |
:param name: Display name of the Task Option |
| 1022 |
:param default: Default value |
| 1023 |
:param description: Description of the Task Option |
| 1024 |
|
| 1025 |
:type option_id: str |
| 1026 |
:type name: str |
| 1027 |
:type description: str |
| 1028 |
""" |
| 1029 |
self.option_id = validate_task_option_id(option_id) |
| 1030 |
self.name = name |
| 1031 |
self._default = self.validate_core_type(default) |
| 1032 |
self.description = description |
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
if self.OPTION_TYPE_ID not in TaskOptionTypes.ALL(): |
| 1037 |
msg = "InValid Task Option type id {t} Subclasses of {c} must " \ |
| 1038 |
"override OPTION_TYPE_ID to have a consistent value with " \ |
| 1039 |
"TaskOptionTypes.*".format(t=self.OPTION_TYPE_ID, |
| 1040 |
c=self.__class__.__name__) |
| 1041 |
raise ValueError(msg) |
| 1042 |
|
| 1043 |
@property |
| 1044 |
def default(self): |
| 1045 |
"""Returns the default value for the option""" |
| 1046 |
return self._default |
| 1047 |
|
| 1048 |
def __repr__(self): |
| 1049 |
_d = dict(i=self.option_id, |
| 1050 |
n=self.name, |
| 1051 |
v=self.default, |
| 1052 |
k=self.__class__.__name__, |
| 1053 |
t=self.OPTION_TYPE_ID) |
| 1054 |
return "<{k} {i} name: {n} default: {v} type:{t} >".format(**_d) |
| 1055 |
|
| 1056 |
def to_dict(self): |
| 1057 |
option_type = TaskOptionTypes.from_str(self.OPTION_TYPE_ID) |
| 1058 |
|
| 1059 |
|
| 1060 |
return dict(id=self.option_id, |
| 1061 |
name=self.name, |
| 1062 |
default=self.default, |
| 1063 |
description=self.description, |
| 1064 |
optionTypeId=option_type) |
| 1065 |
|
| 1066 |
|
| 1067 |
def _type_error_msg(value, expected_type): |
| 1068 |
return "{v} Expected {t}, got {x}".format( |
| 1069 |
v=value, t=expected_type, x=type(value)) |
| 1070 |
|
| 1071 |
|
| 1072 |
def _strict_validate_int_or_raise(value): |
| 1073 |
|
| 1074 |
def _to_msg(type_): |
| 1075 |
return _type_error_msg(value, type_) |
| 1076 |
|
| 1077 |
if isinstance(value, bool): |
| 1078 |
raise TypeError(_to_msg(bool)) |
| 1079 |
elif isinstance(value, float): |
| 1080 |
raise TypeError(_to_msg(float)) |
| 1081 |
elif isinstance(value, str): |
| 1082 |
raise TypeError(_to_msg(str)) |
| 1083 |
else: |
| 1084 |
return int(value) |
| 1085 |
|
| 1086 |
|
| 1087 |
def _strict_validate_bool_or_raise(value): |
| 1088 |
if isinstance(value, bool): |
| 1089 |
return value |
| 1090 |
raise TypeError(_type_error_msg(value, bool)) |
| 1091 |
|
| 1092 |
|
| 1093 |
def _strict_validate_float_or_raise(value): |
| 1094 |
|
| 1095 |
def _to_msg(type_): |
| 1096 |
return _type_error_msg(value, type_) |
| 1097 |
|
| 1098 |
if isinstance(value, bool): |
| 1099 |
raise TypeError(_to_msg(bool)) |
| 1100 |
elif isinstance(value, str): |
| 1101 |
raise TypeError(_to_msg(str)) |
| 1102 |
else: |
| 1103 |
return float(value) |
| 1104 |
|
| 1105 |
|
| 1106 |
def _strict_validate_string_or_raise(value): |
| 1107 |
|
| 1108 |
if isinstance(value, str): |
| 1109 |
return value |
| 1110 |
raise TypeError(_type_error_msg(value, str)) |
| 1111 |
|
| 1112 |
|
| 1113 |
def _strict_validate_file_or_raise(value): |
| 1114 |
|
| 1115 |
if isinstance(value, str) or value is None: |
| 1116 |
return value |
| 1117 |
raise TypeError(_type_error_msg(value, str)) |
| 1118 |
|
| 1119 |
|
| 1120 |
class PacBioIntOption(BasePacBioOption): |
| 1121 |
OPTION_TYPE_ID = TaskOptionTypes.INT |
| 1122 |
|
| 1123 |
@classmethod |
| 1124 |
def validate_core_type(cls, value): |
| 1125 |
return _strict_validate_int_or_raise(value) |
| 1126 |
|
| 1127 |
|
| 1128 |
class PacBioFloatOption(BasePacBioOption): |
| 1129 |
OPTION_TYPE_ID = TaskOptionTypes.FLOAT |
| 1130 |
|
| 1131 |
@classmethod |
| 1132 |
def validate_core_type(cls, value): |
| 1133 |
return _strict_validate_float_or_raise(value) |
| 1134 |
|
| 1135 |
|
| 1136 |
class PacBioBooleanOption(BasePacBioOption): |
| 1137 |
OPTION_TYPE_ID = TaskOptionTypes.BOOL |
| 1138 |
|
| 1139 |
@classmethod |
| 1140 |
def validate_core_type(cls, value): |
| 1141 |
return _strict_validate_bool_or_raise(value) |
| 1142 |
|
| 1143 |
|
| 1144 |
class PacBioStringOption(BasePacBioOption): |
| 1145 |
OPTION_TYPE_ID = TaskOptionTypes.STR |
| 1146 |
|
| 1147 |
@classmethod |
| 1148 |
def validate_core_type(cls, value): |
| 1149 |
return _strict_validate_string_or_raise(value) |
| 1150 |
|
| 1151 |
|
| 1152 |
class PacBioFileOption(BasePacBioOption): |
| 1153 |
OPTION_TYPE_ID = TaskOptionTypes.FILE |
| 1154 |
|
| 1155 |
@classmethod |
| 1156 |
def validate_core_type(cls, value): |
| 1157 |
return _strict_validate_file_or_raise(value) |
| 1158 |
|
| 1159 |
|
| 1160 |
def _strict_validate_default_and_choices(core_type_validator_func): |
| 1161 |
""" |
| 1162 |
|
| 1163 |
:param core_type_validator_func: Function (value) => value or raises TypeError |
| 1164 |
|
| 1165 |
Returns a func of (value, choices) => value, choices or raises TypeError |
| 1166 |
or Value Error. |
| 1167 |
""" |
| 1168 |
def wrap(value, choices): |
| 1169 |
for choice in choices: |
| 1170 |
core_type_validator_func(choice) |
| 1171 |
v = core_type_validator_func(value) |
| 1172 |
if v not in choices: |
| 1173 |
raise ValueError( |
| 1174 |
"Default value {v} is not in allowed choices {c}".format( |
| 1175 |
v=value, c=choices)) |
| 1176 |
return v, choices |
| 1177 |
return wrap |
| 1178 |
|
| 1179 |
|
| 1180 |
_strict_validate_int_choices = _strict_validate_default_and_choices( |
| 1181 |
_strict_validate_int_or_raise) |
| 1182 |
_strict_validate_str_choices = _strict_validate_default_and_choices( |
| 1183 |
_strict_validate_string_or_raise) |
| 1184 |
_strict_validate_bool_choices = _strict_validate_default_and_choices( |
| 1185 |
_strict_validate_bool_or_raise) |
| 1186 |
_strict_validate_float_choices = _strict_validate_default_and_choices( |
| 1187 |
_strict_validate_float_or_raise) |
| 1188 |
|
| 1189 |
|
| 1190 |
class BaseChoiceType(BasePacBioOption): |
| 1191 |
|
| 1192 |
|
| 1193 |
def __init__(self, option_id, name, default, description, choices): |
| 1194 |
super().__init__( |
| 1195 |
option_id, |
| 1196 |
name, |
| 1197 |
default, |
| 1198 |
description) |
| 1199 |
_, validated_choices = self.validate_core_type_with_choices( |
| 1200 |
default, choices) |
| 1201 |
self.choices = validated_choices |
| 1202 |
|
| 1203 |
@classmethod |
| 1204 |
def validate_core_type_with_choices(cls, value, choices): |
| 1205 |
raise NotImplementedError |
| 1206 |
|
| 1207 |
def validate_option(self, value): |
| 1208 |
v, _ = self.validate_core_type_with_choices(value, self.choices) |
| 1209 |
return v |
| 1210 |
|
| 1211 |
def to_dict(self): |
| 1212 |
d = super().to_dict() |
| 1213 |
d['choices'] = self.choices |
| 1214 |
return d |
| 1215 |
|
| 1216 |
|
| 1217 |
class PacBioIntChoiceOption(BaseChoiceType): |
| 1218 |
OPTION_TYPE_ID = TaskOptionTypes.CHOICE_INT |
| 1219 |
|
| 1220 |
@classmethod |
| 1221 |
def validate_core_type(cls, value): |
| 1222 |
return _strict_validate_int_or_raise(value) |
| 1223 |
|
| 1224 |
@classmethod |
| 1225 |
def validate_core_type_with_choices(cls, value, choices): |
| 1226 |
return _strict_validate_int_choices(value, choices) |
| 1227 |
|
| 1228 |
|
| 1229 |
class PacBioStringChoiceOption(BaseChoiceType): |
| 1230 |
OPTION_TYPE_ID = TaskOptionTypes.CHOICE_STR |
| 1231 |
|
| 1232 |
@classmethod |
| 1233 |
def validate_core_type(cls, value): |
| 1234 |
return _strict_validate_string_or_raise(value) |
| 1235 |
|
| 1236 |
@classmethod |
| 1237 |
def validate_core_type_with_choices(cls, value, choices): |
| 1238 |
return _strict_validate_str_choices(value, choices) |
| 1239 |
|
| 1240 |
|
| 1241 |
class PacBioFloatChoiceOption(BaseChoiceType): |
| 1242 |
OPTION_TYPE_ID = TaskOptionTypes.CHOICE_FLOAT |
| 1243 |
|
| 1244 |
@classmethod |
| 1245 |
def validate_core_type(cls, value): |
| 1246 |
return _strict_validate_float_or_raise(value) |
| 1247 |
|
| 1248 |
@classmethod |
| 1249 |
def validate_core_type_with_choices(cls, value, choices): |
| 1250 |
return _strict_validate_float_choices(value, choices) |
| 1251 |
|
| 1252 |
|
| 1253 |
def _get_exception_name(e): |
| 1254 |
if isinstance(e, Exception): |
| 1255 |
return e.__class__.__name__ |
| 1256 |
else: |
| 1257 |
return str(e) |
| 1258 |
|
| 1259 |
|
| 1260 |
def _get_level_name(l): |
| 1261 |
if isinstance(l, int): |
| 1262 |
return logging.getLevelName(l) |
| 1263 |
else: |
| 1264 |
return l |
| 1265 |
|
| 1266 |
|
| 1267 |
class PacBioAlarm: |
| 1268 |
""" |
| 1269 |
Simple container for alarms that need to be passed between components in |
| 1270 |
SMRT Link. This mimics the interface in the instrument control code; note |
| 1271 |
that not all fields will necessarily be used by SMRT Link. The JSON I/O |
| 1272 |
format is always a list to support the possibility of multiple alarms |
| 1273 |
created by the same task, but we mostly only need to work with one at a |
| 1274 |
time. |
| 1275 |
""" |
| 1276 |
|
| 1277 |
def __init__(self, |
| 1278 |
name, |
| 1279 |
message, |
| 1280 |
exception=None, |
| 1281 |
info=None, |
| 1282 |
severity=logging.ERROR, |
| 1283 |
created_at=None, |
| 1284 |
owner=None, |
| 1285 |
id_=None): |
| 1286 |
self.message = message |
| 1287 |
self.name = name |
| 1288 |
self.exception = exception |
| 1289 |
self.info = info |
| 1290 |
self.severity = _get_level_name(severity) |
| 1291 |
self.owner = owner |
| 1292 |
self.id = id_ if id_ is not None else str(uuid.uuid4()) |
| 1293 |
self.created_at = created_at if created_at is not None else datetime.datetime.now() |
| 1294 |
|
| 1295 |
@staticmethod |
| 1296 |
def from_dict(d): |
| 1297 |
return PacBioAlarm(d["name"], |
| 1298 |
d["message"], |
| 1299 |
d["exception"], |
| 1300 |
d["info"], |
| 1301 |
d["severity"], |
| 1302 |
owner=d.get("owner", None), |
| 1303 |
id_=d.get("id", None)) |
| 1304 |
|
| 1305 |
@property |
| 1306 |
def log_level(self): |
| 1307 |
return getattr(logging, self.severity) |
| 1308 |
|
| 1309 |
def to_dict(self): |
| 1310 |
return { |
| 1311 |
"exception": _get_exception_name(self.exception), |
| 1312 |
"info": self.info, |
| 1313 |
"message": self.message, |
| 1314 |
"name": self.name, |
| 1315 |
"severity": self.severity, |
| 1316 |
"owner": self.owner, |
| 1317 |
"createdAt": _datetime_to_string(self.created_at), |
| 1318 |
"id": str(self.id) |
| 1319 |
} |
| 1320 |
|
| 1321 |
def to_json(self, file_name): |
| 1322 |
with open(file_name, "w") as json_out: |
| 1323 |
json_out.write(json.dumps([self.to_dict()], |
| 1324 |
indent=2, |
| 1325 |
separators=(',', ': '), |
| 1326 |
sort_keys=True)) |
| 1327 |
return self |
| 1328 |
|
| 1329 |
@staticmethod |
| 1330 |
def from_json(file_name): |
| 1331 |
with open(file_name, "r") as json_in: |
| 1332 |
return PacBioAlarm.from_dict(json.loads(json_in.read())[0]) |
| 1333 |
|
| 1334 |
def raise_exception(self): |
| 1335 |
raise self.exception(self.message) |
| 1336 |
|
| 1337 |
@staticmethod |
| 1338 |
def dump_error(file_name, |
| 1339 |
exception, |
| 1340 |
info, |
| 1341 |
message, |
| 1342 |
name, |
| 1343 |
severity): |
| 1344 |
return PacBioAlarm( |
| 1345 |
name, |
| 1346 |
message, |
| 1347 |
exception, |
| 1348 |
info, |
| 1349 |
severity, |
| 1350 |
owner="python").to_json(file_name) |
| 1351 |
|
| 1352 |
|
| 1353 |
class PipelinePreset: |
| 1354 |
|
| 1355 |
def __init__(self, options, task_options, pipeline_id, |
| 1356 |
preset_id, name, description): |
| 1357 |
self.options = options |
| 1358 |
self.task_options = task_options |
| 1359 |
self.pipeline_id = pipeline_id |
| 1360 |
self.preset_id = preset_id |
| 1361 |
self.name = name |
| 1362 |
self.description = description |
| 1363 |
|
| 1364 |
def __repr__(self): |
| 1365 |
_d = dict(k=self.__class__.__name__) |
| 1366 |
return "<{k} >".format(**_d) |
| 1367 |
|
| 1368 |
def to_dict(self): |
| 1369 |
return OrderedDict([ |
| 1370 |
("pipelineId", self.pipeline_id), |
| 1371 |
("presetId", self.preset_id), |
| 1372 |
("name", self.name), |
| 1373 |
("description", self.description), |
| 1374 |
("options", dict(self.options)), |
| 1375 |
("taskOptions", dict(self.task_options))]) |
| 1376 |
|
| 1377 |
|
| 1378 |
class EntryPoint(namedtuple("EntryPoint", ["entry_id", "file_type_id", "name", "optional"])): |
| 1379 |
|
| 1380 |
@staticmethod |
| 1381 |
def from_dict(d): |
| 1382 |
return EntryPoint(d["entryId"], d["fileTypeId"], d["name"], |
| 1383 |
d.get("optional", False)) |
| 1384 |
|
| 1385 |
@property |
| 1386 |
def short_name(self): |
| 1387 |
return self.file_type_id.split(".")[-1] + " XML" |
| 1388 |
|
| 1389 |
@property |
| 1390 |
def file_ext(self): |
| 1391 |
return FileTypes.ALL()[self.file_type_id].ext |