rc.base.models§

Abstract and concrete base classes for RomCom Models.

Properties§

MetaData

Type for passing metadata as **kwargs.

Matrix

Types which a DataBase Table accepts.

Classes§

Store

Base class for any stored class. Users are not expected to subclass this class directly.

Meta

Concrete class encapsulating metadata stored in a .json file.

Table

Concrete class encapsulating a pd.DataFrame backed by a .csv file.

DataBase

NamedTables(NamedTuple) in a folder alongside Meta. Abstract base class for any model.

Module Contents§

MetaData§

Type for passing metadata as **kwargs.

Matrix§

Types which a DataBase Table accepts.

class Store(path)[source]§

Bases: rc.base.definitions.ABC

Inheritance diagram of rc.base.models.Store

Base class for any stored class. Users are not expected to subclass this class directly.

Parameters:

path (rc.base.definitions.Path)

Path§

Class attribute aliasing Types used to specify the path to a Store. Do not override.

ext: str = ''§

Class attribute specifying the file extension terminating self.path. Override if and only if the derived class must be stored in a file. Otherwise, cls.ext == '' and the derived class is stored in a folder.

property path: rc.base.definitions.Path§

The Path to this Store, without cls.ext. File extension is internal, meaning self._path = self._path + cls.ext.

Return type:

rc.base.definitions.Path

__repr__()[source]§

The Path to this Store.

Return type:

str

__str__()[source]§

The Path to this Store, abbreviated.

Return type:

str

abstractmethod __call__(**data)[source]§

Update and store self.

Parameters:

**data – Data to update.

Return type:

rc.base.definitions.Self

Returns: self.

classmethod extAppend(path)[source]§

Append cls.ext to path.name.

Parameters:

path (rc.base.definitions.Path) – The path to append cls.ext to.

Return type:

rc.base.definitions.Path

Returns: Path(path) with cls.ext appended.

classmethod mkdir(path)[source]§

Create path.parent, with a subfolder path if cls.ext == ''.

Parameters:

path (rc.base.definitions.Path) – The folder to create, or a child file of the folder to create.

Return type:

rc.base.definitions.Path

Returns: Path(path) with cls.ext appended.

classmethod create(path)[source]§
Abstractmethod:

Parameters:

path (rc.base.definitions.Path)

Return type:

rc.base.definitions.Self | rc.base.definitions.Path

Create a folder (and its parents) if it doesn’t already exist.

Overrides should create and return an instance of cls.

Parameters:

path (rc.base.definitions.Path) – Where to create the folder. If cls.ext != '', the parent folder of path is created.

Returns:

path with extension f'.{cls.ext}'.

Raises:

FileExistsError – If attempting to overwrite a file with a folder.

Return type:

rc.base.definitions.Self | rc.base.definitions.Path

classmethod copy(src, dst)[source]§
Abstractmethod:

Parameters:
  • src (rc.base.definitions.Path)

  • dst (rc.base.definitions.Path)

Return type:

rc.base.definitions.Self | rc.base.definitions.Path

Copy src to dst, overwriting only files in common.

Overrides should copy an instance of cls called src to Store.create(dst), and return the copy.

Parameters:
  • src (rc.base.definitions.Path) – The source Path, which must be a folder or a file.

  • dst (rc.base.definitions.Path) – The destination Path, which may or may not exist.

Return type:

rc.base.definitions.Self | rc.base.definitions.Path

Returns: dst.

Raises:
  • FileNotFoundError – If src does not exist.

  • FileExistsError – If attempting to overwrite a file with a folder.

Parameters:
  • src (rc.base.definitions.Path)

  • dst (rc.base.definitions.Path)

Return type:

rc.base.definitions.Self | rc.base.definitions.Path

classmethod delete(path)[source]§

Delete any file or folder at path.

Parameters:

path (rc.base.definitions.Path) – The Path to delete.

Return type:

rc.base.definitions.Path

Returns: path, which no longer exists.

class Meta(path, **data)[source]§

Bases: Store, dict

Inheritance diagram of rc.base.models.Meta

Concrete class encapsulating metadata stored in a .json file.

Parameters:
  • path (Store)

  • data (rc.base.definitions.Any)

ext: str = '.json'§

Class attribute specifying the file extension terminating self.path. Override if and only if the derived class must be stored in a file. Otherwise, cls.ext == '' and the derived class is stored in a folder.

__call__(**data)[source]§

Update and store self, overwriting.

Parameters:

**data (rc.base.definitions.Any) – Data to update self.data.

Return type:

rc.base.definitions.Self

Returns: self.

__setitem__(key, value)[source]§

Indexer sets the value indexed by key.

classmethod create(path, **data)[source]§

Create a Meta at path, overwriting.

Parameters:
  • path (Store) – The Path (file) to store self, overwritten if existing. A .json extension is automatically appended.

  • **data (rc.base.definitions.Any) – The MetaData to store.

Returns: The Meta created.

classmethod copy(src, dst)[source]§

Copy src to dst, overwriting.

Parameters:
  • src (Meta) – The source Meta.

  • dst (Store) – The destination Path, overwritten if existing. A .json extension is automatically appended.

Return type:

rc.base.definitions.Self

Returns: The Meta now stored at dst.json.

class Table(path, data=None, **options)[source]§

Bases: Store

Inheritance diagram of rc.base.models.Table

Concrete class encapsulating a pd.DataFrame backed by a .csv file.

This class may be usefully overridden to provide bespoke read and write options for file operations. Subclasses should follow the template (copy and paste it):

class MyTable(Table):

class Options(NamedTuple):

    read: MetaData =  {'index_col': 0}  #: Read options passed to ``pd.read_csv``.
    write: MetaData =  {}   #: Write options passed to ``pd.DataFrame.to_csv``.

    @classmethod
    def default(cls) -> MetaData:
        """ Returns the default Options as ``cls.read | cls.write``."""
        return cls._field_defaults['read'] | cls._field_defaults['write']
Parameters:
  • path (Store)

  • data (rc.base.definitions.Self | rc.base.definitions.Pd.DataFrame | None)

  • options (rc.base.definitions.Any)

ext: str = '.csv'§

Class attribute specifying the file extension terminating self.path. Override if and only if the derived class must be stored in a file. Otherwise, cls.ext == '' and the derived class is stored in a folder.

writeOptions: list[str] = ['sep', 'na_rep', 'float_format']§

Class attribute listing kwargs which will be interpreted as write options. All other kwargs are interpreted as read options. To specify a separator, use delimiter as read option and sep as write option.

property options: MetaData§

A dict of options for file operations involving ``self. Any option not in Table.writeOptions is stored in self.options.read and passed to pd.read_csv. Any option in Table.writeOptions is stored in self.options.write and passed to pd.DataFrame.to_csv. The setter updates via logical or |=, so existing values are retained unless explicitly updated.

Return type:

MetaData

property pd: rc.base.definitions.Pd.DataFrame§

The Pd.DataFrame stored in self.

Return type:

rc.base.definitions.Pd.DataFrame

property np: rc.base.definitions.Np.Matrix§

The Np.Matrix stored in self.

Return type:

rc.base.definitions.Np.Matrix

property tc: rc.base.definitions.Tc.Matrix§

The TF.Matrix stored in self.

Return type:

rc.base.definitions.Tc.Matrix

broadcast_to(target_shape, is_diagonal=True)[source]§

Broadcast self.

Parameters:
  • target_shape (rc.base.definitions.Tuple[int, int]) – The shape to broadcast to.

  • is_diagonal (bool) – Whether to zero the off-diagonal elements of a square matrix.

Return type:

rc.base.definitions.Self

Returns: self.

Raises:

IndexError – If broadcasting is impossible.

Parameters:
  • target_shape (rc.base.definitions.Tuple[int, int])

  • is_diagonal (bool)

Return type:

rc.base.definitions.Self

__call__(data, **options)[source]§

Update and store self, overwriting.

Parameters:
  • data (rc.base.definitions.Self | Matrix | None) – The data updates.

  • **options (rc.base.definitions.Any) – Updates self.options, before storing self.

Return type:

rc.base.definitions.Self

Returns: self.

classmethod create(path, data=None, index=None, columns=None, dtype=None, copy=None, **metadata)[source]§

Create a Table at path, overwriting.

Parameters:
  • path (Store) – The Path to store this DataTable, overwritten if existing. A .csv extension is automatically appended.

  • data (rc.base.definitions.Self | Matrix | None) – The data to store. If None, a Pd.DataFrame is read from .csv. See pd.DataFrame.

  • index (rc.base.definitions.Pd.Index | rc.base.definitions.Np.Array) –

    See pd.DataFrame.

  • columns (rc.base.definitions.Pd.Index | rc.base.definitions.Np.Array) –

    See pd.DataFrame.

  • dtype (rc.base.definitions.Np.DType | None) –

    See pd.DataFrame.

  • copy (bool | None) –

    See pd.DataFrame.

  • **metadata – MetaData passed to pd.read_csv or pd.DataFrame.to_csv.

Return type:

rc.base.definitions.Self

Returns: The DataTable created.

classmethod copy(src, dst)[source]§

Copy src to dst, overwriting.

Parameters:
  • src (rc.base.definitions.Self) – The source DataTable.

  • dst (Store) – The destination Path, overwritten if existing. A .csv extension is automatically appended.

Return type:

rc.base.definitions.Self

Returns: The DataTable now stored at dst.csv.

class DataBase(path, **tables)[source]§

Bases: Store

Inheritance diagram of rc.base.models.DataBase

NamedTables(NamedTuple) in a folder alongside Meta. Abstract base class for any model.

DataBase subclasses must be implemented according to the template (copy and paste it):

class MyDataBase(DataBase):

    class NT(NamedTuple):

        names[i]: Table | Matrix | MetaData = pd.DataFrame(defaults[names[i]].pd)   #: Comment
        ...

        def __call__(self, name: str) -> Table | Matrix | MetaData:
            """ Returns the Table named ``name``."""
            return getattr(self, name)


    options: NamedTables[MetaData] = NamedTables(**{name: table.options for name, table in {}.items()})
    """ Class attribute of the form ``NamedTables(**{names[i]: options[i], ...})``.
    Override as necessary for bespoke ``Table.options``.
    Elements of ``options[i]`` found in ``Table.writeOptions`` populate ``self[i].options.write``,
    the remainder populate ``self[i].options.read``."""

    defaultMetaData: MetaData = {'Tables': Tables.options._asdict()}
Parameters:
  • path (Store)

  • tables (Table | rc.base.definitions.Pd.DataFrame)

class NamedTables[source]§

Bases: rc.base.definitions.NamedTuple

Inheritance diagram of rc.base.models.DataBase.NamedTables

Must be overridden.

__call__(name)[source]§

Returns the Table named name.

Parameters:

name (str)

Return type:

Table | Matrix | MetaData

options: NamedTables[MetaData]§

Class attribute of the form NamedTables(**{names[i]: options[i], ...}). Override as necessary for bespoke Table.options. Elements of options[i] found in Table.writeOptions populate self[i].options.write, the remainder populate self[i].options.read.

property nt: NamedTables§

The NamedTables currently in self.

Return type:

NamedTables

property meta: Meta§

The Meta currently in self.

Return type:

Meta

__len__()[source]§

Counts the Table s in self.

Return type:

int

__getitem__(name)[source]§

Indexer returns the Table (s) named or sliced by name.

Parameters:

name (str | slice)

Return type:

Table | rc.base.definitions.Tuple[Table, Ellipsis]

__setitem__(name, tables)[source]§

Indexer sets the Table (s) named or sliced by name.

Parameters:
  • name (str | slice)

  • tables (Table | Matrix | rc.base.definitions.Tuple[Table | Matrix, Ellipsis])

__call__(**tables)[source]§

Update and store self, overwriting.

Parameters:
  • path – Optionally, an update to self.path, overwritten if existing.

  • **tables (Table | Matrix) – Updates to self in the form names[i]=Table[i], ....

Return type:

rc.base.definitions.Self

Returns: self.

classmethod names()[source]§

(names[i], ...) of table names for this Tables class.

Return type:

rc.base.definitions.Tuple[str, Ellipsis]

classmethod defaults()[source]§

{names[i]: Pd.DataFrame[i], ...} of default tables for this Tables class.

Return type:

rc.base.definitions.Dict[str, rc.base.definitions.Pd.DataFrame]

classmethod create(path, **tables_and_meta)[source]§

Create a DataBase in path.

Parameters:
  • path (Store) – The folder to store the DataBase in. Need not exist, any existing Tables will be overwritten if it does.

  • **tables_and_meta (Table | rc.base.definitions.Pd.DataFrame | MetaData) – Data to update cls.defaults(), in the form names[i]=tables[i], and optional MetaData to update cls.defaultMetaData in the form meta=MetaData.

Return type:

rc.base.definitions.Self

Returns: The DataBase created.

classmethod copy(src, dst)[source]§

Copy src to dst, overwriting any files in common.

Parameters:
  • src (rc.base.definitions.Self) – The source DataBase.

  • dst (Store) – The destination Path, which may or may not exist.

Return type:

rc.base.definitions.Self

Returns: The DataBase now stored in dst.

classmethod delete(path)[source]§

Delete all DataBase files in path, retaining path and any other files it contains.

If you wish to delete path entirely, use Store.delete(path) instead.

Parameters:

path (Store) – Path to the DataBase to delete.

Return type:

rc.base.definitions.Path

Returns: path, which still exists.