Поиск по блогу

вторник, 11 февраля 2014 г.

Пример из руководства по PyTabes

Здесь мы рассмотрим второй пример из PyTables Tutorials. Код этого и других примеров можно найти в репозитории GitHub PyTables
Для того, чтобы понять, чего не могут PyTables, нужно прочитать Hints for SQL users. Здесь ясно можно проследить аналогии: файл .h5 это база данных, классы или словари таблиц - это определение бполей БД..., а вот с перекрестными запросами проблемы...

Кроме того, есть еще форум, он старый, новый перенесен Гугл-группы
It will cover the most usual SQL statements. If you are missing a particular statement or usage example, you can ask at the PyTables users’ list (старый форум)
После предварительного изучения ясно, что бибилотека ( и сама идея) старые. Среди достоинств - возможность комментирования (пользовательские атрибуты), скорость...
А среди недостатков - отсутствие перектестных запросов. Частично это компенсируется тем, что можно сделать отдельный массив или таблицу, и его включать (при помощи ссылкок) в другие таблицы..., но...
Есть подозрение, что есть более новый "технологии" работы с табличными данными..., но здесь пытаемся понять PyTables
В нижней части этого поста попытки просмотреть файлы .h5 с помощью утилит (dump) вызвали проблемы. Потому я загрузил ViTables с сайта бинарниковUnofficial Windows Binaries for Python Extension Packages.

Что мне нужно от бибилиотеки pytables.

Мои размышления о том, как обрабатывать большое количесвто таблиц сначала затормозили мои проекты "Data Mining", но потом привели к осознаию того, что надо найти уже готовые бибилиотеки для работы с таблицами.
Например, я беру сайт про автомобили и скачиваю с него 100 файлов .csv про автомобили Nissan. По этим файлам я могу определить, что потребителям нравится в современных ниссанах, потом я могу проделать то же самое с тойотами, фордами...
Все эти файлы могут быть с разных сайтов, я, скорее всего, буду работать с ними в разное время...
Возможно, через год я буду иссследовать рынок труда и мне придет в голову идея о том, что спрос на автоэлектриков должен коррелировать с модой на "псевдоквадроаудио" системы, которые так популярнв сегодня у покупателей ниссанов.
Получается, что мне нужен максимально гибкий архив проектов... и возможность быстрого импорта данных из разных проектов. При этом, каждый проект должен быть закомментирован так, чтобы сразу была понятна структура данных.
Ни традиционная база данных, ни текстовый формат для этого не подходят. Нужен новый подход. Его я и надеюсь найти в PyTables

Multidimensional table cells and automatic sanity checks

Now it’s time for a more real-life example (i.e. with errors in the code). We will create two groups that branch directly from the root node, Particles and Events. Then, we will put three tables in each group. In Particles we will put tables based on the Particle descriptor and in Events, the tables based the Event descriptor.
Afterwards, we will provision the tables with a number of records. Finally, we will read the newly-created table /Events/TEvent3 and select some values from it, using a comprehension list.
Look at the next script (you can find it in examples/tutorial2.py). It appears to do all of the above, but it contains some small bugs. Note that this Particle class is not directly related to the one defined in last tutorial; this class is simpler (note, however, the multidimensional columns called pressure and temperature).
We also introduce a new manner to describe a Table as a structured NumPy dtype (or even as a dictionary), as you can see in the Event description. See File.create_table() about the different kinds of descriptor objects that can be passed to this method:
In [1]:
from tables import *
from numpy import *
In [2]:
# Describe a particle record
class Particle(IsDescription):
    name        = StringCol(itemsize=16)  # 16-character string
    lati        = Int32Col()              # integer
    longi       = Int32Col()              # integer
    pressure    = Float32Col(shape=(2,3)) # array of floats (single-precision)
    temperature = Float64Col(shape=(2,3)) # array of doubles (double-precision)

# Native NumPy dtype instances are also accepted
Event = dtype([
    ("name"     , "S16"),
    ("TDCcount" , uint8),
    ("ADCcount" , uint16),
    ("xcoord"   , float32),
    ("ycoord"   , float32)
    ])

# And dictionaries too (this defines the same structure as above)
# Event = {
#     "name"     : StringCol(itemsize=16),
#     "TDCcount" : UInt8Col(),
#     "ADCcount" : UInt16Col(),
#     "xcoord"   : Float32Col(),
#     "ycoord"   : Float32Col(),
#     }
In [3]:
# Open a file in "w"rite mode
fileh = open_file("tutorial2.h5", mode = "w")

# Get the HDF5 root group
root = fileh.root

# Create the groups:
for groupname in ("Particles", "Events"):
    group = fileh.create_group(root, groupname)

# Now, create and fill the tables in Particles group
gparticles = root.Particles
In [12]:
# Create 3 new tables
for tablename in ("TParticle0", "TParticle2", "TParticle3"):
    # Create a table
    table = fileh.create_table("/Particles", tablename, Particle, "Particles: "+tablename)

    # Get the record object associated with the table:
    particle = table.row
    # Fill the table with 257 particles
    for i in xrange(257):
        # First, assign the values to the Particle record
        particle['name'] = 'Particle: %6d' % (i)
        particle['lati'] = i
        particle['longi'] = 10 - i

        ########### Detectable errors start here. Play with them!
        #particle['pressure'] = array(i*arange(2*3)).reshape((2,4))  # Incorrect
        particle['pressure'] = array(i*arange(2*3)).reshape((2,3)) # Correct
        ########### End of errors

        particle['temperature'] = (i**2)     # Broadcasting

        # This injects the Record values
        particle.append()

    # Flush the table buffers
    table.flush()
In [13]:
 # Now, go for Events:
for tablename in ("TEvent1", "TEvent2", "TEvent3"):
    # Create a table in Events group
    table = fileh.create_table(root.Events, tablename, Event, "Events: "+tablename)

    # Get the record object associated with the table:
    event = table.row

    # Fill the table with 257 events
    for i in xrange(257):
        # First, assign the values to the Event record
        event['name']  = 'Event: %6d' % (i)
        event['TDCcount'] = i % (1<<8)   # Correct range

        ########### Detectable errors start here. Play with them!
        #event['xcoor'] = float(i**2)     # Wrong spelling
        event['xcoord'] = float(i**2)   # Correct spelling
        #event['ADCcount'] = "sss"        # Wrong type
        event['ADCcount'] = i * 2       # Correct type
        ########### End of errors

        event['ycoord'] = float(i)**4

        # This injects the Record values
        event.append()

    # Flush the buffers
    table.flush()
In [14]:
# Read the records from table "/Events/TEvent3" and select some
table = root.Events.TEvent3
e = [ p['TDCcount'] for p in table if p['ADCcount'] < 20 and 4 <= p['TDCcount'] < 15 ]
print("Last record ==>", p)
print("Selected values ==>", e)
print("Total selected records ==> ", len(e))

# Finally, close the file (this also will flush all the remaining buffers!)
fileh.close()
('Last record ==>', /Events/TEvent3.row (Row), pointing to row #256)
('Selected values ==>', [4, 5, 6, 7, 8, 9])
('Total selected records ==> ', 6)

In [19]:
!chcp 65001
!ptdump tutorial2.h5
Active code page: 65001

'ptdump' is not recognized as an internal or external command,
operable program or batch file.

In [20]:
!h5ls -rd tutorial2.h5
'h5ls' is not recognized as an internal or external command,
operable program or batch file.

Почему мое подозрение крепнет? Вот утилиты не работают, в руководстве ссылок нет... Явные следы запустения... Бибилиотеке более 10 лет, почему ее перестали обновлять?


Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий