---
title: "Ling 120, session 06: collocation"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-02-09 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)
}
```

Disfluencies in language production are often correlated with problems in retrieving and planning the upcoming elements and structures. In this session, we will investigate in one corpus file which part-of-speech (POS) tags are often preceded by the disfluencies (*er* or *erm*). We will do so with the SGML version of the British National Corpus (BNC), but we will reduce the fine-grained POS tags it provides to a more coarse-grained set.

## Step 1: things we need to do

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;
   d. define vectors with the fine-grained and the coarse-grained POS tags;
2. implement the tasks:
   a. process each corpus file:
      i. load it;
      ii. convert it to lower case;
      iii. use regular expressions to find disfluencies with their next POS tag;
      iv. save those somewhere;
   b. do some anal/OCD housekeeping;
   c. from the matches, isolate
      i. the disfluencies;
      ii. the following POS tag;
   d. determine how often each disfluency occurs with with each coarse-grained POS tag;
   e. maybe visualize the result.

## Step 2: functions we will need for that

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`;
   d. define vectors with the fine-grained and the coarse-grained POS tags: `XXX`;
2. implement the tasks:
   a. process each corpus file:
      i. load it: `XXX`;
      ii. use regular expressions to find disfluencies with their next POS tag: `XXX`;
      iii. save those somewhere: `<-`;
   b. do some anal/OCD housekeeping: `XXX` and `XXX`;
   c. from the matches, isolate
      i. the disfluencies: `XXX` or `XXX`;
      ii. the following POS tag: `XXX` or `XXX`;
   d. determine how often each disfluency occurs with with each coarse-grained POS tag: `XXX`
   e. maybe visualize the result: `XXX` and `XXX`.

# Preparation
## Data structures

We first 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 `disfl_and_tags`, each element of which will be a match from some corpus file; thus, this will be a replace this with your answers/code:

```{r collector}
disfl_and_tags <- # replace this with your answers/code
```

Finally, we define a vector `summary tags` for the POS tag substitution: it has the coarse-grained summary tags as the vector elements and the fine-grained BNC tags as their names:

```{r definereplacer}
summary_tags <- setNames(
   c("adj", "adj", "adj", "det", "adv", "adv_part", "adv", "conj", "conj", "conj", "num",
     "det", "det", "det", "exist", "intjec", "noun", "noun", "noun", "other", "other",
     "noun", "other", "num", "pron", "pron", "pron", "pron", "pos", "of", "prep", "punct",
     "punct", "punct", "punct", "inf", "other", "be", "be", "be", "be", "be", "be", "do",
     "do", "do", "do", "do", "do", "have", "have", "have", "have", "have", "have", "modal",
     "lexverb", "lexverb", "lexverb", "lexverb", "lexverb", "lexverb", "not", "other"),
   tolower(c(
      "AJ0", "AJC", "AJS", "AT0", "AV0", "AVP", "AVQ", "CJC", "CJS", "CJT", "CRD", "DPS",
      "DT0", "DTQ", "EX0", "ITJ", "NN0", "NN1", "NN2", "NNN", "NNS", "NP0", "NUL", "ORD",
      "PNI", "PNP", "PNQ", "PNX", "POS", "PRF", "PRP", "PUL", "PUN", "PUQ", "PUR", "TO0",
      "UNC", "VBB", "VBD", "VBG", "VBI", "VBN", "VBZ", "VDB", "VDD", "VDG", "VDI", "VDN",
      "VDZ", "VHB", "VHD", "VHG", "VHI", "VHN", "VHZ", "VM0", "VVB", "VVD", "VVG", "VVI",
      "VVN", "VVZ", "XX0", "ZZ0")))
head(summary_tags, 15)
```

## Regex development

The BNC with its SGML annotation looks like this:

```{r bncsgmlexample}
noquote(current_corpus_file <- tolower(c(
   "<s n=\"7\"><w PNP>I <w VM0>could<w XX0>n't <w UNC>erm <w VVI>fight <w DPS>my <w NN1>way <w PRP>out of <w AT0>a <w NN1>paper <w NN1>bag <w AV0>now <unclear><c PUN>.",
   "<s n=\"8\"><w CJC>But <w UNC>erm <pause> <w CJS>unless <w PNP>he <w VVZ>alters <w DPS>his <w NN1>way <w PNP>you <w VVB>know <w PNP>I <w VM0>can <w VVI>see <w PNP>it <w VVG>coming <w AVP>off<c PUN>.",
   "<s n=\"9\"><w AV0>Anyway <w EX0>there<w VBZ>'s <w DT0>more <w NN1>football <w VVG>coming <w DPS>your <w NN1>way <w PRP>on <w AJ0>Central <w PRP>in <w NN1>midweek<c PUN>.")))
```

How could we process this? We look for

* a word tag containing an 'unclear' tag; followed by
* *er* or *erm*, followed by
* stuff till the text word tag (which is most likely just a space); followed by
* the beginning of a word tag up to and including its, say, first 3 characters:

```{r regex1}
# replace this with your answers/code
```

This is not that complex but we'll still look at this with free-spacing:

```{r regex1freespacg}
# replace this with your answers/code
```

Note that this search might be too permissive because 'stuff' may include material that we may *not* want to skip over in our search for the next POS tag (e.g., annotation like <pause>, which indicates an unfilled disfluency after the filled disfluency we're already retrieving (see sentence 8 above for an example). This is how we could adjust the regex accordingly but we're sticking with the above for now:

```{r regex2freespacg}
#| eval: false
# replace this with your answers/code
```

# Processing
## The loop: loading, searching, interim saving

Then, we loop over each file name and

* load each file path in `corpus_files` (w/ `XXX`);
* change the words to lower case (w/ `XXX`);
* retrieve the disfluencies plus the next POS tag from the corpus file (w/ `XXX`);
* add those matches to all the ones we collected before;
* print a progress report.

As before, we will also gather two useful bits of information, namely

* measure the time it takes to do that with `system.time({...})`;
* compute the size of the collector `disfl_and_tags` at the end.

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}
system.time({

# replace this with your answers/code

}) # how fast is this?
object.size(disfl_and_tags)
```

## 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
```

## Isolate disfluencies & POS tags

From `disfl_and_tags`, we retrieve the disfluencies, which we put into a vector called `all_disfl`:

```{r disfl1}
all_disfl <- # replace this with your answers/code
```

You could also use `XXX` to get the disfluencies:

```{r disfl2}
#| eval: false
all_disfl <- # replace this with your answers/code
```

From `disfl_and_tags`, we retrieve the POS tags of the following words, which we put into a vector called `all_tags_after_disfl`.

```{r tag1}
# replace this with your answers/code
```

You could also use `XXX` to get the tags (if we didn't allow for portmanteau tags):

```{r tag2}
#| eval: false
# replace this with your answers/code
```

## Replace with coarse-grained tags

Now we have the fine-grained tags in `all_tags_after_disfl`, but we want to simplify them to the coarse grained tags -- remember `summary_tags` and create a vector `sum_tags_after_disfluencies` that contains for each of the (fine-grained) POS tags the corresponding coarse-grained POS tag:

```{r replaceWsumtags1}
head(summary_tags, 15)
sum_tags_after_disfl <- # replace this with your answers/code
```

But, if you want to make things more complicated, you could of course use `XXX`:

```{r replaceWsumtags2}
#| echo: false
# replace this with your answers/code
```

## Cross-tabulation and quantification

We cross-tabulate the disfluencies with those coarse-grained POS tags into an object called `result`:

```{r}
result <- # replace this with your answers/code
```

To now determine which POS tag is most attracted to which disfluency, we can again use the *KLD*. We could make the prior the overall distribution of the two disfluencies:

```{r prior}
prior <- # replace this with your answers/code
```

And the posteriors are the frequency distributions of each part of speech with the two disfluencies:

```{r posteriors}
posteriors <- # replace this with your answers/code
```

Thus, we can do the exact same thing as last session for dispersion (with one small add-on in a moment):

```{r KLDs1}
KLD_values <- # replace this with your answers/code
```

But one problem remains -- what is it? XXX

 do we address it? XXX

```{r KLDs2}
# replace this with your answers/code
```

## Visualization

How about a plot that reflects both

* the frequency of each tag with both disfluencies;
* the preferential behavior of each tag with regard to the disfluencies?

```{r plot}
# replace this with your answers/code
```

# Session info

```{r sessionInfo}
sessionInfo()
```
