Skip to content

asymcat.common

Reading data and collecting co-occurrences. The functions most often needed are also available from the top-level package, as asymcat.collect_cooccs, asymcat.read_sequences and so on.

Utility functions for the asymcat library.

The module mostly includes functions for input/output, as well as pre-computations from raw data.

collect_alphabets

collect_alphabets(cooccs: list[tuple]) -> tuple

Return the x and y alphabets from a list of co-occurrences.

Parameters:

Name Type Description Default
cooccs List[tuple]

The list of co-occurrence tuples.

required

Returns:

Name Type Description
alphabets tuple

A tuple of two elements, the sorted list of symbols in series x and the sorted list of symbols in series y.

Raises:

Type Description
ValueError

If cooccs is empty or contains invalid tuples.

TypeError

If cooccs is not a list or contains non-tuple elements.

collect_ngrams

collect_ngrams(seq: list[Any] | str, order: int, pad: str) -> Generator[tuple, None, None]

Function for yielding the ngrams of a sequence.

The sequence is padded so that symbols at the extremities will be repeated the same number of times that other symbols. This operation also guarantees that sequences shorter than the order will be collected.

Parameters:

Name Type Description Default
seq Union[List[Any], str]

The list/string of elements for ngram collection.

required
order int

The ngram order.

required
pad str

The padding symbol.

required

Yields:

Name Type Description
ngram tuple

The ngrams of the sequence.

Raises:

Type Description
ValueError

If order is less than 1 or seq is empty.

TypeError

If seq is not a list, tuple, or string, or order is not an integer.

collect_cooccs

collect_cooccs(seqs: list[list[list[Any] | str] | tuple], order: int | None = None, pad: str = '#') -> list[tuple]

Collects tuples of co-occurring elements in pairs of sequences.

This function is used for collecting co-occurring elements in order to train or improve scorers. Co-occurrences can be collected either considering sequences in their entirety, or by aligned ngrams.

When collecting ngrams, a padding symbol is used internally to guarantee that elements at the extremities of the sequences will be collected the same number of times that other elements. The padding symbol defaults to "#", but given that the tuples where it occurs are automatically removed before returning, it is important that such symbol is not a part of either of the sequence alphabets. It is the user responsability to set an appropriate, non-conflicting pad symbol in case the default is used in the data.

Parameters:

Name Type Description Default
seqs List[Union[List[Union[List[Any], str]], tuple]]

A list of sequence pairs (each sequence can be a list or string).

required
order Optional[int]

The order of the ngrams to be collected, with None indicating the collection of the entire sequences (default: None).

None
pad str

The symbol for internal padding, which must not conflict with symbols in the sequences (default: "#").

'#'

Returns:

Name Type Description
coocc List[tuple]

A list of tuples of co-occurring elements.

Raises:

Type Description
ValueError

If seqs is empty, contains invalid sequence pairs, or sequences have mismatched lengths.

TypeError

If seqs is not a list or contains invalid data types.

collect_observations

collect_observations(cooccs: list[tuple]) -> dict

Build a dictionary of observations for all possible correspondences.

The counts of observations are derived from typical organization in a non-squared contingency table, using indexes 0, 1, and 2, where 0 means that the identity is not considered (so that "00" would refer to all correspondence pairs), 1 that there is a match, and 2 that there is a mismatch. In more detail, given a pair of symbols x and y, the counts of co-occurrences will be:

  • obs["10"]: number of pairs matching x (with any y)
  • obs["20"]: number of pairs not matching x (with any y)
  • obs["01"]: number of pairs matching y (with any x)
  • obs["02"]: number of pairs not matching y (with any x)
  • obs["11"]: number of pairs matching x and matching y
  • obs["12"]: number of pairs matching x and not matching y
  • obs["21"]: number of pairs not matching x and matching y
  • obs["22"]: number of pairs not matching x and matching Y

Note that obs["22"] is not the number of pairs where either x or y are mismatching, but where both necessarily mismatch.

When doing x->y, a non-squared contingency table will be

|            |  pair[1]  | pair[1]==y | pair[1]!=y |
| pair[0]==x | obs["10"] | obs["11"]  | obs["12"]  |
| pair[0]!=x | obs["20"] | obs["21"]  | obs["22"]  |

Parameters:

Name Type Description Default
cooccs List[tuple]

A list of tuples of co-occurring elements.

required

Returns:

Name Type Description
obs dict

A dictionary of observations per co-occurrence type.

Raises:

Type Description
ValueError

If cooccs is empty or contains invalid tuples.

TypeError

If cooccs is not a list.

build_ct

build_ct(observ, square: bool = True) -> list

Build a contingency table from a dictionary of observations.

The contingency table can be either square (2x2) or not (3x2). Non-squared contingency tables include co-occurrences where neither the x or y under investigation occur.

Parameters:

Name Type Description Default
observ dict

A dictionary of observations, as provided by common.collect_observations().

required
square bool

Whether to return a square (2x2) or non-square (3x2) contingency table.

True

Returns:

Name Type Description
cont_table array

A contingency table as a numpy array.

read_sequences

read_sequences(filename: str, cols: list[str] | None = None, col_delim: str = '\t', elem_delim: str = ' ') -> list[list[list[str]]]

Reads parallel sequences, returning them as a list of lists.

Datafiles should have one sequence pair per row, with pairs separated by col_delim and elements delimited by elem_delim, as in:

Orthography                 Segments
E X C L A M A T I O N       ɛ k s k l ʌ m eɪ ʃ ʌ n
C L O S E Q U O T E         k l oʊ z k w oʊ t
D O U B L E Q U O T E       d ʌ b ʌ l k w oʊ t
E N D O F Q U O T E         ɛ n d ʌ v k w oʊ t
E N D Q U O T E             ɛ n d k w oʊ t
I N Q U O T E S             ɪ n k w oʊ t s
Q U O T E                   k w oʊ t
U N Q U O T E               ʌ n k w oʊ t
H A S H M A R K             h æ m ɑ ɹ k

Rows without complete data are not included. The function allows to collect data from multiple columns, but it is inteded to pairwise comparison; if no column names are provided, as per default, the reading will skip the first row (assumed to be header).

Parameters:

Name Type Description Default
filename str

Path to the file to be read.

required
cols Optional[List[str]]

List of column names to be collected (default: None)

None
col_delim str

String used as field delimiter (default: " ").

'\t'
elem_delim str

String used as element delimiter (default: " ").

' '

Returns:

Name Type Description
data List[List[List[str]]]

A list of lists, where each list contains the data from a row.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist.

ValueError

If file is empty or has invalid format.

PermissionError

If file cannot be read due to permissions.

read_pa_matrix

read_pa_matrix(filename: str, delimiter: str = '\t') -> list[tuple]

Reads a presence-absence matrix, returning as equivalent sequences.

The location must be specified under column name ID.

Parameters:

Name Type Description Default
filename str

Path to the file to be read.

required
delimiter str

String used as field delimiter (default: " ").

'\t'

Returns:

Name Type Description
obs_combinations List[tuple]

A list of tuples representing observed combinations.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist.

ValueError

If file format is invalid or ID column is missing.