SlideShare a Scribd company logo
1 of 14
HDF5
                            Hierarchical Data Format




Thursday, January 5, 2012
/the/object/tree
                     • Datasets, Leaf
                      • Tables, records with fixed-length fields
                      • Arrays: Matrices of same type
                        • VLArray, EArray, Array
                     • Groups
                      • May contain groups and datasets
Thursday, January 5, 2012
from tables import *

                            # Define a user record to characterize some kind of particles
                            class Particle(IsDescription):
                                name      = StringCol(16)   # 16-character String
                                idnumber = Int64Col()       # Signed 64-bit integer
                                ADCcount = UInt16Col()      # Unsigned short integer
                                TDCcount = UInt8Col()       # unsigned byte
                                grid_i    = Int32Col()      # integer
                                grid_j    = Int32Col()      # integer
                                pressure = Float32Col()     # float (single-precision)
                                energy    = FloatCol()      # double (double-precision)

                            filename = "test.h5"
                            # Open a file in "w"rite mode
                            h5file = openFile(filename, mode = "w", title = "Test file")
                            # Create a new group under "/" (root)
                            group = h5file.createGroup("/", 'detector', 'Detector information')
                            # Create one table on it
                            table = h5file.createTable(group, 'readout', Particle, "Readout example")
                            # Fill the table with 10 particles
                            particle = table.row
                            for i in xrange(10):
                                particle['name'] = 'Particle: %6d' % (i)
                                particle['TDCcount'] = i % 256
                                particle['ADCcount'] = (i * 256) % (1 << 16)
                                particle['grid_i'] = i
                                particle['grid_j'] = 10 - i
                                particle['pressure'] = float(i*i)
                                particle['energy'] = float(particle['pressure'] ** 4)
                                particle['idnumber'] = i * (2 ** 34)
                                # Insert a new particle record
                                particle.append()
                            # Close (and flush) the file
                            h5file.close()




Thursday, January 5, 2012
Thursday, January 5, 2012
Filling a table
                            >>> class Particle(IsDescription):
                            ...     name      = StringCol(16)     #   16-character String
                            ...     idnumber = Int64Col()         #   Signed 64-bit integer
                            ...     ADCcount = UInt16Col()        #   Unsigned short integer
                            ...     TDCcount = UInt8Col()         #   unsigned byte
                            ...     grid_i    = Int32Col()        #   32-bit integer
                            ...     grid_j    = Int32Col()        #   32-bit integer
                            ...     pressure = Float32Col()       #   float (single-precision)
                            ...     energy    = Float64Col()      #   double (double-precision)




                            >>>   table = h5file.root.detector.readout
                            >>>   particle = table.row
                            >>>   for i in xrange(10, 15):
                            ...       particle['name'] = 'Particle: %6d' % (i)
                            ...       particle['TDCcount'] = i % 256
                            ...       particle['ADCcount'] = (i * 256) % (1 << 16)
                            ...       particle['grid_i'] = i
                            ...       particle['grid_j'] = 10 - i
                            ...       particle['pressure'] = float(i*i)
                            ...       particle['energy'] = float(particle['pressure'] ** 4)
                            ...       particle['idnumber'] = i * (2 ** 34)
                            ...       particle.append()
                            >>>   table.flush()




Thursday, January 5, 2012
Accessing a table:
                                 Slicing

                             >>> table.cols.TDCcount[0] = 1
                             >>> table.cols.energy[1:9:3] = [2,3,4]




Thursday, January 5, 2012
Search in Tables
                            >>> class Particle(IsDescription):
                            ...     name      = StringCol(16)    #   16-character String
                            ...     idnumber = Int64Col()        #   Signed 64-bit integer
                            ...     ADCcount = UInt16Col()       #   Unsigned short integer
                            ...     TDCcount = UInt8Col()        #   unsigned byte
                            ...     grid_i    = Int32Col()       #   32-bit integer
                            ...     grid_j    = Int32Col()       #   32-bit integer
                            ...     pressure = Float32Col()      #   float (single-precision)
                            ...     energy    = Float64Col()     #   double (double-precision)




>>> table = h5file.root.detector.readout
>>> pressure = [x['pressure'] for x in table.iterrows() if x['TDCcount'] > 3 and 20 <= x
['pressure'] < 50]
>>> pressure
[25.0, 36.0, 49.0]

                                             “In-Kernel” Version
>>> names = [ x['name'] for x in table.where("""(TDCcount > 3) & (20 <= pressure) & (pressure < 50)"
>>> names
['Particle:      5', 'Particle:      6', 'Particle:      7']

Thursday, January 5, 2012
Attributes

                            >>>   table = h5file.root.detector.readout
                            >>>   table.attrs.gath_date = "Wed, 06/12/2003 18:33"
                            >>>   table.attrs.temperature = 18.4
                            >>>   table.attrs.temp_scale = "Celsius"




Thursday, January 5, 2012
(C)Arrays
                    import numpy
                    import tables

                    fileName = 'carray1.h5'
                    shape = (200, 300)
                    atom = tables.UInt8Atom()
                    filters = tables.Filters(complevel=5, complib='zlib')

                    h5f = tables.openFile(fileName, 'w')
                    ca = h5f.createCArray(h5f.root, 'carray', atom, shape, filters=filters)

                    # Fill a hyperslab in ``ca``.
                    ca[10:60, 20:70] = numpy.ones((50, 50))
                    h5f.close()

                    # Re-open and read another hyperslab
                    h5f = tables.openFile(fileName)
                    print h5f
                    print h5f.root.carray[8:12, 18:22]
                    h5f.close()




Thursday, January 5, 2012
(E)Arrays
                   import tables
                   import numpy

                   fileh = tables.openFile('earray1.h5', mode='w')
                   a = tables.StringAtom(itemsize=8)

                   # Use ''a'' as the object type for the enlargeable array.
                   array_c = fileh.createEArray(fileh.root, 'array_c', a, (0,), "Chars")
                   array_c.append(numpy.array(['a'*2, 'b'*4], dtype='S8'))
                   array_c.append(numpy.array(['a'*6, 'b'*8, 'c'*10], dtype='S8'))

                   # Read the string ''EArray'' we have created on disk.
                   for s in array_c:
                       print 'array_c[%s] => %r' % (array_c.nrow, s)

                   # Close the file.
                   fileh.close()




Thursday, January 5, 2012
Pytables likes Numpy
>>> gcolumns = h5file.createGroup(h5file.root, "columns", "Pressure and Name")

>>> h5file.createArray(gcolumns, 'pressure', array(pressure))
"Pressure column selection")
/columns/pressure (Array(3,)) 'Pressure column selection'
  atom := Float64Atom(shape=(), dflt=0.0)
  maindim := 0
  flavor := 'numpy'
  byteorder := 'little'
  chunkshape := None

>>> h5file.createArray(gcolumns, 'name', names, "Name column selection")
/columns/name (Array(3,)) 'Name column selection'
  atom := StringAtom(itemsize=16, shape=(), dflt='')
  maindim := 0
  flavor := 'python'
  byteorder := 'irrelevant'
  chunkshape := None




Thursday, January 5, 2012
def _get_pgroup(self, file, p, proj = None):
         """
         Get group node of tables.File corresponding to property p.

           Creates group node, if it does not exist yet.

           :param tables.File file: Handle to HDF5 file to which records are saved.
           :param string p: To be recorded property.
           :param Projection proj: Projection from which property p is recorded.

           :return: Group node corresponding to property p.
           """

           SDict = self.sim.config.ShapeDispatch

           if not proj:
               name = self.sheet.name
           else:
               name = proj.name

           try:
                  pgroup = file.getNode('/%s_%s' % (p, name,))

           except NoSuchNodeError:
               pgroup = file.createGroup('/', '%s_%s' % (p, name,))
               file.createEArray(pgroup, 'data', Float64Atom(),
                   flatten((0, SDict[p])))
               file.createEArray(pgroup, 'step', Int32Atom(), (0, 1))

           return pgroup

     def _write_attr(self, pgroup, data):
         """
         Helper fn writing provided data and step count to group node (of
         tables.File)

           :param tables.group.Group pgroup: Group node to which data is saved.
           :param numpy.Array data: Data matrix to be recorded.
           """

           pgroup.data.append([data])
           pgroup.step.append([[self.count]])
Thursday, January 5, 2012
def function(self):
           """
           Stores activity submatrices from recordings file per node to 3D array
           and returns reshaped 2D version of it.
           """

                x = self.x
                y = self.y
                size = self.size
                nnames = self.nnames

                array = np.zeros((len(nnames), size, size))

                with openFile(self.path, 'r') as file:
                    for i, nname in enumerate(nnames):
                        node = file.getNode(nname)
                        array[i, :, :] = 
                            node.data.read(self.cnt)[0, x : x + size, y : y + size]

                return array.reshape(size, size * len(nnames))




Thursday, January 5, 2012
Useful Programs


                     • HDFView or ViTables
                     • h5dump
                     • hdf5read, hdf5info (MATLAB)


Thursday, January 5, 2012

More Related Content

What's hot

WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0Knoldus Inc.
 
The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180Mahmoud Samir Fayed
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 46 of 210
The Ring programming language version 1.9 book - Part 46 of 210The Ring programming language version 1.9 book - Part 46 of 210
The Ring programming language version 1.9 book - Part 46 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84Mahmoud Samir Fayed
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 

What's hot (20)

WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0
 
The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196
 
The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
The Ring programming language version 1.9 book - Part 46 of 210
The Ring programming language version 1.9 book - Part 46 of 210The Ring programming language version 1.9 book - Part 46 of 210
The Ring programming language version 1.9 book - Part 46 of 210
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.5.1 book - Part 43 of 180
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189The Ring programming language version 1.6 book - Part 38 of 189
The Ring programming language version 1.6 book - Part 38 of 189
 
The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212The Ring programming language version 1.10 book - Part 40 of 212
The Ring programming language version 1.10 book - Part 40 of 212
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
 
The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180The Ring programming language version 1.5.1 book - Part 34 of 180
The Ring programming language version 1.5.1 book - Part 34 of 180
 
The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Object calisthenics
Object calisthenicsObject calisthenics
Object calisthenics
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 

Viewers also liked

intro to scikits.learn
intro to scikits.learnintro to scikits.learn
intro to scikits.learnrocketcircus
 
Social media
Social mediaSocial media
Social mediaSheila A
 
Online Reputation Management and Sentiment Analysis
Online Reputation Management and Sentiment AnalysisOnline Reputation Management and Sentiment Analysis
Online Reputation Management and Sentiment AnalysisNgocSapphire
 
Rdp Software &amp; IT Eligibility
Rdp Software &amp; IT EligibilityRdp Software &amp; IT Eligibility
Rdp Software &amp; IT Eligibilityrkun
 
HR Development Acedemy, Znalostný manažment a sociálne siete
HR Development Acedemy, Znalostný manažment a sociálne sieteHR Development Acedemy, Znalostný manažment a sociálne siete
HR Development Acedemy, Znalostný manažment a sociálne sieteVIRTA s.r.o.
 
Invertebrates alvaro
Invertebrates alvaroInvertebrates alvaro
Invertebrates alvarolola caravaca
 
89 the bermuda triangle mystery
89 the bermuda triangle mystery89 the bermuda triangle mystery
89 the bermuda triangle mysterygorin2008
 
The economy mamartinez5b
The economy mamartinez5bThe economy mamartinez5b
The economy mamartinez5blola caravaca
 
Crop circles dreamcometrue
Crop circles dreamcometrueCrop circles dreamcometrue
Crop circles dreamcometruegorin2008
 
I -Zone-ERP SYSTEM
I -Zone-ERP SYSTEMI -Zone-ERP SYSTEM
I -Zone-ERP SYSTEMCodeZone
 
Need To Hire Someone For Your Business
Need To Hire Someone For Your BusinessNeed To Hire Someone For Your Business
Need To Hire Someone For Your BusinessKellyBrad
 

Viewers also liked (20)

intro to scikits.learn
intro to scikits.learnintro to scikits.learn
intro to scikits.learn
 
Social media
Social mediaSocial media
Social media
 
Emily yeung
Emily yeungEmily yeung
Emily yeung
 
Online Reputation Management and Sentiment Analysis
Online Reputation Management and Sentiment AnalysisOnline Reputation Management and Sentiment Analysis
Online Reputation Management and Sentiment Analysis
 
Science 5ºb celia
Science 5ºb celiaScience 5ºb celia
Science 5ºb celia
 
Carlo 1
Carlo 1Carlo 1
Carlo 1
 
Ecosystems
EcosystemsEcosystems
Ecosystems
 
презентация лузановой с.в.
презентация лузановой с.в.презентация лузановой с.в.
презентация лузановой с.в.
 
Rdp Software &amp; IT Eligibility
Rdp Software &amp; IT EligibilityRdp Software &amp; IT Eligibility
Rdp Software &amp; IT Eligibility
 
HR Development Acedemy, Znalostný manažment a sociálne siete
HR Development Acedemy, Znalostný manažment a sociálne sieteHR Development Acedemy, Znalostný manažment a sociálne siete
HR Development Acedemy, Znalostný manažment a sociálne siete
 
Invertebrates alvaro
Invertebrates alvaroInvertebrates alvaro
Invertebrates alvaro
 
89 the bermuda triangle mystery
89 the bermuda triangle mystery89 the bermuda triangle mystery
89 the bermuda triangle mystery
 
The economy mamartinez5b
The economy mamartinez5bThe economy mamartinez5b
The economy mamartinez5b
 
Crop circles dreamcometrue
Crop circles dreamcometrueCrop circles dreamcometrue
Crop circles dreamcometrue
 
I -Zone-ERP SYSTEM
I -Zone-ERP SYSTEMI -Zone-ERP SYSTEM
I -Zone-ERP SYSTEM
 
The economy pedro
The economy pedroThe economy pedro
The economy pedro
 
Dial 000
Dial 000Dial 000
Dial 000
 
Need To Hire Someone For Your Business
Need To Hire Someone For Your BusinessNeed To Hire Someone For Your Business
Need To Hire Someone For Your Business
 
Anuncio colombovo
Anuncio colombovoAnuncio colombovo
Anuncio colombovo
 
Sea ecosystem 4
Sea ecosystem 4Sea ecosystem 4
Sea ecosystem 4
 

Similar to Pytables

Introduction to Python Programming.ppt
Introduction to Python Programming.pptIntroduction to Python Programming.ppt
Introduction to Python Programming.pptUmeshKumarSingh31
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
Python tutorial
Python tutorialPython tutorial
Python tutorialRajiv Risi
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
Python Cheat Sheet 2.0.pdf
Python Cheat Sheet 2.0.pdfPython Cheat Sheet 2.0.pdf
Python Cheat Sheet 2.0.pdfRahul Jain
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPTAlbin562191
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxHongAnhNguyn285885
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data ManipulationChu An
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfparthp5150s
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfkeerthu0442
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesSubhajit Sahu
 

Similar to Pytables (20)

Introduction to Python Programming.ppt
Introduction to Python Programming.pptIntroduction to Python Programming.ppt
Introduction to Python Programming.ppt
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Array
ArrayArray
Array
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Python Cheat Sheet 2.0.pdf
Python Cheat Sheet 2.0.pdfPython Cheat Sheet 2.0.pdf
Python Cheat Sheet 2.0.pdf
 
Array
ArrayArray
Array
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Arrays
ArraysArrays
Arrays
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPT
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 

More from rocketcircus

More from rocketcircus (7)

Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
Python Academy
Python AcademyPython Academy
Python Academy
 
AWS Quick Intro
AWS Quick IntroAWS Quick Intro
AWS Quick Intro
 
PyPy 1.5
PyPy 1.5PyPy 1.5
PyPy 1.5
 
Message Queues
Message QueuesMessage Queues
Message Queues
 
Rocket Circus on Code Review
Rocket Circus on Code ReviewRocket Circus on Code Review
Rocket Circus on Code Review
 

Recently uploaded

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Recently uploaded (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Pytables

  • 1. HDF5 Hierarchical Data Format Thursday, January 5, 2012
  • 2. /the/object/tree • Datasets, Leaf • Tables, records with fixed-length fields • Arrays: Matrices of same type • VLArray, EArray, Array • Groups • May contain groups and datasets Thursday, January 5, 2012
  • 3. from tables import * # Define a user record to characterize some kind of particles class Particle(IsDescription): name = StringCol(16) # 16-character String idnumber = Int64Col() # Signed 64-bit integer ADCcount = UInt16Col() # Unsigned short integer TDCcount = UInt8Col() # unsigned byte grid_i = Int32Col() # integer grid_j = Int32Col() # integer pressure = Float32Col() # float (single-precision) energy = FloatCol() # double (double-precision) filename = "test.h5" # Open a file in "w"rite mode h5file = openFile(filename, mode = "w", title = "Test file") # Create a new group under "/" (root) group = h5file.createGroup("/", 'detector', 'Detector information') # Create one table on it table = h5file.createTable(group, 'readout', Particle, "Readout example") # Fill the table with 10 particles particle = table.row for i in xrange(10): particle['name'] = 'Particle: %6d' % (i) particle['TDCcount'] = i % 256 particle['ADCcount'] = (i * 256) % (1 << 16) particle['grid_i'] = i particle['grid_j'] = 10 - i particle['pressure'] = float(i*i) particle['energy'] = float(particle['pressure'] ** 4) particle['idnumber'] = i * (2 ** 34) # Insert a new particle record particle.append() # Close (and flush) the file h5file.close() Thursday, January 5, 2012
  • 5. Filling a table >>> class Particle(IsDescription): ... name = StringCol(16) # 16-character String ... idnumber = Int64Col() # Signed 64-bit integer ... ADCcount = UInt16Col() # Unsigned short integer ... TDCcount = UInt8Col() # unsigned byte ... grid_i = Int32Col() # 32-bit integer ... grid_j = Int32Col() # 32-bit integer ... pressure = Float32Col() # float (single-precision) ... energy = Float64Col() # double (double-precision) >>> table = h5file.root.detector.readout >>> particle = table.row >>> for i in xrange(10, 15): ... particle['name'] = 'Particle: %6d' % (i) ... particle['TDCcount'] = i % 256 ... particle['ADCcount'] = (i * 256) % (1 << 16) ... particle['grid_i'] = i ... particle['grid_j'] = 10 - i ... particle['pressure'] = float(i*i) ... particle['energy'] = float(particle['pressure'] ** 4) ... particle['idnumber'] = i * (2 ** 34) ... particle.append() >>> table.flush() Thursday, January 5, 2012
  • 6. Accessing a table: Slicing >>> table.cols.TDCcount[0] = 1 >>> table.cols.energy[1:9:3] = [2,3,4] Thursday, January 5, 2012
  • 7. Search in Tables >>> class Particle(IsDescription): ... name = StringCol(16) # 16-character String ... idnumber = Int64Col() # Signed 64-bit integer ... ADCcount = UInt16Col() # Unsigned short integer ... TDCcount = UInt8Col() # unsigned byte ... grid_i = Int32Col() # 32-bit integer ... grid_j = Int32Col() # 32-bit integer ... pressure = Float32Col() # float (single-precision) ... energy = Float64Col() # double (double-precision) >>> table = h5file.root.detector.readout >>> pressure = [x['pressure'] for x in table.iterrows() if x['TDCcount'] > 3 and 20 <= x ['pressure'] < 50] >>> pressure [25.0, 36.0, 49.0] “In-Kernel” Version >>> names = [ x['name'] for x in table.where("""(TDCcount > 3) & (20 <= pressure) & (pressure < 50)" >>> names ['Particle: 5', 'Particle: 6', 'Particle: 7'] Thursday, January 5, 2012
  • 8. Attributes >>> table = h5file.root.detector.readout >>> table.attrs.gath_date = "Wed, 06/12/2003 18:33" >>> table.attrs.temperature = 18.4 >>> table.attrs.temp_scale = "Celsius" Thursday, January 5, 2012
  • 9. (C)Arrays import numpy import tables fileName = 'carray1.h5' shape = (200, 300) atom = tables.UInt8Atom() filters = tables.Filters(complevel=5, complib='zlib') h5f = tables.openFile(fileName, 'w') ca = h5f.createCArray(h5f.root, 'carray', atom, shape, filters=filters) # Fill a hyperslab in ``ca``. ca[10:60, 20:70] = numpy.ones((50, 50)) h5f.close() # Re-open and read another hyperslab h5f = tables.openFile(fileName) print h5f print h5f.root.carray[8:12, 18:22] h5f.close() Thursday, January 5, 2012
  • 10. (E)Arrays import tables import numpy fileh = tables.openFile('earray1.h5', mode='w') a = tables.StringAtom(itemsize=8) # Use ''a'' as the object type for the enlargeable array. array_c = fileh.createEArray(fileh.root, 'array_c', a, (0,), "Chars") array_c.append(numpy.array(['a'*2, 'b'*4], dtype='S8')) array_c.append(numpy.array(['a'*6, 'b'*8, 'c'*10], dtype='S8')) # Read the string ''EArray'' we have created on disk. for s in array_c: print 'array_c[%s] => %r' % (array_c.nrow, s) # Close the file. fileh.close() Thursday, January 5, 2012
  • 11. Pytables likes Numpy >>> gcolumns = h5file.createGroup(h5file.root, "columns", "Pressure and Name") >>> h5file.createArray(gcolumns, 'pressure', array(pressure)) "Pressure column selection") /columns/pressure (Array(3,)) 'Pressure column selection' atom := Float64Atom(shape=(), dflt=0.0) maindim := 0 flavor := 'numpy' byteorder := 'little' chunkshape := None >>> h5file.createArray(gcolumns, 'name', names, "Name column selection") /columns/name (Array(3,)) 'Name column selection' atom := StringAtom(itemsize=16, shape=(), dflt='') maindim := 0 flavor := 'python' byteorder := 'irrelevant' chunkshape := None Thursday, January 5, 2012
  • 12. def _get_pgroup(self, file, p, proj = None): """ Get group node of tables.File corresponding to property p. Creates group node, if it does not exist yet. :param tables.File file: Handle to HDF5 file to which records are saved. :param string p: To be recorded property. :param Projection proj: Projection from which property p is recorded. :return: Group node corresponding to property p. """ SDict = self.sim.config.ShapeDispatch if not proj: name = self.sheet.name else: name = proj.name try: pgroup = file.getNode('/%s_%s' % (p, name,)) except NoSuchNodeError: pgroup = file.createGroup('/', '%s_%s' % (p, name,)) file.createEArray(pgroup, 'data', Float64Atom(), flatten((0, SDict[p]))) file.createEArray(pgroup, 'step', Int32Atom(), (0, 1)) return pgroup def _write_attr(self, pgroup, data): """ Helper fn writing provided data and step count to group node (of tables.File) :param tables.group.Group pgroup: Group node to which data is saved. :param numpy.Array data: Data matrix to be recorded. """ pgroup.data.append([data]) pgroup.step.append([[self.count]]) Thursday, January 5, 2012
  • 13. def function(self): """ Stores activity submatrices from recordings file per node to 3D array and returns reshaped 2D version of it. """ x = self.x y = self.y size = self.size nnames = self.nnames array = np.zeros((len(nnames), size, size)) with openFile(self.path, 'r') as file: for i, nname in enumerate(nnames): node = file.getNode(nname) array[i, :, :] = node.data.read(self.cnt)[0, x : x + size, y : y + size] return array.reshape(size, size * len(nnames)) Thursday, January 5, 2012
  • 14. Useful Programs • HDFView or ViTables • h5dump • hdf5read, hdf5info (MATLAB) Thursday, January 5, 2012