---
title: "Ling 120, session 05: dispersion"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-02-02 12:34:56"
date-format: "DD MMM YYYY HH-mm-ss"
editor: source
format:
   html:
      page-layout: full
      code-fold: true
      code-link: true
      code-copy: true
      code-tools: true
      code-line-numbers: true
      code-overflow: scroll
      number-sections: true
      smooth-scroll: true
      toc: true
      toc-depth: 4
      number-depth: 4
      toc-location: left
      mainfont: Times New Roman
      monofont: Lucida Console
      tbl-cap-location: top
      fig-cap-location: bottom
      fig-width: 6
      fig-height: 6
      fig-format: png
      fig-dpi: 300
      fig-align: center
      embed-resources: true
      include-in-header:
         text: '<link rel="shortcut icon" href="https://www.stgries.info/favicon.ico" type="image/x-icon" />'
execute:
   cache: false
   echo: true
   eval: true
   warning: false
---

# Introduction

We first clear memory, load `magrittr`, and define `just.matches`:

```{r prepworkspace}
rm(list=ls(all=TRUE)); library(magrittr)
just.matches <- function (search.expr, corpus.v, perl=TRUE, vectorize=TRUE, ...) {
   output <- regmatches(corpus.v, gregexpr(search.expr, corpus.v, perl=perl, ...))
   if (vectorize) { output <- unlist(output) }; return(output)
}
```

In this script, we will compute dispersion values for all words in a corpus. Measures of dispersion are probabilistically related to frequency but quantify the evenness/clumpiness/burstiness with which a word is distributed in a corpus. Here we will compute a measure of dispersion for a handful of words in the International Corpus of English -- the British Component (ICE-GB), namely the so-called **Kullback-Leibler divergence**. To compute the *KLD*, you need the following information:

* for each corpus part, its relative size: $prior/expected~Q=\frac{corpus~part~size~in~words}{overall~corpus~size~in~words}$;
* for each corpus part, the relative frequency of the word in it: $posterior/observed~P=\frac{freq~of~word~in~part}{freq~of~word~in~corpus}$.

With that, the *KLD* is computed like this:

$$KLD(P||Q) = D_{KL} (P||Q) = \sum_{i=1}^{n} P_i \times log_2 \frac{P_i}{Q_i} \mathrm{~(with~}log_2\mathrm{~}0:=0)$$

For example, if you have a corpus such that

* the three corpus parts *A*, *B*, and *C* have the following sizes: 4000, 3000, and 3000 words;
* the corpus parts contain the word in question 1, 2, and 3 times respectively,

then:

* $prior/expected_A=\frac{4000}{10000}=0.4$, $expected_B=\frac{3000}{10000}=0.3$, $expected_C=\frac{3000}{10000}=0.3$,
* $posterior/observed_A=\frac{1}{6}=0.1667$, $observed_B=\frac{2}{6}=0.333$, and $observed_C=\frac{3}{6}=0.5$.

In R:

```{r priorposterior}
corpus_part_sizes <- # replace this with your answers/code
prior <- # replace this with your answers/code
posterior <- # replace this with your answers/code
```

The *KLD* is then computed as follows:

```{r KLDdef}
(KLD_raw <- sum(posterior * log2(posterior/prior)))
```

(Note that this can become problematic when, for instance, the posterior contains 0s because then the log won't work unproblematically. In practice, one often sets log(0) to 0 or just discards the `-Inf`/`NaN` summands that result from log(0).) *KLD*-values fall into the range of [0, +&infin;]:

* values closer to 0 mean that a word is very evenly distributed in a corpus (i.e. very much as one would expect from the corpus part sizes);
* higher values mean that a word is very unevenly distributed in a corpus (i.e. often clumped into a very small number of corpus parts).

To normalize the value range of the *KLD* somewhat, we could apply a transformation to it, e.g. the **odds-to-probabilities transformation** (which you might know from logistic regression modeling contexts):

```{r KLDnormdef1}
#| code-fold: false
KLD_raw / (1+KLD_raw)
```

By the way: it can be useful to know that operators (such as `/`, `+`, `-`, `*`, and others) can be written as functions because (i) this can help with function writing and (ii) it sometimes allows us to use a more human reader-friendly order of functions and arguments:

```{r KLDnormdef2}
"/"( # divide
   KLD_raw,   # the raw KLD by
   KLD_raw+1) # (the raw KLD + 1)
```

## Step 1: things we need to do

If we want to determine the dispersion of several words in a corpus, We need to

1. define the words of interest and a collector for their results;
2. for each corpus (file), we
   a. load it;
   b. homogenize upper-/lower-case spelling;
   c. extract the words from each corpus file and store 'some such information' somehow/somewhere;
3. from that somehow/somewhere we compute the size of each file;
4. for each word of interest, we retrieve their frequencies in files and compute the *KLD* for them.

## Step 2: functions we will need for that

The above tasks require the following functions:

1. define the words of interest: `XXX`; define a collector `KLD_values` for their results: `XXX`;
2. for each corpus file: `XXX` or some file-choosing function to define the corpus files and then a `for`-loop where we
    a. load it: `XXX`;
    b. convert it to lower case `XXX`;
    c. extract the words from each corpus file: `XXX` or `XXX`/`XXX` or `XXX` or `XXX`;
    d. somehow store the words somewhere: `<-`;
3. from that somehow/somewhere we compute `expected`, i.e. the size of each file: `XXX`;
4. for each word of interest (with a `for`-loop)
   a. we compute `observed` by retrieving its frequencies in all files from the somehow/somewhere: `[...]`;
   b. we compute the *KLD*: math functions.

That means, before we enter

* the 1st `for`-loop, we need a collector that will collect the corpus;
* the 2nd `for`-loop, we need a collector that will collect the *KLD*-values.

# Preparation
## Data structures

We define the words of interest and a collector structure for their *KLD*-values:

```{r defstructures}
words_of_interest <- c(
   "the", "on", "with", "of", "for", "at", "forward", "pigmeat", "ozzie", "accidie")
KLD_values <- # replace this with your answers/code
```

Then we define which corpus we want to use, unzip the corresponding corpus files, and put all the file paths into a vector `corpus_files`:

```{r prepfiles}
# replace this with your answers/code
```

We then create a collector data structure `word_freqs_in_files`, each element of which will represent a file from the corpus and contain the frequency table of that file; thus, this will be a list:

```{r collector}
word_freqs_in_files <- # replace this with your answers/code
```

## Regex development

As in the previous script, we need to identify all the words in each file of the British Component of the International Corpus of English ([ICE-GB] (https://www.ucl.ac.uk/english-usage/projects/ice-gb/)). As a reminder, that corpus looks like this:

```{r icegbexample}
noquote(current_corpus_file <- tolower(c(
   "DISMK,FRM {OK}",
   " NPHD,N(prop,sing) {Adam}",
   "DISMK,INTERJEC {uhm}",
   "PAUSE,PAUSE(short) {<,>}",
   " NPHD,PRON(inter) {what}",
   "INTOP,AUX(do,past) {did}",
   "  NPHD,PRON(pers) {you}",
   " MVB,V(cxtr,infin) {see}",
   "  P,PREP(ge) {as}",
   "  MVB,V(intr,ingp) {missing}")))
```

We will extract the words in the same way as before: things that follow a `{` but are not `}`:

```{r extractwords}
current_words <- # replace this with your answers/code
```

# Processing
## The loop: loading, searching, interim saving

We now use a `for`-loop to

* load each file path in `corpus_files` (w/ `XXX`);
* change the words to lower case (w/ `XXX`);
* retrieve the words from the corpus file (w/ `XXX`);
* insert the frequency table of the words from the current corpus file into the right slot of the collector list `XXX`;
* print a progress report (w/ `XXX`).

As before, we will also gather two useful bits of information, namely

* the time it takes to do that with `system.time({...})`;
* the size of the collector `word_freqs_in_files` at the end (with `object.size`).

This adds virtually nothing to the processing costs or the script, but is a useful habit to get into for when scripts require optimization.

```{r mainprocessing}
# replace this with your answers/code
```

## House-keeping

Some house-keeping: we

* delete the unzipped corpus files (while of course retaining the zip archive);
* remove from the workspace all 'temporary files' from the loop:

```{r housekeeping}
# replace this with your answers/code
```

## Computing the 'expected proportions'

```{r prior}
# replace this with your answers/code
```

## Computing the observed proportions & *KLD*

For every word of interest, we now need its frequency in every file. So we do a `for`-loop that, for each word of interest, retrieves those by using `sapply` and the subsetting function `[` to retrieve its frequency from the frequency table of each file; since the absence of a word will return `NA`, we then change the `NA`s returned to 0. Once we have all the frequencies (including the 0s) for a word of interest, we compute the *KLD* for the word (using `expected` for each) and store it in the collector vector:

```{r posteriors2KLD}
# replace this with your answers/code
```

Now, if one uses the logic of the above script to compute the *KLD*-value of every single word type in the corpus -- `words_of_interest <- sort(unique(unlist(sapply(word_freqs_in_files, names))))` returns `r length(sort(unique(unlist(sapply(word_freqs_in_files, names)))))` types -- the above loop takes several minutes on a pretty fast AMD Ryzen with 64GB of fast RAM.

# How would one *really* do this?

Memory permitting, one would actually do this in a more R-y way. One would first create a term-document matrix `tdm`. For that we need two data structures:

* `words`: one data structure with all the words in the corpus:
* `files`: another data structure stating for each word token which file it was observed in:

```{r tdmstep1}
words <- # replace this with your answers/code
files <- # replace this with your answers/code
```

Then we can create a term-document matrix, first one of observed frequencies, then the proportions we actually need:

```{r tdmstep2}
tdm_abs <- # replace this with your answers/code
tdm_rel <- # replace this with your answers/code
tdm_rel[53400:53409, 1:4] # check result
```

But how big is that thing?!

```{r tdmsize}
object.size(tdm_rel)
```

So how long does computing `KLD_values` take now?!

```{r tdmtiming}
# replace this with your answers/code
```

What a trade-off: using a representation of the data that is 10.2 as great as the smallest we could do, we could speed up processing by a factor of several hundreds ... (This is example #1 of why I often hate it when people complain about 'how slow R is'.)

Let's visualize this:

```{r dispVSfreq}
# replace this with your answers/code
```

Or, with the words:

```{r dispVSfreqwords}
# replace this with your answers/code
```

Let's zoom in a bit into the most frequent words and their dispersions:

```{r dispVSfreqzoom}
# replace this with your answers/code
```

But what potential problem of our measure does this point to? # replace this with your answers/code

# How would one *really really* do this?

With much much bigger term-document matrices or if this needs to be done dozens or hundreds of times (e.g., for bootstrapping), outsourcing things into C++ can help (meaning, this won't work on your computer); as you can see, this saves a moment on converting `tdm_abs` into `tdm_rel` and is then another &approx;7.5times as fast.

# Session info

```{r sessionInfo}
sessionInfo()
```
