Wednesday, April 30, 2014

Finding Temporality of Sentences with TempoWordNet


In my previous post, I described a Scala implementation of the Negex algorithm, that was initially developed to detect negation of phrases in a sentence using manually built pre- and post- trigger terms. Later on, it was found that the same algorithm could be used to also detect temporality and experiencer characteristics of a phrase in a sentence, using a different set of pre- and post- trigger terms.

I also recently became aware of the TempoWordNet project from a group at Normandie University. The project provides a free lexical resource that contains each synset of Wordnet marked up with its probability of being past, present, future or atemporal. This paper describes the process by which these probabilities were generated. There is another paper which one of the authors referenced on LinkedIn, but its unfortunately behind an ACM paywall, and I am no longer a member starting this year, so could not read it.

In running the Negex algorithm against the annotated list that comes with it, I found that the Historical and Hypothetical annotations had lower accuracies (0.90 and 0.89 respectively) compared to the other two (Negation and Experiencer). Thinking about it, I realized that the Historical and Hypothetical annotators are a pair of binary annotators used to annotate a phrase into one of 3 classes - Historical, Recent and Not Particular. With this understanding, some small changes in how I measured the accuracy brought them up to 0.93 and 0.99 respectively. But I figured that may be possible to also compute temporality using the TempoWordNet file, similar to how one does classical sentiment analysis. This post describes that work.

Each synset in the TempoWordNet file is written as a triple of word, part of speech and synset ID. From this, I build a LingPipe ExactDictionaryChunker for each word/POS pair for each temporality state. I check to see that I only capture the first synset ID for the word/POS combination, so hopefully I capture the probabilities for the most dominant synset (the first one). I have written earlier about the LingPipe ExactDictionaryChunker, it implements the Aho-Corasick string matching algorithm which is very fast and space efficient.

Each sentence is tokenized into words and POS tagged (using OpenNLP's POS tagger. Each word/POS combination is matched against each of the ExactDictionaryChunkers and the probability of matching word for each tense summed across all words. The class for which the sum of probabilities of individual words is the highest is the class of the sentence. Since OpenNLP uses the Penn Treebank tags, they need to be translated to Wordnet tags before matching.

Here is the code for the TemporalAnnotator.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Source: src/main/scala/com/mycompany/scalcium/transformers/TemporalAnnotator.scala
package com.mycompany.scalcium.transformers

import java.io.File
import java.util.regex.Pattern

import scala.Array.canBuildFrom
import scala.collection.JavaConversions.asScalaIterator
import scala.collection.mutable.ArrayBuffer
import scala.io.Source

import com.aliasi.chunk.Chunker
import com.aliasi.dict.DictionaryEntry
import com.aliasi.dict.ExactDictionaryChunker
import com.aliasi.dict.MapDictionary
import com.aliasi.tokenizer.IndoEuropeanTokenizerFactory
import com.mycompany.scalcium.utils.Tokenizer

class TemporalAnnotator(val tempoWNFile: File) {

  val targets = List("Past", "Present", "Future")
  val chunkers = buildChunkers(tempoWNFile)
  val tokenizer = Tokenizer.getTokenizer("opennlp")
  
  val ptPoss = List("JJ", "NN", "VB", "RB")
    .map(p => Pattern.compile(p + ".*"))
  val wnPoss = List("s", "n", "v", "r")
  
  def predict(sentence: String): String = {
    val scoreTargetPairs = chunkers.map(chunker => {
      val taggedSentence = tokenizer.posTag(sentence)
        .map(wtp => wtp._1.replaceAll("\\p{Punct}", "") + 
          "/" + wordnetPos(wtp._2))
        .mkString(" ")
      val chunking = chunker.chunk(taggedSentence)
      chunking.chunkSet().iterator().toList
        .map(chunk => chunk.score())
        .foldLeft(0.0D)(_ + _)
      })
      .zipWithIndex
      .filter(stp => stp._1 > 0.0D)
    if (scoreTargetPairs.isEmpty) "Present"
    else {
      val bestTarget = scoreTargetPairs
        .sortWith((a,b) => a._1 > b._1)
        .head._2
      targets(bestTarget)
    }
  } 
  
  def buildChunkers(datafile: File): List[Chunker] = {
    val dicts = ArrayBuffer[MapDictionary[String]]()
    Range(0, targets.size).foreach(i => 
      dicts += new MapDictionary[String]())
    val pwps = scala.collection.mutable.Set[String]()
    Source.fromFile(datafile).getLines()
      .filter(line => (!(line.isEmpty() || line.startsWith("#"))))
      .foreach(line => {
        val cols = line.split("\\s{2,}")
        val wordPos = getWordPos(cols(1))
        val probs = cols.slice(cols.size - 4, cols.size)
          .map(x => x.toDouble)
        if (! pwps.contains(wordPos)) {
          Range(0, targets.size).foreach(i => 
            dicts(i).addEntry(new DictionaryEntry[String](
              wordPos, targets(i), probs(i))))
        }
        pwps += wordPos
    })
    val chunkers = new ArrayBuffer[Chunker]()
    dicts.map(dict => new ExactDictionaryChunker(
        dict, IndoEuropeanTokenizerFactory.INSTANCE, 
        false, false))
      .toList
  }
  
  def getWordPos(synset: String): String = {
    val sscols = synset.split("\\.")
    val words = sscols.slice(0, sscols.size - 2)
    val pos = sscols.slice(sscols.size - 2, sscols.size - 1).head
    words.mkString("")
      .split("_")
      .map(word => word + "/" + (if ("s".equals(pos)) "a" else pos))
      .mkString(" ")
  }  
  
  def wordnetPos(ptPos: String): String = {
    val matchIdx = ptPoss.map(p => p.matcher(ptPos).matches())
      .zipWithIndex
      .filter(mip => mip._1)
      .map(mip => mip._2)
    if (matchIdx.isEmpty) "o" else wnPoss(matchIdx.head)
  }
}

As you can see, I just compute the best of Past, Present and Future and ignore the Atemporal probabilities. I had initially included it as well, but accuracy scores on the Negex annotated test data was coming out at 0.89. Changing the logic to only look at Past and flag it as Historical if the sum of past probabilities of matching sentences was greater than 0 got me an even worse accuracy of 0.5. Finally, after a bit of trial and error, removing the Atemporal chunker resulted in an accuracy of 0.904741, so thats what I stayed with.

Here is the JUnit test for evaluating the TemporalWordnetAnnotator using the annotated list of sentences from Negex. Our default is "Recent", and only when we can confidently say something about the temporality of the sentence, we will change to either "Historical" or "Recent". Our annotators will return a score for each of Past, Present and Future. If the result is "Past" from our annotators, it will be converted to "Historical" for comparison.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Source: src/test/scala/com/mycompany/scalcium/transformers/TemporalAnnotatorTest.scala
package com.mycompany.scalcium.transformers

import java.io.File

import scala.io.Source

import org.junit.Test

class TemporalAnnotatorTest {

  val tann = new TemporalAnnotator(
    new File("src/main/resources/TempoWnL_1.0.txt"))
  val input = new File("src/main/resources/negex/test_input.txt")
  
  @Test
  def evaluate(): Unit = {
    var numTested = 0
    var numCorrect = 0
    Source.fromFile(input).getLines().foreach(line => {
      val cols = line.split("\t")
      val sentence = cols(3)
      val actual = cols(5)
      if ((! "Not particular".equals(actual))) {
        val predicted = tann.predict(sentence)
        val correct = actual.equals(translate(predicted))
        if (! correct) {
          Console.println("%s|[%s] %s|%s"
            .format(sentence, (if (correct) "+" else "-"), 
              actual, predicted))
        }
        numCorrect += (if (correct) 1 else 0)
        numTested += 1
      }
    })
    Console.println("Accuracy=%8.6f"
      .format(numCorrect.toDouble / numTested.toDouble))
  }
  
  /**
   * Converts predictions made by TemporalAnnotator to
   * predictions that match annotations in our testcase.
   */
  def translate(pred: String): String = {
    pred match {
      case "Past" => "Historical"
      case _ => "Recent"
    }
  }
}

This approach gives us an accuracy of 0.904741, which is not as good as Negex, but its lack of accuracy is somewhat offset by its ease of use. You can send the entire sentence to the annotator, no need (as in the case of Negex) to concept map the sentence before sending so it identifies the "important" phrases.

Saturday, April 26, 2014

Scala implementation of the Negex Algorithm


I first learned about a (baseline) approach to detecting and dealing with negation in text in the Coursera NLP class taught by Stanford profs Jurafsky and Manning. Essentially it involves ignoring everything in a sentence after certain "negation" words are seen. For example, a naive annotator simply looking for word matches could legitimately conclude that a patient is a smoker based on a doctor's note that says "Patient does not smoke". Using the simple negation rule would ignore everything after the negation keyword "not".

While this is an improvement over not doing it at all, natural language has nuances that are not captured by this simple rule. The Negex algorithm is a bit more complicated, but does a better job of indicating if a clinical condition should be negated in text. It uses around 281 phrases that indicate negation, further classified as CONJ (joins two phrases together), PSEU (Pseudo trigger terms), PREN (Pre-negative trigger terms), POST (Post negative trigger terms), PREP and POSP (Pre and post categories similar to PREN and POST but for a less strict matching mode). The algorithm is described by its authors here.

I started looking at it hoping that I could use it as a library, but the code in the repository looks more like examples that clients could use as inspiration for their own implementations. In fact, Hitex uses a GATE CREOLE resource that wraps the Negex algorithm. Apache cTakes, the other clinical pipeline I am studying, uses a more complex rule based approach using FSMs.

One of the nice things about the Negex algorithm is that it can be generalized (using different sets of trigger terms) to predict whether a condition refers to a historical or current event, a hypothetical or recent event, or if it refers to the patient or someone else. So implementing the algorithm yields benefits greater than just beefing up your negation detection logic. In fact, the ConText project, a spin-off from Negex, does just that (although its code repository seems to contain the same example code that the Negex project contains).

I initially tried reading the original paper on ConText: ConText: An Algorithm for Identifying Contextual Features from Clinical Text, in an attempt to figure out what the algorithm did, but the paper is pretty high level and covers a lot of ground, so I fell back to reading the Java code in the genConText sudirectory of the Negex source code. Unfortunately, Java is not really a good language for describing algorithms because of its verbosity, so I turned to the Python code in the negex.python subdirectory instead, which was far easier to read and understand.

My implementation does not faithfully implement the Negex algorithm description, but it ends up with an identical accuracy achieved on the same data set by the Python reference implementation. Specifically, my algorithm only looks for PREN and POST rules (and optionally PREP and POSP if non-strict mode is selected), but does not use PSEU (Pseudo negation) terms at all. The original algorithm prescribes finding all keywords in the sentence, then discarding any leading PSEU terms, then computing all the negation scopes in the sentence, and finally selecting and working on the negation scope that includes our target phrase. My implementation finds the location of the phrase first, then finds PREN and POST (and optionally PREP and POSP) around it and calculates negation based on the distance between the phrase and trigger term. It also checks for CONJ to split up the sentence (only working on the split containing the target phrase). Here is my code for the Negex algorithm.

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Source: src/main/scala/com/mycompany/scalcium/transformers/NegexAnnotator.scala
package com.mycompany.scalcium.transformers

import java.io.File
import java.util.regex.Pattern

import scala.Array.canBuildFrom
import scala.io.Source

case class Offset(val start: Int, val end: Int) {
  def isNone = start == -1 && end == -1
  def None = Offset(-1,-1)
}

class NegexAnnotator(ruleFile: File, 
    responses: List[String]) {

  val rules = sortRules(ruleFile)
  
  /**
   * Predicts sense of the phrase in the sentence
   * as one of the responses based on whether the
   * negTagger method returns true or false.
   * @param sentence the sentence.
   * @param phrase the phrase.
   * @nonStrict true if non-strict mode.
   * @return a response (passed into constructor).
   */
  def predict(sentence: String, phrase: String, 
      nonStrict: Boolean): String = 
    if (negTagger(sentence, phrase, nonStrict)) 
      responses(0)
    else responses(1)

  /**
   * Parses trigger rules file and converts them
   * to a List of (trigger pattern, rule type) pairs
   * sorted by descending order of length of 
   * original trigger string. This method is called
   * on construction (should not be called from 
   * client code).
   * @param the trigger rules File.
   * @return List of (trigger pattern, rule type)
   *       sorted by trigger string length.
   */
  def sortRules(ruleFile: File): List[(Pattern,String)] = {
    Source.fromFile(ruleFile)
      .getLines()
      // input format: trigger phrase\t\t[TYPE]
      .map(line => {
        val cols = line.split("\t\t")
        (cols(0), cols(1))
      })
      .toList
      // sort by length descending
      .sortWith((a,b) => a._1.length > b._1.length)
      // replace spaces by \\s+ and convert to pattern
      .map(pair => (
        Pattern.compile("\\b(" + pair._1
          .trim()
          .replaceAll("\\s+", "\\\\s+") + ")\\b"), 
            pair._2))
  }
  
  /**
   * This is the heart of the algorithm. It normalizes
   * the incoming sentence, then finds the character
   * offset (start,end) for the phrase. If a CONJ
   * trigger is found, it only considers the part of
   * the sentence where the phrase was found. It 
   * looks at the PREN, POST, PREP and POSP (the
   * last 2 if tagPossible=true) looking for trigger
   * terms within 5 words of the phrase.
   * @param sentence the sentence (unnormalized).
   * @param phrase the phrase (unnormalized)
   * @param tagPossible true if non-strict mode
   *        annotation required.
   */
  def negTagger(sentence: String, phrase: String, 
      tagPossible: Boolean): Boolean = {
    val normSent = sentence.toLowerCase()
      .replaceAll("\\s+", " ")
    val wordPositions = 0 :: normSent.toCharArray()
      .zipWithIndex
      .filter(ci => ci._1 == ' ')
      .map(ci => ci._2 + 1)
      .toList
    // tag the phrase
    val phrasePattern = Pattern.compile(
      "\\b(" + 
      phrase.replaceAll("\\s+", "\\\\s+") + 
      ")\\b", Pattern.CASE_INSENSITIVE)
    val phraseOffset = offset(normSent, phrasePattern)
    if (phraseOffset.isNone) return false
    // look for CONJ trigger terms
    val conjOffsets = offsets(normSent, "[CONJ]", rules)
    if (conjOffsets.isEmpty) {
      // run through the different rule sets, 
      // terminating when we find a match
      val triggerTypes = if (tagPossible) 
        List("[PREN]", "[POST]", "[PREP]", "[POSP]")
      else List("[PREN]", "[POST]")
      isTriggerInScope(normSent, rules, 
        phraseOffset, wordPositions, triggerTypes)      
    } else {
      // chop off the side of the sentence where
      // the phrase does not appear.
      val conjOffset = conjOffsets.head
      if (conjOffset.end < phraseOffset.start) {
        val truncSent = normSent.substring(conjOffset.end + 1)
        negTagger(truncSent, phrase, tagPossible)
      } else if (phraseOffset.end < conjOffset.start) {
        val truncSent = normSent.substring(0, conjOffset.start)
        negTagger(truncSent, phrase, tagPossible)
      } else {
        false
      }
    }
  }
  
  /**
   * Returns true if the trigger term is within the
   * context of the phrase, ie, within 5 words of
   * each other. Recursively checks each rule type
   * in the triggerTypes in list.
   * @param sentence the normalized sentence.
   * @param rules the sorted list of rules.
   * @param phraseOffset the phrase offset.
   * @param wordPositions the positions of the
   *        starting character position of each
   *        word in the normalized sentence.
   * @param triggerTypes the trigger types to
   *        check.
   * @return true if trigger is in the context of
   *        the phrase, false if not.
   */
  def isTriggerInScope(
      sentence: String,
      rules: List[(Pattern,String)],
      phraseOffset: Offset,
      wordPositions: List[Int],
      triggerTypes: List[String]): Boolean = {
    if (triggerTypes.isEmpty) false
    else {
      val currentTriggerType = triggerTypes.head
      val triggerOffsets = offsets(sentence, 
        currentTriggerType, rules)
      val selectedTriggerOffset = firstNonOverlappingOffset(
        phraseOffset, triggerOffsets)
      if (selectedTriggerOffset.isNone)
        // try with the next trigger pattern
        isTriggerInScope(sentence, rules, 
          phraseOffset, wordPositions,
          triggerTypes.tail)
      else {
        // check how far the tokens are. If PRE*
        // token, then there is no distance limit
        // but 5 words is the distance limit for 
        // POS* rules.
        if (currentTriggerType.startsWith("[PRE"))
          selectedTriggerOffset.start < 
            phraseOffset.start
        else
          wordDistance(phraseOffset, 
            selectedTriggerOffset, 
            wordPositions) <= 5 &&
            phraseOffset.start < 
            selectedTriggerOffset.start
      }
    }
  }
  
  /**
   * Returns the distance in number of words
   * between the phrase and trigger term.
   * @param phraseOffset (start,end) for phrase.
   * @param triggerOffset (start,end) for trigger.
   * @param wordPositions a list of starting
   *        character positions for each word
   *        in (normalized) sentence.
   * @return number words between phrase and trigger.
   */
  def wordDistance(phraseOffset: Offset, 
      triggerOffset: Offset,
      wordPositions: List[Int]): Int = {
    if (phraseOffset.start < triggerOffset.start)
      wordPositions
        .filter(pos => pos > phraseOffset.end && 
          pos < triggerOffset.start)
        .size
    else
      wordPositions
        .filter(pos => pos > triggerOffset.end && 
          pos < phraseOffset.start)
        .size
  }
  
  /**
   * Compute the character offset of the phrase
   * in the (normalized) sentence. If there is 
   * no match, then an Offset(-1,-1) is returned.
   * @param sentence the normalized sentence.
   * @param pattern the phras 
   */
  def offset(sentence: String, 
      pattern: Pattern): Offset = {
    val matcher = pattern.matcher(sentence)
    if (matcher.find()) 
      Offset(matcher.start(), matcher.end())
    else Offset(-1, -1)      
  }
  
  /**
   * Find all offsets for trigger terms for the
   * specified rule type. Returns a list of offsets
   * for trigger terms that matched.
   * @param sentence the normalized sentence.
   * @param ruleType the rule type to filter on.
   * @param rules the list of sorted rule patterns.
   * @return a List of Offsets for matched triggers
   *        of the specified rule type.
   */
  def offsets(sentence: String, ruleType: String,
      rules: List[(Pattern,String)]): List[Offset] = {
    rules.filter(rule => ruleType.equals(rule._2))
      .map(rule => offset(sentence, rule._1))
      .filter(offset => (! offset.isNone))
  }
  
  /**
   * Returns the first trigger term that does not
   * overlap with the phrase. May return (-1,-1).
   * @param phraseOffset the offset for the phrase.
   * @param triggerOffsets a list of Offsets for the
   *        triggers.
   * @return the first non-overlapping offset.
   */
  def firstNonOverlappingOffset(phraseOffset: Offset, 
      triggerOffsets: List[Offset]): Offset = {
    val phraseRange = Range(phraseOffset.start, phraseOffset.end)
    val nonOverlaps = triggerOffsets
      .filter(offset => {
        val offsetRange = Range(offset.start, offset.end)  
        phraseRange.intersect(offsetRange).size == 0
      })
    if (nonOverlaps.isEmpty) Offset(-1,-1) 
    else nonOverlaps.head
  }
}

The code is heavily documented, hopefully its easy to understand. The rules are read in from a file (I used the files provided in the genConText subdirectory of the Negex repository), longest rule first. The incoming sentence and phrases are normalized and the location of the phrase determined (start and end character positions). We first attempt to find occurrences of CONJ trigger terms. If found, we split the sentence, working only on the portion that contains our phrase. Next we try to match trigger terms of type PREN, POST, PREP and POSP (the last two if non-strict matching is turned on). If we find one, we calculate the distance (in words) from the phrase to the trigger term. For PREN (and PREP) there is no distance limit, for POST (and POSP) the maximum allowed distance is 5 words.

As I mentioned earlier, we can reuse the same code with different rule files - negex_triggers.txt for Negation, history_triggers.txt and hypothetical_triggers.txt for Temporality, and experiencer_triggers.txt for Experiencer. Here is some JUnit code that instantiates different types of annotators and evaluates them using test data (also from Negex).

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Source: src/test/scala/com/mycompany/scalcium/transformers/NegexAnnotatorTest.scala
package com.mycompany.scalcium.transformers

import java.io.File

import scala.io.Source

import org.junit.Test

class NegexAnnotatorTest {

  val dir = new File("src/main/resources/negex")
  val input = new File(dir, "test_input.txt")
  
  @Test
  def detailReport(): Unit = {
    val negAnnotator = new NegexAnnotator(
      new File(dir, "negex_triggers.txt"),
      List("Negated", "Affirmed"))
    val histAnnotator = new NegexAnnotator(
      new File(dir, "history_triggers.txt"),
      List("Historical", "Recent"))
    val hypAnnotator = new NegexAnnotator(
      new File(dir, "hypothetical_triggers.txt"),
      List("Not particular", "Recent"))
    val expAnnotator = new NegexAnnotator(
      new File(dir, "experiencer_triggers.txt"),
      List("Other", "Patient"))
    var numTested = 0
    var numCorrectNeg = 0
    var numCorrectHist = 0
    var numCorrectHyp = 0
    var numCorrectExp = 0
    Source.fromFile(input)
        .getLines()
        .foreach(line => {
      val cols = line.split("\t")
      val phrase = cols(2)
      val sentence = cols(3)
      val negActual = cols(4)
      val histActual = cols(5)
      val hypActual = cols(5)
      val expActual = cols(6)
      val negPred = negAnnotator.predict(sentence, phrase, false)
      val negCorrect = negActual.equals(negPred)
      val histPred = histAnnotator.predict(sentence, phrase, false)
      val histCorrect = histActual.equals(histPred) 
      val hypPred = hypAnnotator.predict(sentence, phrase, false)
      val hypCorrect = hypActual.equals(hypPred)
      val expPred = expAnnotator.predict(sentence, phrase, false)
      val expCorrect = expActual.equals(expPred)
      numCorrectNeg += (if (negCorrect) 1 else 0)
      numCorrectHist += (if (histCorrect) 1 else 0)
      numCorrectHyp += (if (hypCorrect)1 else 0)
      numCorrectExp += (if (expCorrect) 1 else 0)
      numTested += 1
      Console.println("%s\t%s\t[%s] %s\t[%s] %s\t[%s] %s\t[%s] %s"
        .format(phrase, sentence, 
          if (negCorrect) "+" else "-", negActual,
          if (histCorrect) "+" else "-", histActual,
          if (hypCorrect) "+" else "-", hypActual,
          if (expCorrect) "+" else "-", expActual))
    })
    Console.println()
    Console.println("Accuracy Scores")
    Console.println("Accuracy (Negation) = %8.6f"
      .format(numCorrectNeg.toDouble / numTested.toDouble))
    Console.println("Accuracy (Historical) = %8.6f"
      .format(numCorrectHist.toDouble / numTested.toDouble))
    Console.println("Accuracy (Hypothetical) = %8.6f"
      .format(numCorrectHyp.toDouble / numTested.toDouble))
    Console.println("Accuracy (Experiencer) = %8.6f"
      .format(numCorrectExp.toDouble / numTested.toDouble))
  }
}

The first 20 lines of output from the above JUnit test (post-processed manually to make it suitable for HTML display) is shown below. The green responses indicate that my NegexAnnotator got it right (the actual text indicates the expected response), and red imply that it got it wrong.

PhraseSentenceNegationHistoricalHypotheticalExperiencer
lungs were decreased at the bilateral basesThe LUNGS WERE DECREASED AT THE BILATERAL BASES.AffirmedRecentRecentPatient
coughShe denies any COUGH or sputum production.NegatedRecentRecentPatient
right ventricular pressure or volume overload04) Flattened interventricular septum, consistent with RIGHT VENTRICULAR PRESSURE OR VOLUME OVERLOAD.AffirmedRecentRecentPatient
aortic valve is normalThe AORTIC VALVE IS NORMAL.AffirmedRecentRecentPatient
wheezesNo WHEEZES, rales, or rhonchi.NegatedRecentRecentPatient
Normal left ventricular size and functionFINAL IMPRESSIONS: 01) NORMAL LEFT VENTRICULAR SIZE AND FUNCTION.AffirmedRecentRecentPatient
gastric varicesThere was no evidence of GASTRIC VARICES, ulcers, or Mallory-Weiss tear.NegatedRecentRecentPatient
atypical follicular lymphomaThe most likely possibilities include marginal cell lymphoma vs. an ATYPICAL FOLLICULAR LYMPHOMA.AffirmedRecentRecentPatient
hemodynamically stableThe patient remained HEMODYNAMICALLY STABLE with the heart rate in 70s.AffirmedRecentRecentPatient
ALLERGIES: CODEINEALLERGIES: CODEINE.AffirmedRecentRecentPatient
pulmonic regurgitationThere is trace PULMONIC REGURGITATION.AffirmedRecentRecentPatient
Colitis in the sigmoid colonCOMPLICATIONS: None POSTOPERATIVE DIAGNOSIS(ES): 1) COLITIS IN THE SIGMOID COLON 2) No additional lesions PLAN: 1) Await biopsy results REPEAT EXAM: Colonoscopy in 10 year(s).AffirmedRecentRecentPatient
ANEMIAANEMIA.AffirmedRecentRecentPatient
Thickened aortic valve with mild regurgitation03) THICKENED AORTIC VALVE WITH MILD REGURGITATION.AffirmedRecentRecentPatient
interatrial baffle07) There is an echodensity seen in the atria consistent with the patient''s know INTERATRIAL BAFFLE.AffirmedHistoricalHistoricalPatient
bowel distentionS_O_H Counters Report Type Record Type Subgroup Classifier 13,MFZKSI+l8xGn DS DS 5004 E_O_H [Report de-identified (Safe-harbor compliant) by De-ID v.6.14.02] **INSTITUTION GENERAL MEDICINE DISCHARGE SUMMARY PATIENT NAME: **NAME[AAA, BBB M] ACCOUNT #: **ID-NUM **ROOM ATTENDING PHYSICIAN: **NAME[ZZZ M YYY] ADMISSION DATE: **DATE[Sep 19 2007] DISCHARGE DATE: **DATE[Sep 27 2007] The patient is a **AGE[in 40s]-year-old with past medical history of partial small bowel obstruction, who is admitted quite frequently for abdominal pain, BOWEL DISTENTION, and partial small bowel obstructions.AffirmedHistoricalHistoricalPatient
B12 deficiencyShe does have B12 DEFICIENCY and she is getting vitamin B12 shots every month.AffirmedRecentRecentPatient
unusual headachesShe will alert the physician if any of the following are noted: Nosebleeds, excessive bruising, pink, red, or tea-colored urine, bright red or tarry black stools, UNUSUAL HEADACHES, or stomach pain.AffirmedNot particularNot particularPatient
mitral regurgitationSPECTRAL DOPPLER: There is trace MITRAL REGURGITATION.AffirmedRecentRecentPatient
rib fractureThere is a 1cm area of linear fibrosis in the left lower lobe on image 45 of series 4 which may be related to an adjacent old RIB FRACTURE.AffirmedHistoricalHistoricalPatient

The accuracy scores for the different annotators are shown below. The test data consists of 2,376 phrase/sentence combinations, annotated with the expected value for Negation, Historical/Hypothetical and Experiencer. As you can see, the accuracy for the Negation and Experiencer annotators are quite high, and Historical/Hypothetical isn't too bad either.

1
2
3
4
Accuracy (Negation) = 0.978956
Accuracy (Historical) = 0.909091
Accuracy (Hypothetical) = 0.889731
Accuracy (Experiencer) = 0.997475

Thats all I have for today. Negex seems to be a useful algorithm to know. I liked that the same algorithm could be used to include/exclude clinical concepts based on temporality and experiencer as well, a bit like a Swiss army knife.

Friday, April 11, 2014

NLTK-like Wordnet Interface in Scala


I recently figured out how to setup the Java WordNet Library (JWNL) for something I needed to do at work. Prior to this, I have been largely unsuccessful at figuring out how to access Wordnet from Java, unless you count my one attempt to use the Java Wordnet Interface (JWI) described here. I think there are two main reason for this. First, I just didn't try hard enough, since I could get by before this without having to hook up Wordnet from Java. The second reason was the over-supply of libraries (JWNL, JWI, RiTa, JAWS, WS4j, etc), each of which annoyingly stops short of being full-featured in one or more significant ways.

The one Wordnet interface that I know that doesn't suffer from missing features comes with the Natural Language ToolKit (NLTK) library (written in Python). I have used it in the past to access Wordnet for data pre-processing tasks. In this particular case, I needed to call it at runtime from within a Java application, so I finally bit the bullet and chose a library to integrate into my application - I chose JWNL based on seeing it being mentioned in the Taming Text book (and used in the code samples). I also used code snippets from Daniel Shiffman's Wordnet page to learn about the JWNL API.


After I had successfully integrated JWNL, I figured it would be cool (and useful) if I could build an interface (in Scala) that looked like the NLTK Wordnet interface. Plus, this would also teach me how to use JWNL beyond the basic stuff I needed for my webapp. My list of functions were driven by the examples from the Wordnet section (2.5) from the NLTK book and the examples from the NLTK Wordnet Howto. My Scala class implements most of the functions mentioned on these two pages. The following session will give you an idea of the coverage - even though it looks a Python interactive session, it was generated by my JUnit test. I do render the Synset and Word (Lemma) objects using custom format() methods to preserve the illusion (and to make the output readable), but if you look carefully, you will notice the rendering of List() is Scala's and not Python's.

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
>>> wn.synsets('motorcar')
List(car.n.01)

>>> wn.synset('car.n.01').lemma_names
List(car, auto, automobile, machine, motorcar)
>>> sorted([lemma.name for synset
...    in types_of_motorcar for lemma in synset.lemmas])
List(Model_T, Stanley_Steamer, ambulance, beach_wagon, bus, \
  cab, compact, convertible, coupe, cruiser, electric, gas_guzzler, \
  hardtop, hatchback, horseless_carriage, hot_rod, jeep, limousine, \
  loaner, minicar, minivan, pace_car, racer, roadster, sedan, \
  sport_utility, sports_car, stock_car, subcompact, touring_car, used-car)

>>> wn.synset('car.n.01').definition
a motor vehicle with four wheels; usually propelled by an internal \
  combustion engine

>>> wn.synset('car.n.01').examples
List("he needs a car to get to work")

>>> wn.synset('car.n.01').lemmas
List(car.n.01.car, car.n.02.auto, car.n.03.automobile, \
  car.n.04.machine, car.n.05.motorcar)

>>> wn.lemma('car.n.01.automobile').name
automobile

>>> for synset in wn.synsets('car'):
...     print synset.lemma_names
...
[car, auto, automobile, machine, motorcar]
[car, railcar, railway_car, railroad_car]
[car, gondola]
[car, elevator_car]
[cable_car, car]

>>> wn.lemmas('car')
List(car.n.01.car, car.n.01.car, car.n.01.car, car.n.01.car, \
  cable_car.n.02.car)

>>> motorcar = wn.synset('car.n.01')
>>> types_of_motorcar = motorcar.hyponyms()
>>> types_of_motorcar
List(ambulance.n.01, beach_wagon.n.01, bus.n.01, cab.n.01, \
  compact.n.01, convertible.n.01, coupe.n.01, cruiser.n.01, \
  electric.n.01, gas_guzzler.n.01, hardtop.n.01, hatchback.n.01, \
  horseless_carriage.n.01, hot_rod.n.01, jeep.n.01, limousine.n.01, \
  loaner.n.01, minicar.n.01, minivan.n.01, Model_T.n.01, pace_car.n.01, \
  racer.n.01, roadster.n.01, sedan.n.01, sports_car.n.01, \
  sport_utility.n.01, Stanley_Steamer.n.01, stock_car.n.01, \
  subcompact.n.01, touring_car.n.01, used-car.n.01)
>>> types_of_motorcar[0]
ambulance.n.01

>> motorcar.hypernyms()
List(motor_vehicle.n.01)

>>> paths = motorcar.hypernym_paths()
>>> len(paths)
2
>>> [synset.name for synset in paths[0]]
List(car.n.01, motor_vehicle.n.01, self-propelled_vehicle.n.01, \
  wheeled_vehicle.n.01, vehicle.n.01, conveyance.n.01, \
  instrumentality.n.01, artifact.n.01, whole.n.01, object.n.01, \
  physical_entity.n.01, entity.n.01)
>>> [synset.name for synset in paths[1]]
List(car.n.01, motor_vehicle.n.01, self-propelled_vehicle.n.01, \
  wheeled_vehicle.n.01, container.n.01, instrumentality.n.01, \
  artifact.n.01, whole.n.01, object.n.01, physical_entity.n.01, \
  entity.n.01)

>>> motorcar.root_hypernyms()
List(entity.n.01)

>>> wn.synset('tree.n.01').part_meronyms()
List(stump.n.01, crown.n.01, limb.n.01, trunk.n.01, burl.n.01)
>>> wn.synset('tree.n.01').substance_meronyms()
List(sapwood.n.01, heartwood.n.01)
>>> wn.synset('tree.n.01').member_holonyms()
List(forest.n.01)

>>> for synset in wn.synsets('mint', wn.NOUN):
...     print synset.name + ':', synset.definition
...
batch.n.01: (often followed by `of') a large number or amount or extent
mint.n.01: any north temperate plant of the genus Mentha with aromatic \
  leaves and small mauve flowers
mint.n.01: any member of the mint family of plants
mint.n.01: the leaves of a mint plant used fresh or candied
mint.n.01: a candy that is flavored with a mint oil
mint.n.01: a plant where money is coined by authority of the government
>>> wn.synset('mint.n.04').part_holonyms()
List(mint.n.01)
>>> [x.definition for x
...    in wn.synset('mint.n.04').part_holonyms()]
List(any north temperate plant of the genus Mentha with aromatic leaves \
  and small mauve flowers)
>>> wn.synset('mint.n.04').substance_holonyms()
List(mint.n.01)
>>> [x.definition for x
...    in wn.synset('mint.n.04').substance_holonyms()]
List(a candy that is flavored with a mint oil)

>>> wn.synset('walk.v.01').entailments()
List(step.v.01)
>>> wn.synset('eat.v.01').entailments()
List(chew.v.01, swallow.v.01)
>>> wn.synset('tease.v.03').entailments()
List(arouse.v.01, disappoint.v.01)

>>> wn.lemma('supply.n.02.supply').antonyms()
List(demand.n.01.demand)
>>> wn.lemma('rush.v.01.rush').antonyms()
List(linger.v.01.linger)
>>> wn.lemma('horizontal.a.01.horizontal').antonyms()
List(vertical.a.01.vertical, inclined.a.01.inclined)
>>> wn.lemma('staccato.r.01.staccato').antonyms()
List(legato.r.01.legato)

>>> right = wn.synset('right_whale.n.01')
>>> orca = wn.synset('orca.n.01')
>>> minke = wn.synset('minke_whale.n.01')
>>> tortoise = wn.synset('tortoise.n.01')
>>> novel = wn.synset('novel.n.01')
>>> right.lowest_common_hypernyms(minke)
List(baleen_whale.n.01)
>>> right.lowest_common_hypernyms(orca)
List(whale.n.01)
>>> right.lowest_common_hypernyms(tortoise)
List(vertebrate.n.01)
>>> right.lowest_common_hypernyms(novel)
List(entity.n.01)

>>> wn.synset('baleen_whale.n.01').min_depth()
14
>>> wn.synset('whale.n.02').min_depth()
13
>>> wn.synset('vertebrate.n.01').min_depth()
8
>>> wn.synset('entity.n.01').min_depth()
0

>>> right.path_similarity(minke)
0.25
>>> right.path_similarity(orca)
0.16666666666666666
>>> right.path_similarity(tortoise)
0.07692307692307693
>>> right.path_similarity(novel)
0.043478260869565216

>>> dog = wn.synset('dog.n.01')
>>> cat = wn.synset('cat.n.01')
>>> hit = wn.synset('hit.v.01')
>>> slap = wn.synset('slap.v.01')
>>> dog.path_similarity(cat)
0.2
>>> hit.path_similarity(slap)
0.14285714285714285
>>> dog.lch_similarity(cat)
2.0794415416798357
>>> hit.lch_similarity(slap)
1.3862943611198906
>>> dog.wup_similarity(cat)
0.8666666666666667
>>> hit.wup_similarity(slap)
0.25
>>> dog.res_similarity(cat)
7.2549003421277245
>>> hit.res_similarity(slap)
>>> dog.jcn_similarity(cat)
0.537382154955756
>>> dog.lin_similarity(cat)
0.8863288628086228

>>> for synset in list(wn.all_synsets('n'))[:10]:
...     print(synset)
...
'hood.n.01
The_Hague.n.01
twenty-two.n.01
zero.n.01
one.n.01
lauryl_alcohol.n.01
one-hitter.n.01
ten.n.01
hundred.n.01
thousand.n.01

>>> print(wn.morphy('denied', wn.VERB))
deny
>>> print(wn.morphy('dogs'))
dog
>>> print(wn.morphy('churches'))
church
>>> print(wn.morphy('aardwolves'))
aardwolf
>>> print(wn.morphy('abaci'))
abacus
>>> print(wn.morphy('book', wn.NOUN))
book
>>> wn.morphy('hardrock', wn.ADV)

>>> wn.morphy('book', wn.ADJ)

>>> wn.morphy('his', wn.NOUN)

Under the hood, my interface uses the Wordnet Similarity for Java (WS4j) for the similarity implementations (which JWNL doesn't contain) and JWNL for everything else. The various Similarity measures are described in this paper (PDF) by the authors of the Perl module Wordnet::Similarity, upon which WS4j is based.

Before you can start, you need to download Wordnet (of course). You can skip the installation process unless you also want to access Wordnet functionality directly from your operating system. I installed my Wordnet dictionary under /opt/wordnet-3.0.

Next, you will need to download JWNL. You should download the JWNL source because your client will need an XML configuration file that comes with the source download. Find the file config/file_properties.xml and change the value of the param@value attribute where param@name == "dictionary_path". The value should be the path to your Wordnet dict directory - in my case it is /opt/wordnet-3.0/dict. You also need to update the jwnl_properties/version@number from 2.0 to 3.0 otherwise you will get errors during starting up your code. This file should go somewhere on your classpath - my build tool is sbt (same for mvn), so I put it into src/main/resources/wnconfig.xml.

The JWNL source distribution also contains the JWNL JAR file, so I put this into the lib (unmanaged) subdirectory. I could also have gotten it from Maven Central.

Next, I downloaded the WS4j JAR. This JAR needs to be unmanaged because its not available in Maven Central, so it goes into the lib subdirectory of my project. You need to get the JAR (rather than build from source) because it packages several classes (from the JAWJAW project) that are not included in the source. However, the source was useful for me because it showed me how I could convert from JWNL Synsets to WS4j Concept objects and call the various Similarity measures.

Here is the code for my NLTK-like Wordnet interface. As you can see, it differs from the NLTK version in that it does not support fluent interfaces. So for example, you cannot call wn.synset('car.n.01').definition(). Instead you must call wn.definition(wn.synset("car", POS.NOUN, 1)). This is because JWNL implements its own Synset and Word (analogous to NLTK's Lemma) classes. Supporting the fluent interfaces would have meant subclassing these classes, which would have made the code a bit confusing, so I didn't do it.

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Source: src/main/scala/com/mycompany/scalcium/utils/Wordnet.scala
package com.mycompany.scalcium.utils

import java.io.File
import java.io.FileInputStream

import scala.Array.canBuildFrom
import scala.collection.JavaConversions.asScalaBuffer
import scala.collection.JavaConversions.asScalaIterator
import scala.collection.TraversableOnce.flattenTraversableOnce
import scala.collection.mutable.ArrayBuffer

import edu.cmu.lti.jawjaw.util.WordNetUtil
import edu.cmu.lti.lexical_db.NictWordNet
import edu.cmu.lti.lexical_db.data.Concept
import edu.cmu.lti.ws4j.RelatednessCalculator
import edu.cmu.lti.ws4j.impl.JiangConrath
import edu.cmu.lti.ws4j.impl.LeacockChodorow
import edu.cmu.lti.ws4j.impl.Lesk
import edu.cmu.lti.ws4j.impl.Lin
import edu.cmu.lti.ws4j.impl.Path
import edu.cmu.lti.ws4j.impl.Resnik
import edu.cmu.lti.ws4j.impl.WuPalmer

import net.didion.jwnl.JWNL
import net.didion.jwnl.data.IndexWord
import net.didion.jwnl.data.POS
import net.didion.jwnl.data.PointerType
import net.didion.jwnl.data.PointerUtils
import net.didion.jwnl.data.Synset
import net.didion.jwnl.data.Word
import net.didion.jwnl.data.list.PointerTargetNode
import net.didion.jwnl.data.list.PointerTargetNodeList
import net.didion.jwnl.dictionary.Dictionary

class Wordnet(val wnConfig: File) {

  JWNL.initialize(new FileInputStream(wnConfig))
  val dict = Dictionary.getInstance()

  val lexdb = new NictWordNet()
  val Path_Similarity = new Path(lexdb)
  val LCH_Similarity = new LeacockChodorow(lexdb)
  val WUP_Similarity = new WuPalmer(lexdb)
  val RES_Similarity = new Resnik(lexdb)
  val JCN_Similarity = new JiangConrath(lexdb)
  val LIN_Similarity = new Lin(lexdb)
  val Lesk_Similarity = new Lesk(lexdb)
 
  def allSynsets(pos: POS): Stream[Synset] = 
    dict.getIndexWordIterator(pos)
      .map(iword => iword.asInstanceOf[IndexWord])
      .map(iword => iword.getSenses())
      .flatten
      .toStream
  
  def synsets(lemma: String): List[Synset] = {
    POS.getAllPOS()
      .map(pos => pos.asInstanceOf[POS])  
      .map(pos => synsets(lemma, pos))
      .flatten
      .toList
  }
  
  def synsets(lemma: String, pos: POS): List[Synset] = {
    val iword = dict.getIndexWord(pos, lemma)
    if (iword == null) List.empty[Synset]
    else iword.getSenses().toList
  }
  
  def synset(lemma: String, pos: POS, 
      sid: Int): Option[Synset] = {
    val iword = dict.getIndexWord(pos, lemma)
    if (iword != null) Some(iword.getSense(sid)) 
    else None
  }

  def lemmas(s: String): List[Word] = {
    synsets(s)
      .map(ss => lemmas(Some(ss)))
      .flatten
      .filter(w => w.getLemma().equals(s))
  }

  def lemmas(oss: Option[Synset]): List[Word] = {
    oss match {
      case Some(ss) => ss.getWords().toList
      case _ => List.empty[Word]
    }
  }
  
  def lemma(oss: Option[Synset], wid: Int): Option[Word] = {
    oss match {
      case Some(x) => Option(lemmas(oss)(wid))
      case None => None
    }
  }
  
  def lemma(oss: Option[Synset], lem: String): Option[Word] = {
    oss match {
      case Some(ss) => {
        val words = ss.getWords()
          .filter(w => lem.equals(w.getLemma()))
        if (words.size > 0) Some(words.head)
        else None
      }
      case None => None
    }
  }
  
  ////////////////// similarities /////////////////////
  
  def pathSimilarity(loss: Option[Synset], 
      ross: Option[Synset]): Double = 
    getPathSimilarity(loss, ross, Path_Similarity)
    
  def lchSimilarity(loss: Option[Synset],
      ross: Option[Synset]): Double =
    getPathSimilarity(loss, ross, LCH_Similarity)
  
  def wupSimilarity(loss: Option[Synset], 
      ross: Option[Synset]): Double = 
    getPathSimilarity(loss, ross, WUP_Similarity)
    
  // WS4j Information Content Finder (ICFinder) uses
  // SEMCOR, Resnik, JCN and Lin similarities are with
  // the SEMCOR corpus.
  def resSimilarity(loss: Option[Synset], 
      ross: Option[Synset]): Double =
    getPathSimilarity(loss, ross, RES_Similarity)
    
  def jcnSimilarity(loss: Option[Synset], 
      ross: Option[Synset]): Double = 
    getPathSimilarity(loss, ross, JCN_Similarity)
    
  def linSimilarity(loss: Option[Synset], 
      ross: Option[Synset]): Double =
    getPathSimilarity(loss, ross, LIN_Similarity)
  
  def leskSimilarity(loss: Option[Synset], 
      ross: Option[Synset]): Double = 
    getPathSimilarity(loss, ross, Lesk_Similarity)
    
  def getPathSimilarity(loss: Option[Synset],
      ross: Option[Synset],
      sim: RelatednessCalculator): Double = {
 val lconcept = getWS4jConcept(loss)
 val rconcept = getWS4jConcept(ross)
 if (lconcept == null || rconcept == null) 0.0D
 else sim.calcRelatednessOfSynset(lconcept, rconcept)
      .getScore()
  }
  
  def getWS4jConcept(oss: Option[Synset]): Concept = {
    oss match {
      case Some(ss) => {
        val pos = edu.cmu.lti.jawjaw.pobj.POS.valueOf(
          ss.getPOS().getKey())
        val synset = WordNetUtil.wordToSynsets(
          ss.getWord(0).getLemma(), pos)
          .head
        new Concept(synset.getSynset(), pos)
      }
      case _ => null
    }
  } 
  
  ////////////////// Morphy ///////////////////////////
  
  def morphy(s: String, pos: POS): String = {
    val bf = dict.getMorphologicalProcessor()
      .lookupBaseForm(pos, s)
    if (bf == null) "" else bf.getLemma()
  }
  
  def morphy(s: String): String = {
    val bases = POS.getAllPOS().map(pos =>
      morphy(s, pos.asInstanceOf[POS]))
    .filter(str => (! str.isEmpty()))
    .toSet
    if (bases.isEmpty) "" else bases.toList.head
  }
  
  ////////////////// Synset ///////////////////////////
  
  def lemmaNames(oss: Option[Synset]): List[String] = {
    oss match {
      case Some(ss) => ss.getWords()
        .map(word => word.getLemma())
        .toList
      case _ => List.empty[String]
    }
  }
  
  def definition(oss: Option[Synset]): String = {
    oss match {
      case Some(ss) => {
        ss.getGloss()
          .split(";")
          .filter(s => !isQuoted(s.trim))
          .mkString(";")
      }
      case _ => ""
    }
  }
  
  def examples(oss: Option[Synset]): List[String] = {
    oss match {
      case Some(ss) => {
        ss.getGloss()
          .split(";")
          .filter(s => isQuoted(s.trim))
          .map(s => s.trim())
          .toList
      }
      case _ => List.empty[String]
    }
  }
  
  def hyponyms(oss: Option[Synset]): List[Synset] =
    relatedSynsets(oss, PointerType.HYPONYM)

  def hypernyms(oss: Option[Synset]): List[Synset] = 
    relatedSynsets(oss, PointerType.HYPERNYM)
  
  def partMeronyms(oss: Option[Synset]): List[Synset] = 
    relatedSynsets(oss, PointerType.PART_MERONYM)
  
  def partHolonyms(oss: Option[Synset]): List[Synset] =
    relatedSynsets(oss, PointerType.PART_HOLONYM)
    
  def substanceMeronyms(oss: Option[Synset]): List[Synset] = 
    relatedSynsets(oss, PointerType.SUBSTANCE_MERONYM)
  
  def substanceHolonyms(oss: Option[Synset]): List[Synset] =
    relatedSynsets(oss, PointerType.SUBSTANCE_HOLONYM)
    
  def memberHolonyms(oss: Option[Synset]): List[Synset] = 
    relatedSynsets(oss, PointerType.MEMBER_HOLONYM)

  def entailments(oss: Option[Synset]): List[Synset] = 
    relatedSynsets(oss, PointerType.ENTAILMENT)
  
  def entailedBy(oss: Option[Synset]): List[Synset] = 
    relatedSynsets(oss, PointerType.ENTAILED_BY)

  def relatedSynsets(oss: Option[Synset], 
      ptr: PointerType): List[Synset] = {
    oss match {
      case Some(ss) => ss.getPointers(ptr)
        .map(ptr => ptr.getTarget().asInstanceOf[Synset])
        .toList
      case _ => List.empty[Synset]
    }
  }

  def hypernymPaths(oss: Option[Synset]): List[List[Synset]] = {
    oss match {
      case Some(ss) => PointerUtils.getInstance()
        .getHypernymTree(ss)
        .toList
        .map(x => x.asInstanceOf[PointerTargetNodeList])
        .map(ptnl => ptnl
          .map(x => x.asInstanceOf[PointerTargetNode])
          .map(ptn => ptn.getSynset())
          .toList)
        .toList
      case _ => List.empty[List[Synset]]
    }
  }
  
  def rootHypernyms(oss: Option[Synset]): List[Synset] = {
    hypernymPaths(oss)
      .map(hp => hp.reverse.head)
      .toSet
      .toList
  }
  
  def lowestCommonHypernym(loss: Option[Synset], 
      ross: Option[Synset]): List[Synset] = {
    val lpaths = hypernymPaths(loss)
    val rpaths = hypernymPaths(ross)
    val pairs = for (lpath <- lpaths; rpath <- rpaths) 
      yield (lpath, rpath)
    val lchs = ArrayBuffer[(Synset,Int)]()
    pairs.map(pair => {
      val lset = Set(pair._1).flatten
      val matched = pair._2
        .zipWithIndex
        .filter(si => lset.contains(si._1))
      if (! matched.isEmpty) lchs += matched.head
    })
    val lchss = lchs.sortWith((a, b) => a._2 < b._2)
      .map(lc => lc._1)  
      .toList
    if (lchss.isEmpty) List.empty[Synset] 
    else List(lchss.head)
  }
  
  def minDepth(oss: Option[Synset]): Int = {
    val lens = hypernymPaths(oss)
      .map(path => path.size)
      .sortWith((a,b) => a > b)
    if (lens.isEmpty) -1 else (lens.head - 1)
  }
  
  def format(ss: Synset): String = {
    List(ss.getWord(0).getLemma(), 
      ss.getPOS().getKey(),
      (ss.getWord(0).getIndex() + 1).formatted("%02d"))
      .mkString(".")
  }

  /////////////////// Words / Lemmas ////////////////////

  def antonyms(ow: Option[Word]): List[Word] = 
    relatedLemmas(ow, PointerType.ANTONYM)
  
  def relatedLemmas(ow: Option[Word], 
      ptr: PointerType): List[Word] = {
    ow match {
      case Some(w) => w.getPointers(ptr)
        .map(ptr => ptr.getTarget().asInstanceOf[Word])
        .toList
      case _ => List.empty[Word]
    }
  }
  
  def format(w : Word): String = {
    List(w.getSynset().getWord(0).getLemma(), 
      w.getPOS().getKey(),
      (w.getIndex() + 1).formatted("%02d"),
      w.getLemma())
      .mkString(".")
  }

  ////////////////// misc ////////////////////////////////
  
  def isQuoted(s: String): Boolean = {
    if (s.isEmpty()) false
    else (s.charAt(0) == '"' && 
      s.charAt(s.length() - 1) == '"')
  }
}

There are some other, more subtle differences. If you look at the output of wn.lemmas('car'), the output from NLTK is List[Lemma](car.n.01.car, car.n.02.car, car.n.03.car, car.n.04.car, cable_car.n.01.car). On the other hand, the output from my Scala code is List[Word](car.n.01.car, car.n.01.car, car.n.01.car, car.n.01.car, cable_car.n.02.car). This is because NLTK puts the Synset ID in the third position. My JWNL based wn.lemmas() method returns a List of Synsets, each Synset containing a List of Words, and provides a Word.id value which refers to the position of the Word within the Synset. Since my formatting method does not have access to the id of the Synset, it is not able to populate the third position correctly.

Another difference, which is not that critical (once you know it, you can work around it) is that NLTK's and my version of wn.hyponyms() return synsets in opposite order. Also my allSynsets() returns Synsets in a different order than does NLTK's wn.all_synsets() call.

Some of the WS4j Similarity measures depend on the Information Content, which in turn depends on a corpus being analyzed. NLTK provides access to a many corpora and allows the user to specify what corpus should be used to calculate the Information Content. WS4j uses the SEMCOR corpus, and does not allow it to be overriden as far as I can tell.

The JUnit code below shows how to call the methods in the Wordnet.scala class. Each test case roughly corresponds to a block in the session above, and closely mimics the calls in the NLTK Chapter 2 and HOWTO pages. All exceptions are clearly marked in the Javadocs.

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
// Source: src/test/scala/com/mycompany/scalcium/utils/WordnetTest.scala
package com.mycompany.scalcium.utils

import java.io.File

import org.junit.Assert
import org.junit.Test

import net.didion.jwnl.data.POS

class WordnetTest {

  val wn = new Wordnet(new File("src/main/resources/wnconfig.xml"))

  /**
   * >>> from nltk.corpus import wordnet as wn
   * >>> wn.synsets('motorcar')
   * [Synset('car.n.01')]
   */
  @Test
  def testSynsets(): Unit = {
    Console.println(">>> wn.synsets('motorcar')")
    val motorcar = wn.synsets("motorcar")
    Console.println(motorcar.map(m => wn.format(m)))
    Assert.assertNotNull(motorcar)
  }
  
  /**
   * >>> wn.synset('car.n.01').lemma_names
   * ['car', 'auto', 'automobile', 'machine', 'motorcar']
   */
  @Test
  def testSynsetLemmaNames(): Unit = {
    Console.println(">>> wn.synset('car.n.01').lemma_names")
    val lms = wn.lemmaNames(wn.synset("car", POS.NOUN, 1))
    Console.println(lms)
    Assert.assertEquals(5, lms.size)
  }
  
  /**
   * >>> wn.synset('car.n.01').definition
   * 'a motor vehicle with four wheels; usually propelled by \
   * an internal combustion engine'
   */
  @Test
  def testSynsetDefinition(): Unit = {
    Console.println(">>> wn.synset('car.n.01').definition")
    val sd = wn.definition(wn.synset("car", POS.NOUN, 1))
    Console.println(sd)
    Assert.assertTrue(sd.contains(";"))
  }
  
  /**
   * >>> wn.synset('car.n.01').examples
   * ['he needs a car to get to work']
   */
  @Test
  def testSynsetExamples(): Unit = {
    Console.println(">>> wn.synset('car.n.01').examples")
    val se = wn.examples(wn.synset("car", POS.NOUN, 1))
    Console.println(se)
    Assert.assertEquals(1, se.size)
  }
  
  /**
   * >>> wn.synset('car.n.01').lemmas
   * [Lemma('car.n.01.car'), Lemma('car.n.01.auto'), \
   * Lemma('car.n.01.automobile'),\
   * Lemma('car.n.01.machine'), Lemma('car.n.01.motorcar')]
   * >>> wn.synset('car.n.01').lemmas[1]
   * Lemma('car.n.01.auto')
   */
  @Test
  def testSynsetLemmas(): Unit = {
    Console.println(">>> wn.synset('car.n.01').lemmas")
    val sl = wn.lemmas(wn.synset("car", POS.NOUN, 1))
    Console.println(sl.map(l => wn.format(l)))
    Assert.assertEquals(5, sl.size)
    Assert.assertTrue(sl(1).getLemma().equals("auto"))
  }
  
  /**
   * >>> wn.lemma('car.n.01.automobile').name
   * 'automobile'
   */
  @Test
  def testSynsetLemma(): Unit = {
    Console.println(">>> wn.lemma('car.n.01.automobile').name")
    val sl = wn.lemma(wn.synset("car", POS.NOUN, 1), 2)
    sl match {
      case Some(x) => {
        Console.println(x.getLemma())
        Assert.assertTrue("automobile".equals(x.getLemma()))
      }
      case None => Assert.fail()
    }
  }
  
  /**
   * >>> for synset in wn.synsets('car'):
   * ...     print synset.lemma_names
   * ...
   * ['car', 'auto', 'automobile', 'machine', 'motorcar']
   * ['car', 'railcar', 'railway_car', 'railroad_car']
   * ['car', 'gondola']
   * ['car', 'elevator_car']
   * ['cable_car', 'car']
   */
  @Test
  def testSynsetsAndLemmaNames(): Unit = {
    Console.println(">>> for synset in wn.synsets('car'):")
    Console.println("...     print synset.lemma_names")
    Console.println("...")
    val lns = wn.synsets("car")
      .map(ss => wn.lemmaNames(Some(ss)))
    lns.foreach(ln => 
      Console.println("[" + ln.mkString(", ") + "]"))
    Assert.assertEquals(5, lns.size)
    Assert.assertEquals(5, lns(0).size)
  }
  
  /**
   * >>> wn.lemmas('car')
   * [Lemma('car.n.01.car'), Lemma('car.n.02.car'), \
   * Lemma('car.n.03.car'), Lemma('car.n.04.car'), \
   * Lemma('cable_car.n.01.car')]
   * :NOTE: in NLTK, the third field in Lemma indicates 
   * the (unique) sequence number of the synset from which
   * the lemma is derived. For example, Lemma('car.n.01.car')
   * comes from the first synset with word(0) == "car".
   * JWNL does not capture the information, the index
   * here means the sequence number of the lemma inside
   * the synset.
   */
  @Test
  def testLemmas(): Unit = {
    Console.println(">>> wn.lemmas('car')")
    val ls = wn.lemmas("car")
    Console.println(ls.map(l => wn.format(l)))
  }
  
  /**
   * >>> motorcar = wn.synset('car.n.01')
   * >>> types_of_motorcar = motorcar.hyponyms()
   * >>> types_of_motorcar[26]
   * Synset('ambulance.n.01')
   * :NOTE: NLTK's wordnet returns hyponyms in a different
   * order than JWNL but both return the same number of
   * synsets. Test is modified accordingly.
   */
  @Test
  def testHyponyms(): Unit = {
    Console.println(">>> motorcar = wn.synset('car.n.01')")
    Console.println(">>> types_of_motorcar = motorcar.hyponyms()")
    val motorcar = wn.synset("car", POS.NOUN, 1)
    val typesOfMotorcar = wn.hyponyms(motorcar)
    Console.println(">>> types_of_motorcar")
    Console.println(typesOfMotorcar.map(ss => wn.format(ss)))
    Assert.assertEquals(31, typesOfMotorcar.size)
    Console.println(">>> types_of_motorcar[0]")
    val ambulance = typesOfMotorcar(0)
    Console.println(wn.format(ambulance))
    Assert.assertEquals("ambulance.n.01", wn.format(ambulance))
    Console.println(">>> sorted([lemma.name for synset\n" +  
       "...    in types_of_motorcar for lemma in synset.lemmas])")
    val sortedMotorcarNames = typesOfMotorcar
      .map(ss => wn.lemmaNames(Some(ss))(0))
      .sortWith((a,b) => a < b)
    Console.println(sortedMotorcarNames)
    Assert.assertEquals("Model_T", sortedMotorcarNames(0))
  }
  
  /**
   * >>> motorcar.hypernyms()
   * [Synset('motor_vehicle.n.01')]
   */
  @Test
  def testHypernyms(): Unit = {
    Console.println(">> motorcar.hypernyms")
    val motorcar = wn.synset("car", POS.NOUN, 1)
    val parents = wn.hypernyms(motorcar)
    Console.println(parents.map(p => wn.format(p)))
    Assert.assertEquals(1, parents.size)
    Assert.assertEquals("motor_vehicle.n.01", 
      wn.format(parents(0)))
  }
  
  /**
   * >>> paths = motorcar.hypernym_paths()
   * >>> len(paths)
   * 2
   * >>> [synset.name for synset in paths[0]]
   * ['entity.n.01', 'physical_entity.n.01', 'object.n.01', 
   * 'whole.n.02', 'artifact.n.01', 'instrumentality.n.03', 
   * 'container.n.01', 'wheeled_vehicle.n.01',
   * 'self-propelled_vehicle.n.01', 'motor_vehicle.n.01', 
   * 'car.n.01']
   * >>> [synset.name for synset in paths[1]]
   * ['entity.n.01', 'physical_entity.n.01', 'object.n.01', 
   * 'whole.n.02', 'artifact.n.01', 'instrumentality.n.03', 
   * 'conveyance.n.03', 'vehicle.n.01', 
   * 'wheeled_vehicle.n.01', 'self-propelled_vehicle.n.01', 
   * 'motor_vehicle.n.01', 'car.n.01']
   * >>> motorcar.root_hypernyms()
   * [Synset('entity.n.01')]
   */
  @Test
  def testHypernymPaths(): Unit = {
    Console.println(">>> paths = motorcar.hypernym_paths()")
    Console.println(">>> len(paths)")
    val motorcar = wn.synset("car", POS.NOUN, 1)
    val paths = wn.hypernymPaths(motorcar)
    Console.println(paths.size)
    Assert.assertEquals(2, paths.size)
    Console.println(">>> [synset.name for synset in paths[0]]")
    val paths0 = paths(0).map(ss => wn.format(ss))
    Console.println(paths0)
    Console.println(">>> [synset.name for synset in paths[1]]")
    val paths1 = paths(1).map(ss => wn.format(ss))
    Console.println(paths1)
    Console.println(">>> motorcar.root_hypernyms()")
    val rhns = wn.rootHypernyms(motorcar)
      .map(rhn => wn.format(rhn))
    Console.println(rhns)
  }
  
  /**
   * >>> wn.synset('tree.n.01').part_meronyms()
   * [Synset('burl.n.02'), Synset('crown.n.07'), 
   * Synset('stump.n.01'), Synset('trunk.n.01'), 
   * Synset('limb.n.02')]
   * >>> wn.synset('tree.n.01').substance_meronyms()
   * [Synset('heartwood.n.01'), Synset('sapwood.n.01')]
   * >>> wn.synset('tree.n.01').member_holonyms()
   * [Synset('forest.n.01')]
   */
  @Test
  def testMiscRelationMethods(): Unit = {
    Console.println(">>> wn.synset('tree.n.01').part_meronyms()")
    val tree = wn.synset("tree", POS.NOUN, 1)
    val pn = wn.partMeronyms(tree)
    Console.println(pn.map(ss => wn.format(ss)))
    Assert.assertEquals(5, pn.size)
    Console.println(">>> wn.synset('tree.n.01').substance_meronyms()")
    val sn = wn.substanceMeronyms(tree)
    Assert.assertEquals(2, sn.size)
    Console.println(sn.map(ss => wn.format(ss)))
    Console.println(">>> wn.synset('tree.n.01').member_holonyms()")
    val mn = wn.memberHolonyms(tree)
    Assert.assertEquals(1, mn.size)
    Console.println(mn.map(ss => wn.format(ss)))
  }
  
  /**
   * >>> for synset in wn.synsets('mint', wn.NOUN):
   * ...     print synset.name + ':', synset.definition
   * ...
   * batch.n.02: (often followed by `of') a large number or amount or extent
   * mint.n.02: any north temperate plant of the genus Mentha with aromatic leaves and
   *        small mauve flowers
   * mint.n.03: any member of the mint family of plants
   * mint.n.04: the leaves of a mint plant used fresh or candied
   * mint.n.05: a candy that is flavored with a mint oil
   * mint.n.06: a plant where money is coined by authority of the government
   * >>> wn.synset('mint.n.04').part_holonyms()
   * [Synset('mint.n.02')]
   * >>> [x.definition for x 
   * ...    in wn.synset('mint.n.04').part_holonyms()]
   * ['any north temperate plant of the genus Mentha with 
   *   aromatic leaves and small mauve flowers']
   * >>> wn.synset('mint.n.04').substance_holonyms()
   * [Synset('mint.n.05')]
   * >>> [x.definition for x 
   * ...    in wn.synset('mint.n.04').substance_holonyms()]
   * ['a candy that is flavored with a mint oil']
   */
  @Test
  def testListSynsetNameDefinition(): Unit = {
    val mintss = wn.synsets("mint", POS.NOUN)
    Assert.assertEquals(6, mintss.size)
    Console.println(">>> for synset in wn.synsets('mint', wn.NOUN):")
    Console.println("...     print synset.name + ':', synset.definition")
    Console.println("...")
    mintss.foreach(ss => 
      Console.println(wn.format(ss) + ": " + 
        wn.definition(Some(ss))))
    Console.println(">>> wn.synset('mint.n.04').part_holonyms()")
    val mint = wn.synset("mint", POS.NOUN, 4)
    val ph = wn.partHolonyms(mint)
    Console.println(ph.map(ss => wn.format(ss)))
    Console.println(">>> [x.definition for x") 
    Console.println("...    in wn.synset('mint.n.04').part_holonyms()]")
    Console.println(ph.map(ss => wn.definition(Some(ss))))
    Console.println(">>> wn.synset('mint.n.04').substance_holonyms()")
    val sh = wn.substanceHolonyms(mint)
    Console.println(sh.map(ss => wn.format(ss)))
    Console.println(">>> [x.definition for x") 
    Console.println("...    in wn.synset('mint.n.04').substance_holonyms()]")
    Console.println(sh.map(ss => wn.definition(Some(ss))))
  }
  
  /**
   * >>> wn.synset('walk.v.01').entailments()
   * [Synset('step.v.01')]
   * >>> wn.synset('eat.v.01').entailments()
   * [Synset('swallow.v.01'), Synset('chew.v.01')]
   * >>> wn.synset('tease.v.03').entailments()
   * [Synset('arouse.v.07'), Synset('disappoint.v.01')]
   */
  @Test
  def testVerbRelationships(): Unit = {
    Console.println(">>> wn.synset('walk.v.01').entailments()")
    val walk = wn.synset("walk", POS.VERB, 1)
    val walkEnt = wn.entailments(walk)
    Console.println(walkEnt.map(ss => wn.format(ss)))
    Assert.assertEquals(1, walkEnt.size)
    Console.println(">>> wn.synset('eat.v.01').entailments()")
    val eat = wn.synset("eat", POS.VERB, 1)
    val eatEnt = wn.entailments(eat)
    Console.println(eatEnt.map(ss => wn.format(ss)))
    Assert.assertEquals(2, eatEnt.size)
    Console.println(">>> wn.synset('tease.v.03').entailments()")
    val tease = wn.synset("tease", POS.VERB, 3)
    val teaseEnt = wn.entailments(tease)
    Console.println(teaseEnt.map(ss => wn.format(ss)))
    Assert.assertEquals(2, teaseEnt.size)
  }
  
  /**
   * >>> wn.lemma('supply.n.02.supply').antonyms()
   * [Lemma('demand.n.02.demand')]
   * >>> wn.lemma('rush.v.01.rush').antonyms()
   * [Lemma('linger.v.04.linger')]
   * >>> wn.lemma('horizontal.a.01.horizontal').antonyms()
   * [Lemma('vertical.a.01.vertical'), 
   * Lemma('inclined.a.02.inclined')]
   * >>> wn.lemma('staccato.r.01.staccato').antonyms()
   * [Lemma('legato.r.01.legato')]
   */
  @Test
  def testLemmaAntonyms(): Unit = {
    Console.println(">>> wn.lemma('supply.n.02.supply').antonyms()")
    val supply = wn.lemma(wn.synset("supply", POS.NOUN, 2), "supply")
    val supplyAntonyms = wn.antonyms(supply)
    Console.println(supplyAntonyms.map(w => wn.format(w)))
    Assert.assertEquals(1, supplyAntonyms.size)
    Console.println(">>> wn.lemma('rush.v.01.rush').antonyms()")
    val rush = wn.lemma(wn.synset("rush", POS.VERB, 1), "rush")
    val rushAntonyms = wn.antonyms(rush)
    Console.println(rushAntonyms.map(w => wn.format(w)))
    Assert.assertEquals(1, rushAntonyms.size)
    Console.println(">>> wn.lemma('horizontal.a.01.horizontal').antonyms()")
    val horizontal = wn.lemma(wn.synset("horizontal", POS.ADJECTIVE, 1), "horizontal")
    val horizontalAntonyms = wn.antonyms(horizontal)
    Console.println(horizontalAntonyms.map(w => wn.format(w)))
    Assert.assertEquals(2, horizontalAntonyms.size)
    Console.println(">>> wn.lemma('staccato.r.01.staccato').antonyms()")
    val staccato = wn.lemma(wn.synset("staccato", POS.ADVERB, 1), "staccato")
    val staccatoAntonyms = wn.antonyms(staccato)
    Console.println(staccatoAntonyms.map(w => wn.format(w)))
    Assert.assertEquals(1, staccatoAntonyms.size)
  }

  /**
   * >>> right = wn.synset('right_whale.n.01')
   * >>> orca = wn.synset('orca.n.01')
   * >>> minke = wn.synset('minke_whale.n.01')
   * >>> tortoise = wn.synset('tortoise.n.01')
   * >>> novel = wn.synset('novel.n.01')
   * >>> right.lowest_common_hypernyms(minke)
   * [Synset('baleen_whale.n.01')]
   * >>> right.lowest_common_hypernyms(orca)
   * [Synset('whale.n.02')]
   * >>> right.lowest_common_hypernyms(tortoise)
   * [Synset('vertebrate.n.01')]
   * >>> right.lowest_common_hypernyms(novel)
   * [Synset('entity.n.01')]
   */
  @Test
  def testSynsetLowestCommonHypernyms(): Unit = {
    Console.println(">>> right = wn.synset('right_whale.n.01')")
    Console.println(">>> orca = wn.synset('orca.n.01')")
    Console.println(">>> minke = wn.synset('minke_whale.n.01')")
    Console.println(">>> tortoise = wn.synset('tortoise.n.01')")
    Console.println(">>> novel = wn.synset('novel.n.01')")
    val right = wn.synset("right_whale", POS.NOUN, 1)
    val orca = wn.synset("orca", POS.NOUN, 1)
    val minke = wn.synset("minke_whale", POS.NOUN, 1)
    val tortoise = wn.synset("tortoise", POS.NOUN, 1)
    val novel = wn.synset("novel", POS.NOUN, 1)
    Console.println(">>> right.lowest_common_hypernyms(minke)")
    val rightMinkeLCH = wn.lowestCommonHypernym(right, minke)
    Console.println(rightMinkeLCH.map(ss => wn.format(ss)))
    Console.println(">>> right.lowest_common_hypernyms(orca)")
    val rightOrcaLCH = wn.lowestCommonHypernym(right, orca)
    Console.println(rightOrcaLCH.map(ss => wn.format(ss)))
    Console.println(">>> right.lowest_common_hypernyms(tortoise)")
    val rightTortoiseLCH = wn.lowestCommonHypernym(right, tortoise)
    Console.println(rightTortoiseLCH.map(ss => wn.format(ss)))
    Console.println(">>> right.lowest_common_hypernyms(novel)")
    val rightNovelLCH = wn.lowestCommonHypernym(right, novel)
    Console.println(rightNovelLCH.map(ss => wn.format(ss)))
  }
  
  /**
   * >>> wn.synset('baleen_whale.n.01').min_depth()
   * 14
   * >>> wn.synset('whale.n.02').min_depth()
   * 13
   * >>> wn.synset('vertebrate.n.01').min_depth()
   * 8
   * >>> wn.synset('entity.n.01').min_depth()
   * 0
   */
  @Test
  def testSynsetMinDepth(): Unit = {
    Console.println(">>> wn.synset('baleen_whale.n.01').min_depth()")
    val baleenWhaleMinDepth = wn.minDepth(wn.synset("baleen_whale", POS.NOUN, 1))
    Console.println(baleenWhaleMinDepth)
    Assert.assertEquals(14, baleenWhaleMinDepth)
    Console.println(">>> wn.synset('whale.n.02').min_depth()")
    val whaleMinDepth = wn.minDepth(wn.synset("whale", POS.NOUN, 2))
    Console.println(whaleMinDepth)
    Assert.assertEquals(13, whaleMinDepth)
    Console.println(">>> wn.synset('vertebrate.n.01').min_depth()")
    val vertebrateMinDepth = wn.minDepth(wn.synset("vertebrate", POS.NOUN, 1))
    Console.println(vertebrateMinDepth)
    Assert.assertEquals(8, vertebrateMinDepth)
    Console.println(">>> wn.synset('entity.n.01').min_depth()")
    val entityMinDepth = wn.minDepth(wn.synset("entity", POS.NOUN, 1))
    Console.println(entityMinDepth)
    Assert.assertEquals(0, entityMinDepth)
  }
  
  /**
   * >>> right.path_similarity(minke)
   * 0.25
   * >>> right.path_similarity(orca)
   * 0.16666666666666666
   * >>> right.path_similarity(tortoise)
   * 0.076923076923076927
   * >>> right.path_similarity(novel)
   * 0.043478260869565216
   */
  @Test
  def testPathSimilarity(): Unit = {
    val right = wn.synset("right_whale", POS.NOUN, 1)
    val orca = wn.synset("orca", POS.NOUN, 1)
    val minke = wn.synset("minke_whale", POS.NOUN, 1)
    val tortoise = wn.synset("tortoise", POS.NOUN, 1)
    val novel = wn.synset("novel", POS.NOUN, 1)
    Console.println(">>> right.path_similarity(minke)")
    val rightMinkePathSimilarity = wn.pathSimilarity(right, minke) 
    Console.println(rightMinkePathSimilarity)
    Assert.assertEquals(0.25D, rightMinkePathSimilarity, 0.01D)
    Console.println(">>> right.path_similarity(orca)")
    val rightOrcaPathSimilarity = wn.pathSimilarity(right, orca) 
    Console.println(rightOrcaPathSimilarity)
    Assert.assertEquals(0.1667D, rightOrcaPathSimilarity, 0.01D)
    Console.println(">>> right.path_similarity(tortoise)")
    val rightTortoisePathSimilarity = wn.pathSimilarity(right, tortoise) 
    Console.println(rightTortoisePathSimilarity)
    Assert.assertEquals(0.0769D, rightTortoisePathSimilarity, 0.01D)
    Console.println(">>> right.path_similarity(novel)")
    val rightNovelPathSimilarity = wn.pathSimilarity(right, novel) 
    Console.println(rightNovelPathSimilarity)
    Assert.assertEquals(0.043D, rightNovelPathSimilarity, 0.01D)
  }

  /**
   * >>> dog = wn.synset('dog.n.01')
   * >>> cat = wn.synset('cat.n.01')
   * >>> hit = wn.synset('hit.v.01')
   * >>> slap = wn.synset('slap.v.01')
   * >>> dog.path_similarity(cat)
   * 0.2...
   * >>> hit.path_similarity(slap)
   * 0.142...
   * >>> dog.lch_similarity(cat)
   * 2.028...
   * >>> hit.lch_similarity(slap)
   * 1.312...
   * >>> dog.wup_similarity(cat)
   * 0.857...
   * >>> hit.wup_similarity(slap)
   * 0.25
   * >>> dog.res_similarity(cat, semcor_ic)
   * 7.911...
   * >>> dog.jcn_similarity(cat, semcor_ic)
   * 0.449...
   * >>> dog.lin_similarity(cat, semcor_ic)
   * 0.886...
   */
  @Test
  def testOtherSimilarities(): Unit = {
    Console.println(">>> dog = wn.synset('dog.n.01')")
    Console.println(">>> cat = wn.synset('cat.n.01')")
    Console.println(">>> hit = wn.synset('hit.v.01')")
    Console.println(">>> slap = wn.synset('slap.v.01')")
    val dog = wn.synset("dog", POS.NOUN, 1)
    val cat = wn.synset("cat", POS.NOUN, 1)
    val hit = wn.synset("hit", POS.VERB, 1)
    val slap = wn.synset("slap", POS.VERB, 1)
    
    Console.println(">>> dog.path_similarity(cat)")
    val dogCatPathSimilarity = wn.pathSimilarity(dog, cat) 
    Console.println(dogCatPathSimilarity)
    Console.println(">>> hit.path_similarity(slap)")
    val hitSlapPathSimilarity = wn.pathSimilarity(hit, slap)
    Console.println(hitSlapPathSimilarity)
    Assert.assertEquals(0.2D, dogCatPathSimilarity, 0.01D)
    Assert.assertEquals(0.1428D, hitSlapPathSimilarity, 0.01D)
    
    Console.println(">>> dog.lch_similarity(cat)")
    val dogCatLchSimilarity = wn.lchSimilarity(dog, cat)
    Console.println(dogCatLchSimilarity)
    Console.println(">>> hit.lch_similarity(slap)")
    val hitSlapLchSimilarity = wn.lchSimilarity(hit, slap)
    Console.println(hitSlapLchSimilarity)
    Assert.assertEquals(2.079D, dogCatLchSimilarity, 0.01D)
    Assert.assertEquals(1.386D, hitSlapLchSimilarity, 0.01D)
    
    Console.println(">>> dog.wup_similarity(cat)")
    val dogCatWupSimilarity = wn.wupSimilarity(dog, cat)
    Console.println(dogCatWupSimilarity)
    Console.println(">>> hit.wup_similarity(slap)")
    val hitSlapWupSimilarity = wn.wupSimilarity(hit, slap)
    Console.println(hitSlapWupSimilarity)
    Assert.assertEquals(0.866D, dogCatWupSimilarity, 0.01D)
    Assert.assertEquals(0.25D, hitSlapWupSimilarity, 0.01D)
    
    Console.println(">>> dog.res_similarity(cat)")
    val dogCatResSimilarity = wn.resSimilarity(dog, cat)
    Console.println(dogCatResSimilarity)
    Console.println(">>> hit.res_similarity(slap)")
    Assert.assertEquals(7.254D, dogCatResSimilarity, 0.01D)

    Console.println(">>> dog.jcn_similarity(cat)")
    val dogCatJcnSimilarity = wn.jcnSimilarity(dog, cat)
    Console.println(dogCatJcnSimilarity)
    Assert.assertEquals(0.537D, dogCatJcnSimilarity, 0.01D)

    Console.println(">>> dog.lin_similarity(cat)")
    val dogCatLinSimilarity = wn.linSimilarity(dog, cat)
    Console.println(dogCatLinSimilarity)
    Assert.assertEquals(0.886D, dogCatLinSimilarity, 0.01D)
  }
  
  /**
   * >>> for synset in list(wn.all_synsets('n'))[:10]:
   * ...     print(synset)
   * ...
   * Synset('entity.n.01')
   * Synset('physical_entity.n.01')
   * Synset('abstraction.n.06')
   * Synset('thing.n.12')
   * Synset('object.n.01')
   * Synset('whole.n.02')
   * Synset('congener.n.03')
   * Synset('living_thing.n.01')
   * Synset('organism.n.01')
   * Synset('benthos.n.02')
   * :NOTE: order of synsets returned is different in 
   * JWNL than with NLTK.
   */
  @Test
  def testAllSynsets(): Unit = {
    Console.println(">>> for synset in list(wn.all_synsets('n'))[:10]:")
    Console.println("...     print(synset)")
    Console.println("...")
    val fss = wn.allSynsets(POS.NOUN)
      .take(10)
      .toList
    fss.foreach(ss => Console.println(wn.format(ss)))
    Assert.assertEquals(10, fss.size)
  }
  
  /**
   * >>> print(wn.morphy('denied', wn.VERB))
   * deny
   * >>> print(wn.morphy('dogs'))
   * dog
   * >>> print(wn.morphy('churches'))
   * church
   * >>> print(wn.morphy('aardwolves'))
   * aardwolf
   * >>> print(wn.morphy('abaci'))
   * abacus
   * >>> print(wn.morphy('book', wn.NOUN))
   * book
   * >>> wn.morphy('hardrock', wn.ADV)
   * >>> wn.morphy('book', wn.ADJ)
   * >>> wn.morphy('his', wn.NOUN)
   */
  @Test
  def testMorphy(): Unit = {
    Console.println(">>> print(wn.morphy('denied', wn.VERB))")
    val denied = wn.morphy("denied", POS.VERB)
    Console.println(denied)
    Assert.assertEquals("deny", denied)
    Console.println(">>> print(wn.morphy('dogs'))")
    val dogs = wn.morphy("dogs")
    Console.println(dogs)
    Assert.assertEquals("dog", dogs)
    Console.println(">>> print(wn.morphy('churches'))")
    val churches = wn.morphy("churches")
    Console.println(churches)
    Assert.assertEquals("church", churches)
    Console.println(">>> print(wn.morphy('aardwolves'))")
    val aardwolves = wn.morphy("aardwolves")
    Console.println(aardwolves)
    Assert.assertEquals("aardwolf", aardwolves)
    Console.println(">>> print(wn.morphy('abaci'))")
    val abaci = wn.morphy("abaci")
    Console.println(abaci)
    Assert.assertEquals("abacus", abaci)
    Console.println(">>> print(wn.morphy('book', wn.NOUN))")
    val book = wn.morphy("book", POS.NOUN)
    Console.println(book)
    Assert.assertEquals("book", book)
    Console.println(">>> wn.morphy('hardrock', wn.ADV)")
    val hardrock = wn.morphy("hardrock", POS.ADVERB)
    Console.println(hardrock)
    Assert.assertTrue(hardrock.isEmpty)
    Console.println(">>> wn.morphy('book', wn.ADJ)")
    val bookAdj = wn.morphy("book", POS.ADJECTIVE)
    Console.println(bookAdj)
    Assert.assertTrue(bookAdj.isEmpty)
    Console.println(">>> wn.morphy('his', wn.NOUN)")
    val his = wn.morphy("his", POS.NOUN)
    Console.println(his)
    Assert.assertTrue(his.isEmpty)
  }
}

Writing this code to mimic the functionality of NLTK's Wordnet interface has given me quite a bit of insight into JWNL (and to a lesser extent WS4j). In the past I had used hyponyms and hypernyms, but there are a large number of other relationships available. The other new thing I learned was the Wordnet Morphological Analyzer, an English Lemmatizer, which is available in JWNL, and with which I implemented the wn.morphy() methods. In terms of utility, I now have a way of accessing Wordnet from Scala that is as powerful as NLTK's.