def test04a_validReprEnum(self): """Checking the string representation of an enumeration.""" colors = tables.Enum(['red', 'green', 'blue']) enumcol = tables.EnumCol(colors, 'red', base='uint32', shape=()) # needed due to "Hash randomization" (default on python 3.3) template = """EnumCol(enum=Enum({%s}), dflt='red', base=UInt32Atom(shape=(), dflt=0), shape=(), pos=None)""" permitations = [template % ', '.join(items) for items in itertools.permutations( ("'blue': 2", "'green': 1", "'red': 0"))] self.assertTrue(repr(enumcol) in permitations)
def _createAtom(self, enum, dflt, base='uint32', shape=()): """Create and check an enumerated atom.""" enumatom = tables.EnumAtom(enum, dflt, base=base, shape=shape) sameEnum = tables.Enum(enum) self.assertEqual(enumatom.type, 'enum') self.assertEqual(enumatom.dtype.base.name, enumatom.base.type) self.assertEqual(enumatom.shape, shape) self.assertEqual(enumatom.enum, sameEnum)
class XRefTable(tables.IsDescription): EntryNr = tables.UInt32Col(pos=1) XRefSource = tables.EnumCol( tables.Enum({ 'UniProtKB/SwissProt': 0, 'UniProtKB/TrEMBL': 10, 'Ensembl Protein': 20, 'Ensembl Gene': 25, 'Ensembl Transcript': 30, 'RefSeq': 40, 'EntrezGene': 50, 'FlyBase': 60, 'WormBase': 65, 'EnsemblGenomes': 70, 'NCBI': 75, 'EMBL': 80, 'SourceID': 95, 'SourceAC': 100, 'HGNC': 105, 'Gene Name': 110, 'Synonym': 115, 'Protein Name': 120, 'ORF Name': 125, 'Ordered Locus Name': 130, 'PMP': 150, 'PDB': 155, 'WikiGene': 160, 'IPI': 240, 'GI': 241, 'n/a': 255 }), # last line: deprecated systems 'n/a', base='uint8', pos=2) XRefId = tables.StringCol(50, pos=3) Verification = tables.EnumCol(tables.Enum({ 'exact': 0, 'modified': 1, 'unchecked': 2 }), 'unchecked', base='uint8', pos=4)
def _createCol(self, enum, dflt, base='uint32', shape=()): """Create and check an enumerated column description.""" enumcol = tables.EnumCol(enum, dflt, base=base, shape=shape) sameEnum = tables.Enum(enum) self.assertEqual(enumcol.type, 'enum') self.assertEqual(enumcol.dtype.base.name, enumcol.base.type) # To avoid 'LongInt' vs 'Int' issues # self.assertEqual(enumcol.dflt, sameEnum[dflt]) self.assertEqual(int(enumcol.dflt), int(sameEnum[dflt])) self.assertEqual(enumcol.dtype.shape, shape) self.assertEqual(enumcol.enum, sameEnum)
def test(self): self.assertIn('/EnumTest', self.h5file) arr = self.h5file.get_node('/EnumTest') self.assertIsInstance(arr, tables.Array) enum = arr.get_enum() expectedEnum = tables.Enum(['RED', 'GREEN', 'BLUE', 'WHITE', 'BLACK']) self.assertEqual(enum, expectedEnum) data = list(arr.read()) expectedData = [ enum[name] for name in ['RED', 'GREEN', 'BLUE', 'WHITE', 'BLACK', 'RED', 'GREEN', 'BLUE', 'WHITE', 'BLACK']] self.assertEqual(data, expectedData)
class PairwiseRelationTable(tables.IsDescription): EntryNr1 = tables.UInt32Col(pos=0) EntryNr2 = tables.UInt32Col(pos=1) RelType = tables.EnumCol(tables.Enum({ '1:1': 0, '1:n': 1, 'm:1': 2, 'm:n': 3, 'close paralog': 4, 'homeolog': 5, 'n/a': 6 }), 'n/a', base='uint8', pos=2) Score = tables.Float32Col(pos=3, dflt=-1) Distance = tables.Float32Col(pos=4, dflt=-1) AlignmentOverlap = tables.Float16Col(pos=5, dflt=-1) SyntenyConservationLocal = tables.Float16Col(pos=6, dflt=-1) Confidence = tables.Float16Col(pos=7, dflt=-1)
def main(): with tables.open_file(file_path, 'w', title='Hello, PyTables!') as f: group = f.create_group(f.root, 'group', 'My first PyTables group') data = [[1,2,3,4], [5,6,7,8], [9,10,11,12]] array = f.create_array(group, 'dataset', np.array(data), 'My first PyTables array') array.attrs.double = math.pi hello = '你好!' array.attrs['hello-zh_CN'] = hello hello_utf8 = hello.encode('utf-8') hello_ascii = 'Hello, world!' array.attrs['string-ascii'] = hello_ascii array.attrs['string-utf8'] = hello_utf8 array.attrs['boolean'] = True color_enum = tables.Enum({"RED": 0, "GREEN": 1, "BLUE": 42}) array.attrs.color = color_enum.RED
'attrs': { 'search': None, 'fraction': None, 'project': None, 'ms1': None, 'scans': None, 'precursor': None, 'product': None, 'matched': None, }, 'root': { 'files': [] } } SCAN_MODES = tb.Enum(['null', 'spectra', 'matched']) # DATA # ---- SOURCE_ATTRIBUTES = ('quantitative', 'fingerprinting', 'reporterions') PRECURSOR_KEYS = ('precursor_num', 'precursor_rt', 'precursor_mz', 'precursor_z') @logger.init('matched', 'DEBUG') @mapping.serializable('DataTable') class DataTable(dict): '''Matched datatable interface to XL Discoverer''' def __init__(self, data=None, **attrs):
# if hasattr(numpy, 'complex192'): # type_info['complex192'] = (numpy.complex192, complex) # if hasattr(numpy, 'complex256'): # type_info['complex256'] = (numpy.complex256, complex) sctype_from_type = dict((type_, info[0]) for (type_, info) in type_info.items()) """Maps PyTables types to NumPy scalar types.""" nxtype_from_type = dict((type_, info[1]) for (type_, info) in type_info.items()) """Maps PyTables types to Numexpr types.""" heavy_types = frozenset(['uint8', 'int16', 'uint16', 'float32', 'complex64']) """PyTables types to be tested only in heavy mode.""" enum = tables.Enum(dict(('n%d' % i, i) for i in range(_maxnvalue))) """Enumerated type to be used in tests.""" # Table description # ----------------- def append_columns(classdict, shape=()): """Append a ``Col`` of each PyTables data type to the `classdict`. A column of a certain TYPE gets called ``c_TYPE``. The number of added columns is returned. """ heavy = common.heavy for (itype, type_) in enumerate(sorted(type_info.keys())): if not heavy and type_ in heavy_types:
# load modules import shutil import tables as tb from xldlib.objects import sqlite from xldlib.resources import paths from xldlib.utils import logger # load objects/functions from collections import defaultdict # ENUMS # ----- LimitedDatabase = tb.Enum(['None', 'Mild', 'Strict']) # HELPERS # ------- def get_path(path): '''Returns a valid path object, which defaults to the current db''' if path is None: path = paths.DYNAMIC['current_proteins'] return path # CONSTRUCTORS # ------------
class EnumVLArrayTestCase(common.TempFileMixin, common.PyTablesTestCase): """Test variable-length arrays of enumerated values.""" enum = tables.Enum({'red': 4, 'green': 2, 'blue': 1, 'black': 0}) valueInEnum = enum.red valueOutOfEnum = 1234 enumType = 'uint16' def _atom(self, shape=()): return tables.EnumAtom( self.enum, 'red', base=self.enumType, shape=shape) def test00a_reopen(self): """Reopening a file with variable-length arrays using enumerated data.""" self.h5file.create_vlarray( '/', 'test', self._atom(), title=self._getMethodName()) self.h5file.root.test.flavor = 'python' self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") def test00b_reopenMD(self): """ Reopening a file with variable-length arrays using enumerated multi-dimensional data. """ self.h5file.create_vlarray( '/', 'test', self._atom((2,)), title=self._getMethodName()) self.h5file.root.test.flavor = 'python' self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") def test01_append(self): """Appending scalar elements of enumerated values.""" vlarr = self.h5file.create_vlarray( '/', 'test', self._atom(), title=self._getMethodName()) vlarr.flavor = 'python' appended = [ [self.valueInEnum, ], [self.valueInEnum, self.valueOutOfEnum]] vlarr.append(appended[0]) vlarr.append(appended[1]) vlarr.flush() read = vlarr.read() common.verbosePrint( "* appended value: %s\n" "* read value: %s\n" % (appended, read)) self.assertEqual(appended, read, "Written and read values differ.") def test02_appendMD(self): """Appending multi-dimensional elements of enumerated values.""" vlarr = self.h5file.create_vlarray( '/', 'test', self._atom((2,)), title=self._getMethodName()) vlarr.flavor = 'python' appended = [ [[self.valueInEnum, self.valueInEnum], ], [[self.valueInEnum, self.valueOutOfEnum], [self.valueInEnum, self.valueInEnum]]] vlarr.append(appended[0]) vlarr.append(appended[1]) vlarr.flush() read = vlarr.read() common.verbosePrint( "* appended value: %s\n" "* read value: %s\n" % (appended, read)) self.assertEqual(appended, read, "Written and read values differ.") def test03_setitem(self): """Changing enumerated values using ``vlarray.__setitem__()``.""" vlarr = self.h5file.create_vlarray( '/', 'test', self._atom(), title=self._getMethodName()) vlarr.flavor = 'python' appended = (self.valueInEnum, self.valueInEnum) vlarr.append(appended) written = [self.valueInEnum, self.valueOutOfEnum] vlarr[0] = written read = vlarr.read() common.verbosePrint( "* written value: %s\n" "* read value: %s\n" % (written, read)) self.assertEqual(written, read[0], "Written and read values differ.")
timeMaskReasonList.append("Flash in r1") timeMaskReasonList.append("Flash in r2") timeMaskReasonList.append("Flash in r3") timeMaskReasonList.append("Flash in r4") timeMaskReasonList.append("Flash in r5") timeMaskReasonList.append("Flash in r6") timeMaskReasonList.append("Flash in r7") timeMaskReasonList.append("Flash in r8") timeMaskReasonList.append("Flash in r9") timeMaskReasonList.append("Merged Flash") timeMaskReasonList.append("cosmic") timeMaskReasonList.append("poofing") timeMaskReasonList.append("hot pixel") timeMaskReasonList.append("cold pixel") timeMaskReasonList.append("dead pixel") timeMaskReasonList.append("manual hot pixel") timeMaskReasonList.append("manual cold pixel") timeMaskReasonList.append("laser not on") #Used in flashing wavecals timeMaskReasonList.append("laser not off") #Used in flashing wavecals timeMaskReasonList.append( "none") #To be used for photon lists where the photon is NOT time-masked. timeMaskReason = tables.Enum(timeMaskReasonList) class TimeMask(tables.IsDescription): """The pytables derived class that stores time intervals to be masked""" tBegin = tables.UInt32Col() # beginning time of this mask (clock ticks) tEnd = tables.UInt32Col() # ending time of this mask (clock ticks) reason = tables.EnumCol(timeMaskReason, "unknown", base='uint8')
import tables as tb from xldlib.general import mapping from xldlib.resources import paths from xldlib.utils import serialization # PATHS # ----- INPUT_FILE_PATH = os.path.join(paths.DIRS['data'], 'input_files.json') # ENUMS # ----- INPUT_FILE_TYPES = tb.Enum(['level_separated', 'hierarchical']) CROSSLINK_DISCOVERER_MODES = tb.Enum(['default', 'quantitative']) # OBJECTS # ------- @serialization.register("InputFilesTable") class InputFilesTable(mapping.TableModel): '''Definitions for input files''' # TABLE FACTORIES # --------------- __hierarchical = [("MS Scans", "scans"), ("Matched Output", "matched")] __default = [("Precursor Scans", "precursor"),
from namedlist import namedlist from xldlib.definitions import re from xldlib.general import sequence from xldlib.utils import serialization from xldlib.utils.io_ import typechecker from . import dicttools # ENUMS # ----- IDENTIFIERS = tb.Enum([ 'mgf', 'mzxml', 'mzml' ]) SPECTRAL_FORMATS = tb.Enum([ 'RAW', 'HDF5', 'XML', 'TEXT' ]) # OBJECTS # ------- @sequence.serializable("SpectralFormatVersion")
from xldlib.utils import serialization from . import column_defs # load objects/functions from collections import defaultdict, namedtuple # PATHS # ----- REPORT_PATH = os.path.join(paths.DIRS['data'], 'reports.json') # ENUMS # ----- REPORT_TYPES = tb.Enum(['dependent', 'independent']) DEPENDENT_REPORTS = tb.Enum(['overall', 'skyline']) LINKNAMES = tb.Enum( ['Standard', 'Low Confidence', 'Fingerprint', 'Incomplete']) LINKTYPES = tb.Enum( ['interlink', 'intralink', 'deadend', 'multilink', 'single']) # OBJECTS # ------- Report = namedtuple("Report", "name sheets") Independent = namedtuple("Independent", "linkname linktype sheet") Dependent = namedtuple("Dependent", "sheet")
def test04a_validReprEnum(self): """Checking the string representation of an enumeration.""" colors = tables.Enum(['red', 'green', 'blue']) enumcol = tables.EnumCol(colors, 'red', base='uint32', shape=()) assert repr(enumcol) == \ """EnumCol(enum=Enum({'blue': 2, 'green': 1, 'red': 0}), dflt='red', base=UInt32Atom(shape=(), dflt=0), shape=(), pos=None)"""
import subprocess import substages_parser import db_info import pymacs_request import testsuite_utils as utils import addr_space def int_repr(self): return "({0:08X}, {1:08X})".format(self.begin, self.end) intervaltree.Interval.__str__ = int_repr intervaltree.Interval.__repr__ = int_repr BOOKKEEPING = "bookkeeping" substage_types = tables.Enum([BOOKKEEPING, "loading", "patching"]) region_types = tables.Enum([ "future", 'global', 'patching', 'stack', 'symbol', 'readonly', BOOKKEEPING ]) vlist = ['rw', 'r', 'w', 'none', '?'] perms = tables.Enum(vlist + ["rwx", "x", "rx"]) class MemoryRegionInfo(tables.IsDescription): short_name = tables.StringCol(255) parent_name = tables.StringCol(255) name = tables.StringCol(255) comments = tables.StringCol(512) include_children = tables.BoolCol() reclassifiable = tables.BoolCol() do_print = tables.BoolCol()
from xldlib.resources import paths __all__ = [ 'ENZYMES', 'Protease', 'TERMINI', ] # PATHS # ----- ENZYME_PATH = os.path.join(paths.DIRS['data'], 'enzymes.json') # ENUMS # ----- TERMINI = tb.Enum(['N', 'C']) # OBJECTS # ------- @sequence.serializable("Protease") class Protease(namedlist("Protease", "name cut nocut side")): '''Definitions for a protease configuration object''' # RESIDUES # -------- _residues = set(building_blocks.ONE_LETTER) # PROPERTIES
# if hasattr(numpy, 'complex192'): # type_info['complex192'] = (numpy.complex192, complex) # if hasattr(numpy, 'complex256'): # type_info['complex256'] = (numpy.complex256, complex) sctype_from_type = {type_: info[0] for (type_, info) in type_info.items()} """Maps PyTables types to NumPy scalar types.""" nxtype_from_type = {type_: info[1] for (type_, info) in type_info.items()} """Maps PyTables types to Numexpr types.""" heavy_types = frozenset(['uint8', 'int16', 'uint16', 'float32', 'complex64']) """PyTables types to be tested only in heavy mode.""" enum = tb.Enum({'n%d' % i: i for i in range(_maxnvalue)}) """Enumerated type to be used in tests.""" # Table description # ----------------- def append_columns(classdict, shape=()): """Append a ``Col`` of each PyTables data type to the `classdict`. A column of a certain TYPE gets called ``c_TYPE``. The number of added columns is returned. """ heavy = common.heavy for (itype, type_) in enumerate(sorted(type_info)): if not heavy and type_ in heavy_types:
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import config import pytable_utils import intervaltree import tables import os from config import Main import csv from fiddle_extra import parse_am37x_register_tables import testsuite_utils as utils register_map = {} mmap_perms = tables.Enum(['rw', 'r', '?', 'rwx', 'x', 'w']) mmap_type = tables.Enum(['special', 'reserved', 'rom', 'ram', 'registers', 'virtual', 'other', 'iva2.2']) var_type = tables.Enum(['staticvar', 'register', 'othervar', 'heapvar', 'stackvar', 'text']) vlist = ['rw', 'r', 'w', 'none', '?'] var_perms = tables.Enum(vlist) perms = tables.Enum(vlist + ["rwx", "x", "rx"]) class MemMapEntry(tables.IsDescription):
class EnumTableTestCase(common.TempFileMixin, common.PyTablesTestCase): """Test tables with enumerated columns.""" enum = tables.Enum({'red': 4, 'green': 2, 'blue': 1, 'black': 0}) defaultName = 'black' valueInEnum = enum.red valueOutOfEnum = 1234 enumType = 'uint16' def _description(self, shape=()): class TestDescription(tables.IsDescription): rid = tables.IntCol(pos=0) rcolor = tables.EnumCol( self.enum, self.defaultName, base=self.enumType, shape=shape, pos=1) return TestDescription def test00a_reopen(self): """Reopening a file with tables using enumerated data.""" self.h5file.create_table( '/', 'test', self._description(), title=self._getMethodName()) self._reopen() self.assertEqual( self.h5file.root.test.get_enum('rcolor'), self.enum, "Enumerated type was not restored correctly from disk.") def test00b_reopenMD(self): """ Reopening a file with tables using enumerated multi-dimensional data. """ self.h5file.create_table( '/', 'test', self._description((2,)), title=self._getMethodName()) self._reopen() self.assertEqual( self.h5file.root.test.get_enum('rcolor'), self.enum, "Enumerated type was not restored correctly from disk.") def test01_rowAppend(self): """Appending enumerated values using ``row.append()``.""" tbl = self.h5file.create_table( '/', 'test', self._description(), title=self._getMethodName()) appended = [ (10, self.valueInEnum), (20, self.valueOutOfEnum)] row = tbl.row row['rid'] = appended[0][0] row['rcolor'] = appended[0][1] row.append() row['rid'] = appended[1][0] self.assertRaises( ValueError, operator.setitem, row, 'rcolor', appended[1][1]) tbl.flush() tbl.flavor = 'python' read = tbl.read() common.verbosePrint( "* appended value: %s\n" "* read value: %s\n" % (appended[:-1], read)) self.assertEqual( appended[:-1], read, "Written and read values differ.") def test02_append(self): """Appending enumerated values using ``table.append()``.""" tbl = self.h5file.create_table( '/', 'test', self._description(), title=self._getMethodName()) appended = [ (10, self.valueInEnum), (20, self.valueOutOfEnum)] tbl.append(appended) tbl.flush() tbl.flavor = 'python' read = tbl.read() common.verbosePrint( "* appended value: %s\n" "* read value: %s\n" % (appended, read)) self.assertEqual(appended, read, "Written and read values differ.") def test03_setitem(self): """Changing enumerated values using ``table.__setitem__()``.""" tbl = self.h5file.create_table( '/', 'test', self._description(), title=self._getMethodName()) appended = [ (10, self.valueInEnum), (20, self.valueInEnum)] tbl.append(appended) written = [ (10, self.valueInEnum), (20, self.valueOutOfEnum)] tbl[:] = written tbl.flavor = 'python' read = tbl.read() common.verbosePrint( "* written value: %s\n" "* read value: %s\n" % (written, read)) self.assertEqual(written, read, "Written and read values differ.") def test04_multidim(self): """Appending multi-dimensional enumerated data.""" tbl = self.h5file.create_table( '/', 'test', self._description((2,)), title=self._getMethodName()) appended = [ (10, (self.valueInEnum, self.valueOutOfEnum)), (20, (self.valueInEnum, self.valueOutOfEnum))] row = tbl.row row['rid'] = appended[0][0] self.assertRaises( ValueError, operator.setitem, row, 'rcolor', appended[0][1]) tbl.append(appended) tbl.flush() tbl.flavor = 'python' read = tbl.read() for i in range(len(appended)): self.assertEqual(appended[i][0], read[i][0], "Written and read values differ.") self.assertEqual(appended[i][1][0], read[i][1][0], "Written and read values differ.") self.assertEqual(appended[i][1][1], read[i][1][1], "Written and read values differ.") def test05_where(self): """Searching enumerated data.""" tbl = self.h5file.create_table( '/', 'test', self._description(), title=self._getMethodName()) appended = [ (10, self.valueInEnum), (20, self.valueInEnum), (30, self.valueOutOfEnum)] tbl.append(appended) tbl.flush() searched = [ (row['rid'], row['rcolor']) for row in tbl.where('rcolor == v', {'v': self.valueInEnum})] common.verbosePrint( "* ``valueInEnum``: %s\n" "* ``rcolor`` column: ``%s``\n" "* ``searched``: %s\n" "* Should look like: %s\n" % (self.valueInEnum, tbl.cols.rcolor, searched, appended[:-1])) self.assertEqual( searched, appended[:-1], "Search returned incorrect results.")
import numpy as np import tables as tb #'-**-**-**-**- The sample nested class description -**-**-**-**-**-' class Info(tb.IsDescription): """A sub-structure of Test""" _v_pos = 2 # The position in the whole structure name = tb.StringCol(10) value = tb.Float64Col(pos=0) colors = tb.Enum(['red', 'green', 'blue']) class NestedDescr(tb.IsDescription): """A description that has several nested columns.""" color = tb.EnumCol(colors, 'red', base='uint32') info1 = Info() class info2(tb.IsDescription): _v_pos = 1 name = tb.StringCol(10) value = tb.Float64Col(pos=0) class info3(tb.IsDescription): x = tb.Float64Col(dflt=1)
def test00a_validFromEnum(self): """Describing an enumerated column from an enumeration.""" colors = tables.Enum(['red', 'green', 'blue']) self._createCol(colors, 'red')
Contains library definitions for the MSFileReader API. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' # load modules import tables as tb # LIBRARY DEFINITIONS # ------------------- Sample_Type = tb.Enum([ 'Unknown', 'Blank', 'QC', 'Standard Clear (None)', 'Standard Update (None)', 'Standard Bracket (Open)', 'Standard Bracket Start (multiple brackets)', 'Standard Bracket End (multiple brackets' ]) Controller_Type = tb.Enum({ 'No device': -1, 'MS': 0, 'Analog': 1, 'A/D card': 2, 'PDA': 3, 'UV': 4 }) Cutoff_Type = tb.Enum([ 'None (all values returned)', 'Absolute (in intensity units)', 'Relative (to base peak)'
# Example to show how nested types can be dealed with PyTables # F. Alted 2005/05/27 import random import tables fileout = "nested1.h5" # An example of enumerated structure colors = tables.Enum(['red', 'green', 'blue']) def read(file): fileh = tables.open_file(file, "r") print("table (short)-->", fileh.root.table) print("table (long)-->", repr(fileh.root.table)) print("table (contents)-->", repr(fileh.root.table[:])) fileh.close() def write(file, desc, indexed): fileh = tables.open_file(file, "w") table = fileh.create_table(fileh.root, 'table', desc) for colname in indexed: table.colinstances[colname].create_index() row = table.row for i in range(10): row['x'] = i
class EnumEArrayTestCase(common.TempFileMixin, TestCase): """Test extendable arrays of enumerated values.""" enum = tables.Enum({'red': 4, 'green': 2, 'blue': 1, 'black': 0}) valueInEnum = enum.red valueOutOfEnum = 1234 enumType = 'uint16' def _atom(self, shape=()): return tables.EnumAtom( self.enum, 'red', base=self.enumType, shape=shape) def test00a_reopen(self): """Reopening a file with extendable arrays using enumerated data.""" self.h5file.create_earray( '/', 'test', self._atom(), shape=(0,), title=self._getMethodName()) self.h5file.root.test.flavor = 'python' self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") def test00b_reopenMD(self): """Reopening a file with extendable arrays using enumerated multi-dimensional data.""" self.h5file.create_earray( '/', 'test', self._atom(), shape=(0, 2), title=self._getMethodName()) self.h5file.root.test.flavor = 'python' self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") def test_enum_default_persistence_red(self): dflt = 'red' atom = tables.EnumAtom( self.enum, dflt, base=self.enumType, shape=()) self.h5file.create_earray('/', 'test', atom, shape=(0,), title=self._getMethodName()) self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") self.assertEqual( self.h5file.root.test.atom.dflt, self.enum[dflt], "The default value of enumerated type was not restored correctly " "from disk.") def test_enum_default_persistence_green(self): dflt = 'green' atom = tables.EnumAtom( self.enum, dflt, base=self.enumType, shape=()) self.h5file.create_earray('/', 'test', atom, shape=(0,), title=self._getMethodName()) self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") self.assertEqual( self.h5file.root.test.atom.dflt, self.enum[dflt], "The default value of enumerated type was not restored correctly " "from disk.") def test_enum_default_persistence_blue(self): dflt = 'blue' atom = tables.EnumAtom( self.enum, dflt, base=self.enumType, shape=()) self.h5file.create_earray('/', 'test', atom, shape=(0,), title=self._getMethodName()) self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") self.assertEqual( self.h5file.root.test.atom.dflt, self.enum[dflt], "The default value of enumerated type was not restored correctly " "from disk.") def test_enum_default_persistence_black(self): dflt = 'black' atom = tables.EnumAtom( self.enum, dflt, base=self.enumType, shape=()) self.h5file.create_earray('/', 'test', atom, shape=(0,), title=self._getMethodName()) self._reopen() self.assertEqual( self.h5file.root.test.get_enum(), self.enum, "Enumerated type was not restored correctly from disk.") self.assertEqual( self.h5file.root.test.atom.dflt, self.enum[dflt], "The default value of enumerated type was not restored correctly " "from disk.") def test01_append(self): """Appending scalar elements of enumerated values.""" earr = self.h5file.create_earray( '/', 'test', self._atom(), shape=(0,), title=self._getMethodName()) earr.flavor = 'python' appended = [self.valueInEnum, self.valueOutOfEnum] earr.append(appended) earr.flush() read = earr.read() self.assertEqual(appended, read, "Written and read values differ.") def test02_appendMD(self): """Appending multi-dimensional elements of enumerated values.""" earr = self.h5file.create_earray( '/', 'test', self._atom(), shape=(0, 2), title=self._getMethodName()) earr.flavor = 'python' appended = [ [self.valueInEnum, self.valueOutOfEnum], [self.valueInEnum, self.valueOutOfEnum]] earr.append(appended) earr.flush() read = earr.read() self.assertEqual(appended, read, "Written and read values differ.") def test03_setitem(self): """Changing enumerated values using ``earray.__setitem__()``.""" earr = self.h5file.create_earray( '/', 'test', self._atom(), shape=(0,), title=self._getMethodName()) earr.flavor = 'python' appended = (self.valueInEnum, self.valueInEnum) earr.append(appended) written = [self.valueInEnum, self.valueOutOfEnum] earr[:] = written read = earr.read() self.assertEqual(written, read, "Written and read values differ.")
# Example on using enumerated types under PyTables. # This file is intended to be run in an interactive Python session, # since it contains some statements that raise exceptions. # To run it, paste it as the input of ``python``. def COMMENT(string): pass COMMENT("**** Usage of the ``Enum`` class. ****") COMMENT("Create an enumeration of colors with automatic concrete values.") import tables colorList = ['red', 'green', 'blue', 'white', 'black'] colors = tables.Enum(colorList) COMMENT("Take a look at the name-value pairs.") print "Colors:", [v for v in colors] COMMENT("Access values as attributes.") print "Value of 'red' and 'white':", (colors.red, colors.white) print "Value of 'yellow':", colors.yellow COMMENT("Access values as items.") print "Value of 'red' and 'white':", (colors['red'], colors['white']) print "Value of 'yellow':", colors['yellow'] COMMENT("Access names.") print "Name of value %s:" % colors.red, colors(colors.red) print "Name of value 1234:", colors(1234)
from namedlist import namedlist import tables as tb from xldlib import exception from xldlib.general import sequence from xldlib.resources import chemical_defs from xldlib.utils import serialization from xldlib.utils.io_ import typechecker from . import dicttools # ENUMS # ----- SEARCH_IDENTIFIERS = tb.Enum( ['Protein Prospector', 'Mascot', 'Proteome Discoverer']) MATCHED_FORMATS = tb.Enum(['XML', 'TEXT', 'SQLITE', 'MIME']) # DATA # ---- MATCHED_TYPES = [ "modifications", "num", "peptide", "start", "fraction", "id", "name", "mz", "z", "ppm", "score", "ev" ] # HELPERS # -------
import numpy as np from scipy import integrate import tables as tb from xldlib import exception # load objects/functions from collections import namedtuple from .metrics import Metrics # ENUMS # ----- SPECTRAL_ENUM = tb.Enum({'Area': "area", 'Intensity': "ymax"}) INTEGRAL_ENUM = tb.Enum({ 'Included Charges': "charges", 'Integrated PPM': "ppm" }) # DATA # ---- XRANGE_KEYS = ('Min Window', 'Max Window') # OBJECTS # ------- WeightedPpm = namedtuple("WeightedPpm", "ppm weight")
# PATHS # ----- COLUMNSPATH = os.path.join(paths.DIRS['data'], 'columns.json') # ENUMS # ----- REPORTNAMES = tb.Enum([ 'report', 'best_peptide', 'best_peptide_file', 'comparative', 'comparative_named', 'quantitative', 'quantitative_comparative', 'skyline', 'overall', 'ratiotable', ]) BLOCKTYPES = tb.Enum([ 'static', 'sequential', 'clustered', 'unused', ]) # OBJECTS