view numerics/data.py @ 48:36e47061187f

stub a transposition function
author Jeff Hammel <k0scist@gmail.com>
date Mon, 19 Jan 2015 12:38:51 -0800
parents 87615a38190c
children 5caa67643162
line wrap: on
line source

# -*- coding: utf-8 -*-

"""
data models
"""

from collections import OrderedDict

__all__ = ['ColumnNumberException', 'ColumnLengthException', 'Rows', 'Columns']


class ColumnNumberException(Exception):
    """
    wrong number of columns: {given} given; {expected} expected
    """
    def __init__(self, given, expected):
        self.given = given
        self.expected = expected
        Exception.__init__(self.__doc__.format(**self.__dict__).strip())


def transpose(array):
    """makes rows into columns or vice versa"""

    if not array:
        return array  # nothing to do

    n_cols = len(array[0])
    retval = []] * n_cols
    raise NotImplementedError('TODO') # -> record TODO items

class ColumnLengthException(ColumnNumberException):
    """
    wrong length of column: {given} given; {expected} expected
    """
    # XXX should share ABC, not inherit from ColumnNumberException


class Rows(object):
    """
    row-based data
    """

    array = OrderedDict

    def __init__(self, columns, *rows):
        """
        columns -- column labels
        """
        self.column_names = columns
        self.rows = []

        for row in rows:
            self += row

    def __iadd__(self, row):
        """add a labeled row"""
        if len(row) != len(self.columns_names):
            raise ColumnNumberException(len(row), len(self.columns_names))
        self.rows.append(self.array(zip(self.columns_names, row)))

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, item):
        return self.rows[item]


class Columns(object):
    """
    column-oriented data
    """

    def __init__(self, *columns):
        self.columns = OrderedDict()  # this should be ordered
        for name, values in columns:
            self += (name, values)

    def __iadd__(self, item):
        column_name, values = item
        assert column_name not in self.columns
        return self