Skip to content

gcam

Sparse GCAM dictionary counts and matched-word mean scores.

GCAMLexicon dataclass

GCAMLexicon(name: str, dimensions: Mapping[str, frozenset[str]], weighted_dimensions: Mapping[str, Mapping[str, float]] = dict(), tokenization: Mapping[str, str] = dict(), patterns: Mapping[str, tuple[str, ...]] = dict(), lemmatization: Mapping[str, str] = dict(), exceptions: Mapping[str, tuple[str, ...]] = dict(), theme_dimensions: Mapping[str, str] = dict(), theme_lexicon: ThemeLexicon | None = None, emit_count: Mapping[str, bool] = dict(), exclusions: Mapping[str, tuple[str, ...]] = dict(), languages: Mapping[str, str] = dict())

Reusable GCAM count dictionaries, weighted scores, and matching options.

dimensions maps count keys to word sets; weighted_dimensions maps score keys to word weights. Load compiled profiles with from_json and select dictionaries or languages before analysis.

implemented_dimensions property

implemented_dimensions: tuple[str, ...]

All supported serialized keys, including value-only dimensions.

without_dictionaries

without_dictionaries(disabled: Iterable[int | str] = ()) -> GCAMLexicon

Select a lexicon with the requested dictionaries excluded.

Parameters:

Name Type Description Default
disabled Iterable[int | str]

Collection of dictionary names, integer IDs, or numeric strings.

()

Returns:

Type Description
GCAMLexicon

A reusable selection, or this lexicon if no applicable IDs are excluded.

Raises:

Type Description
TypeError

If selectors have invalid types or form a bare string.

ValueError

If a dictionary name or ID is unknown.

Source code in src/gdelt_regkg/fields/gcam.py
def without_dictionaries(self, disabled: Iterable[int | str] = ()) -> GCAMLexicon:
    """Select a lexicon with the requested dictionaries excluded.

    Args:
        disabled: Collection of dictionary names, integer IDs, or numeric strings.

    Returns:
        A reusable selection, or this lexicon if no applicable IDs are excluded.

    Raises:
        TypeError: If selectors have invalid types or form a bare string.
        ValueError: If a dictionary name or ID is unknown.
    """
    present = {dictionary_id(key) for key in self.implemented_dimensions}
    ids = tuple(
        code for code in resolve_dictionaries(disabled, custom_ids=present) if code in present
    )
    if not ids:
        return self
    return self._selection(("dictionaries", *ids), lambda key: dictionary_id(key) not in ids)

for_language

for_language(language: str = 'eng') -> GCAMLexicon

Select dimensions for a supported language code, name, or regional tag.

Source code in src/gdelt_regkg/fields/gcam.py
def for_language(self, language: str = "eng") -> GCAMLexicon:
    """Select dimensions for a supported language code, name, or regional tag."""
    language = normalize_language(language)
    if all(value == language for value in self.languages.values()):
        return self
    return self._selection(("language", language), lambda key: self.languages[key] == language)

from_json classmethod

from_json(path: str | Path) -> GCAMLexicon

Load a compiled GCAM profile from JSON or gzip-compressed JSON.

Source code in src/gdelt_regkg/fields/gcam.py
@classmethod
def from_json(cls, path: str | Path) -> GCAMLexicon:
    """Load a compiled GCAM profile from JSON or gzip-compressed JSON."""
    return _load(read_gcam_json(path))

GCAMResult dataclass

GCAMResult(word_count: int, counts: Mapping[str, int], implemented_dimensions: tuple[str, ...], lexicon_name: str, values: Mapping[str, float] = dict(), native_word_count: int | None = None)

GCAM counts and weighted scores with the profile's supported dimensions.

Attributes:

Name Type Description
word_count int

English input token count.

counts Mapping[str, int]

Count-dimension matches, including supported zero counts.

implemented_dimensions tuple[str, ...]

Keys computed by the selected lexicon.

lexicon_name str

Profile identity.

values Mapping[str, float]

Weighted means for dimensions with matched words.

native_word_count int | None

Original-language token count when native text is supplied.

to_gkg

to_gkg()

Serialize word counts and sparse dimension values in GCAM key order.

Zero counts are omitted. Matched weighted means of zero are retained.

Source code in src/gdelt_regkg/fields/gcam.py
def to_gkg(self):
    """Serialize word counts and sparse dimension values in GCAM key order.

    Zero counts are omitted. Matched weighted means of zero are retained.
    """
    entries = [f"wc:{self.word_count}"]
    if self.native_word_count is not None:
        entries.append(f"nwc:{self.native_word_count}")
    for key in self.implemented_dimensions:
        if key in self.counts and self.counts[key]:
            entries.append(f"{key}:{self.counts[key]}")
        elif key in self.values:
            entries.append(f"{key}:{self.values[key]:.15g}")
    return ",".join(entries)

analyze_gcam

analyze_gcam(text: str, *, lexicon: GCAMLexicon | None = None, disabled_dictionaries: Iterable[int | str] = (), original_text: str | None = None, original_language: str | None = None) -> GCAMResult

Compute dictionary match counts and matched-word weighted means.

Original-language text is scored with dimensions for that language.

Parameters:

Name Type Description Default
text str

Prepared English body.

required
lexicon GCAMLexicon | None

Reusable GCAM profile. Defaults to the configured local profile.

None
disabled_dictionaries Iterable[int | str]

Dictionary names or IDs to exclude before matching.

()
original_text str | None

Optional body before English translation.

None
original_language str | None

Non-English language of original_text; supply both together.

None

Returns:

Type Description
GCAMResult

Counts, weighted means, and supported dimension keys. Unmatched weighted

GCAMResult

means are omitted.

Raises:

Type Description
TypeError

If text, lexicon, or dictionary selectors have invalid types.

ValueError

If dictionary selectors or the original-language inputs are invalid.

ResourceUnavailableError

If the default local profile is unavailable.

Source code in src/gdelt_regkg/fields/gcam.py
def analyze_gcam(
    text: str,
    *,
    lexicon: GCAMLexicon | None = None,
    disabled_dictionaries: Iterable[int | str] = (),
    original_text: str | None = None,
    original_language: str | None = None,
) -> GCAMResult:
    """Compute dictionary match counts and matched-word weighted means.

    Original-language text is scored with dimensions for that language.

    Args:
        text: Prepared English body.
        lexicon: Reusable GCAM profile. Defaults to the configured local profile.
        disabled_dictionaries: Dictionary names or IDs to exclude before matching.
        original_text: Optional body before English translation.
        original_language: Non-English language of `original_text`; supply both together.

    Returns:
        Counts, weighted means, and supported dimension keys. Unmatched weighted
        means are omitted.

    Raises:
        TypeError: If text, lexicon, or dictionary selectors have invalid types.
        ValueError: If dictionary selectors or the original-language inputs are invalid.
        ResourceUnavailableError: If the default local profile is unavailable.
    """
    if (original_text is None) != (original_language is None):
        raise ValueError("Supply original_text and original_language together")
    native_language = (
        normalize_language(original_language) if original_language is not None else None
    )
    if native_language == "eng":
        raise ValueError("Original GCAM text must have a non-English language")
    lexicon = default_gcam_lexicon() if lexicon is None else lexicon
    if not isinstance(lexicon, GCAMLexicon):
        raise TypeError("lexicon must be GCAMLexicon")
    lexicon = lexicon.without_dictionaries(disabled_dictionaries)
    result = _analyze_language(text, lexicon.for_language("eng"), "eng")
    if original_text is None:
        return result
    assert native_language is not None
    native = _analyze_language(
        original_text, lexicon.for_language(native_language), native_language
    )
    return GCAMResult(
        result.word_count,
        MappingProxyType({**result.counts, **native.counts}),
        tuple(sorted((*result.implemented_dimensions, *native.implemented_dimensions), key=_order)),
        result.lexicon_name,
        MappingProxyType({**result.values, **native.values}),
        native.word_count,
    )