---
title: "Ling 120, session 08: working w/ bigrams"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-02-23 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)
}
```

Much psycholinguistic work has been concerned with bigrams, either because esp. in English things that might look like two words (after splitting up a corpus or in general) might really just be, or be treated as, one lexical unit (e.g., *according to*, *because of*, etc.) or because bigrams have been used to compute surprisal values, i.e. how surprising the second part of a bigram is after you have seen/heard the first. In this session, we will perform two tasks:

* we'll generate bigrams that do not cross sentences or turns (using the [BNC SGML](http://www.natcorp.ox.ac.uk/docs/URG.xml?ID=cdifbase) as input);
* we'll compute the above-mentioned kind of surprisal value of each second part of a bigram.

**Surprisal** will be computed here as follows, i.e. as the negative binary log of the conditional probability of seeing word~2~ when you just saw word~1~:

$$surprisal=-log_2 p(b|a) = -log_2 \frac{p(ab)}{p(a)} = -log_2 \frac{freq_{ab}}{freq_a}$$

This can easily be illustrated on the basis of a table like @tbl-surprisal, from which the surprisal of *ab* can be computed as 0.2:

|                      | word~2~ = *b*    | word~2~ != *b*   | Sum    |
|:---------------------|:-----------------|:-----------------|:-------|
| **word~1~ = *a***    | 2                | 8                | 10     |
| **word~1~ &ne; *a*** | 3                | 99987            | 99990  |
| **Sum**              | 5                | 99995            | 100000 |

: Hypothetical 2x2-table to compute surprisal {#tbl-surprisal}

Let me remind you what the corpus looks like, and let's imagine we want all bigrams involving words, punctuation marks, but sentence boundary positions (so we will get *the* at the beginning of a sentence or a comma after *however*:

```{r bncsgmlexample}
noquote(current_corpus_file <- tolower(c(
   "<s n=\"25\"><w PNP>you <w VM0>can <w AV0>sort of <w VVI>bluff <w DPS>your <w NN1>way <w PRP-AVP>through <w PRP>to <w AT0>a <w AJ0>certain <w NN1>extent<c PUN>.",
   "<s n=\"26\"><ptr target=XX1LC0TY><w PNP>I<w VBB>'m <w VVG>working <w DPS>my <ptr target=XX1LC0U0><w NN1>way <pause> <w AV0>slowly <w CJC>but <w AV0>surely",
   "<s n=\"27\"><w PNP>You <w VHB>have <w TO0>to <w VVI>lose <w DPS>your <w NN1>way<c PUN>, <w VVB>come <w AVP>back<c PUN>, <ptr target=XX1LC0W5><w ITJ>yeah<c PUN>. <ptr target=XX1LC0W6></u>")))
```

## Step 1: things we need to do (only for task 1)

We need to

1. prepare (for) the tasks:
   a. (maybe) clear memory;
   b. set up / define the corpus files;
   c. (maybe) define one or more collector structures;
2. implement tasks in a loop:
   a. load each corpus file;
   b. do something with the sentence number tags (as boundary markers);
   c. find the words
   d. convert things to lower case;
   e. save them somewhere
3. do some anal/OCD housekeeping;
4. create bigrams from unigrams.

## Step 2: functions we will need for that (only for task 1)

The above tasks require the following functions:

1. prepare (for) the tasks:
   a. (maybe) clear memory: `XXX`;
   b. set up / define the corpus files: `XXX` and `XXX`;
   c. (maybe) define one or more collector structures: `XXX` or `XXX`;
2. implement tasks in a loop:
   a. load each corpus file: `XXX`;
   b. change the sentence number tags into 'words' (as boundary markers): `gsub`;
   c. find the words: `XXX`;
   d. convert things to lower case: `XXX`;
   e. save them somewhere: `c` and `XXX`;
3. do some anal/OCD housekeeping: `XXX` and `XXX` and `XXX`;
4. create bigrams from unigrams (with a loop?).

# Preparation

We first define which corpus we want to use, unzip the corresponding corpus files, and put all the file paths into a vector `corpusfiles`.

```{r prepfiles}
# replace this with your answers/code
```

We then create a collector data structure `unigrams`, each element of which will represent a word from the corpus:

```{r collector}
unigrams <- # replace this with your answers/code
```

# Processing
## Computing bigrams

Now we do a `for`-loop like before, but this time of course with some additional steps: We loop over each file name and

* load each file (`XXX`);
* make sentence-number tags look like words (so we can treat them as 'boundary words' in the bigrams): `XXX`;
* find all words (based on the tags): `XXX`;
* replace the tag to retain only the words: `XXX`;
* change all words to lower case: `XXX`;
* add those matches to all the ones we collected before: `XXX`;
* print a progress report: `XXX`.

As always, 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 `unigrams` at the end (with `object.size`).

```{r mainprocessing}
system.time({
for(i in seq(corpus_files)) { # access each corpus file
   # we read in each corpus file
   # replace this with your answers/code

   # we make the sentence number tags look like word tags
   # replace this with your answers/code

   # we find the matches ...
   # replace this with your answers/code

   # ... and save them
   # replace this with your answers/code
}
}) # how fast is this?
object.size(unigrams)
length(unigrams)
```

Now we need to combine each word with the next -- how do we do that? A first idea might be some kind of loop ...

```{r bigramsbad}
system.time({ # measure the time of everything that follows
bigrams <- character(length=length(unigrams)-1) # create a collector vector

# replace this with your answers/code

}) # how fast is this?
# check result
unigrams %>% head(42)
bigrams %>% head(42)
```

But this is **R**: we should not want to loop: R is much faster/better when things are vectorized and/or use `apply` functions! Thus, we ...

```{r bigramsbetter}
system.time({ # measure the time of everything that follows

# replace this with your answers/code

}) # how fast is this?
# check result
unigrams %>% head(42)
bigrams %>% head(42)
```

Worked well and is around 14 times as fast. (This is example #2 of why I often hate it when people complain about 'how slow R is'.)

### Excursus

If you're already finished, think about how one might generate such n-grams more generally, i.e. how one could adjust the code chunk `bigramsbetter` such that it can handle even longer *n*-grams without annoying repetitions of code. Try and develop this for `qwe` below and with a numeric vector `the_n_in_ngrams` that defines the *n* in *n*-grams. Use a loop if you feel like you have to (Cooper's code from above would do this really fast/well), but for learning about R and its elegance, you might also get inspired by looking at `?mapply` ...

```{r ngramsbetter}
qwe <- unigrams[1:15]
the_n_in_ngrams <- 3
# replace this with your answers/code
```

And to really learn stuff, make that a function `ngram_builder` that takes two arguments:

* a character vector `cv` that would contain the unigrams;
* a numeric vector `gram_length` that defines the *n* in *n*-grams (and is by default set to 2).

and then use that function to compute all trigrams for all our data:

```{r ngram_builder}
# 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 everything but data structures contains "grams":

```{r housekeeping}
# replace this with your answers/code
```

## Computing surprisals

Now on to the surprisal values. We still have `unigrams` and `bigrams` stored so let's now compute for each bigram the surprisal of the second word given the first word. How do we proceed? Here's the dumbest, slowest, 'brute-forcest' example of how *not* to do it (in R!), which does everything sub-optimally:

```{r surprisalsAWFUL}
#| eval: false
surprisals <- c()
system.time({ # measure the time of everything that follows
for (curr_bigram in unique(bigrams)) { # for each bigram type
    surprisals <- c( # make surprisals the combination of
       surprisals,   # what was in there from before, followed by
       -log2("/"(    # the negative binary log of this fraction:
          sum(bigrams==curr_bigram),                                 # numerator
          sum(unigrams==sub(         # replace                       # denominator
             "_.*$", "",             # everything after _ by nothing
             curr_bigram, perl=TRUE) # in curr_bigram using PCRE
   )))) # end of sum, "/", log2, c
} # end of for
}) # stop timing: approx. 1140 seconds, puke
```

This does *everything* wrong:

* replace this with your answers/code;
* replace this with your answers/code;
* replace this with your answers/code.

As a result, this is indeed insanely slow -- because we made all the choices one shouldn't make in R.

So, how should this really be done in R? First, replace this with your answers/code! Second, replace this with your answers/code.

```{r freqsOFgrams}
unigram_freqs <- # replace this with your answers/code
bigram_freqs  <- # replace this with your answers/code
```

And then we find for each bigram type what the type of its first word is (and check what we're doing):

```{r firstwordsinbigramtypes}
first_words_in_bigram_types <- # replace this with your answers/code
tail(bigram_freqs)                # check results
tail(first_words_in_bigram_types) # check results
```

So now we can compute the surprisals. I'm doing it in 2 steps here just for didactic reasons (so we can see the three ^1^/~3~s for *zoo*):

```{r surprisals}
tail(surprisals <- # replace this with your answers/code
tail(surprisals <- # replace this with your answers/code
```

How much faster is this? This easy way of doing it takes &approx;0.7 seconds, which means it's faster by a factor of &approx;1650 (This is example #2 of why I often hate it when people complain about 'how slow R is'.)

```{r timeitall}
# replace this with your answers/code
surprisals[grep("^knowledge", names(surprisals))] %>% sort
```

Now let's plot this just for the fun of it:

```{r plot}
# replace this with your answers/code
```

Also, it might be interesting to determine for a variety of bigram frequency ranges what the least surprising bigrams are:

```{r leastsurpr}
# replace this with your answers/code
```

What if we only want to see bigrams that consist of words, i.e. none with punctuation marks or sentence boundaries?

```{r leastsurpr_onlywords}
# replace this with your answers/code
```

# Session info

```{r}
sessionInfo()
```
