Class: LinkParser

Inherits:
Object show all
Includes:
Log4r
Defined in:
lib/linkparser.rb,
lib/linkparser/log.rb,
lib/linkparser/word.rb,
lib/linkparser/utils.rb,
lib/linkparser/linkage.rb,
lib/linkparser/sentence.rb,
lib/linkparser/connector.rb,
lib/linkparser/connection.rb,
lib/linkparser/definition.rb,
lib/linkparser/dictionary.rb

Overview

connection.rb - this file contains the class declarations for the LinkParser::Connection class.

Synopsis

Rcsid

$Id: connection.rb,v 1.3 2003/06/08 03:53:27 stillflame Exp $

Authors

Martin Chase <[email protected]>

:include: COPYRIGHT


Please see the file COPYRIGHT for licensing details.

Defined Under Namespace

Classes: Connection, Connector, Definition, Dictionary, Linkage, ParseError, ParseState, Sentence, Word

Constant Summary collapse

LEFT_MODE =
1
RIGHT_MODE =
2
INNER_MODE =
4
OUTER_MODE =
8
FORCE_MODE =
16
UNSATISFIED =
nil
Log =
Logger::new( "LinkParser" )

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dict_opts, parse_opts) ⇒ LinkParser

Initializes a new parser, using the option hashes given



66
67
68
69
# File 'lib/linkparser.rb', line 66

def initialize( dict_opts, parse_opts )
    @dictionary = LinkParser::Dictionary::new(dict_opts)
    @parseOptions = parse_opts
end

Instance Attribute Details

#dictionaryObject (readonly)

the dictionary



426
427
428
# File 'lib/linkparser.rb', line 426

def dictionary
  @dictionary
end

#parseOptionsObject (readonly)

the options for parsing



429
430
431
# File 'lib/linkparser.rb', line 429

def parseOptions
  @parseOptions
end

Instance Method Details

#add_connection(ps) ⇒ Object

With a connection having been found between two words, or assumed to be so, create it if possible, recurse where needed, and combine it all into the results. The “force” modes are where no actual connection has been made, but recursion is still needed to connect the words inbetween the inner word under consideration and both edge words.



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/linkparser.rb', line 242

def add_connection(ps)
  if (ps.mode & INNER_MODE).nonzero?
    if (ps.mode & FORCE_MODE).nonzero?
      r = inner_force_recursion(ps)
      # Log.debug( "inner_force_recursion finished" )
      r
    else
      r = inner_add_connection(ps)
      # Log.debug( "inner_add_connection finished" )
      r
    end
  elsif (ps.mode & FORCE_MODE).nonzero?
    r = outer_force_recursion(ps)
    # Log.debug( "outer_force_recursion finished" )
    r
  else
    r = outer_add_connection(ps)
    # Log.debug( "outer_add_connection finished" )
    r
  end
end

#create_connection(sentence, left, right, left_conn, right_conn) ⇒ Object

Makes the Word and Connection objects out of the Sentence, indicies and Connectors.



394
395
396
397
398
399
400
401
# File 'lib/linkparser.rb', line 394

def create_connection(sentence, left, right, left_conn, right_conn)
  left_word = Word::new(sentence, left)
  right_word = Word::new(sentence, right)
  connection = Connection::new(left_conn, right_conn, left_word, right_word)
  left_word.right << connection
  right_word.left << connection
  return [left_word, right_word, connection]
end

#find_linkages(sentence) ⇒ Object

Finds all valid linkages in the sentence



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
# File 'lib/linkparser.rb', line 110

def find_linkages(sentence)
  # Log.debug( "find_linkages start" )
  ps = ParseState::new
  ps.sentence = sentence
  # :MC: To be used for pruning, but not until profiling/benchmarking is
  # done.  The idea will be to check each <side>_conn to see if it has any
  # chance of connecting, and if not, skipping the entire set.
  ps.all_connectors = make_connector_hash(ps.sentence)
  # Log.debug( "Connector hash created => #{ps.all_connectors.inspect}" )
  ps.results = []
  ps.left = 0
  ps.right = sentence.definitions.length - 1
  satisfied = false
  for ps.right_set in ps.sentence.definitions[ps.right].connector_sets do
    next unless ps.right_set.right.all_pass?(:optional?)
    # :MC: For pruning.
    next if ps.right_set.find {|c| (! c.optional?) and (ps.all_connectors[c].empty? or c.cost > 0)}
    for ps.left_set in ps.sentence.definitions[ps.left].connector_sets do
      next unless ps.left_set.left.all_pass?(:optional?)
      # :MC: For pruning.
      next if ps.left_set.find {|c| (! c.optional?) and (ps.all_connectors[c].empty? or c.cost > 0)}
      matched = false
      for ps.right_conn in ps.right_set.left do
        for ps.left_conn in ps.left_set.right do
          if ps.left_conn.match(ps.right_conn)
            matched = true
            ps.mode = OUTER_MODE
            flag = add_connection(ps)
            satisfaction = true unless flag == UNSATISFIED
          end
        end
      end
      unless matched
        ps.right_conn = ps.left_conn = nil
        ps.mode = OUTER_MODE | FORCE_MODE
        flag = add_connection(ps)
        satisfaction = true unless flag == UNSATISFIED
      end
    end
  end
  ps.results = ps.results.find_all {|linkage|
    linkage.valid? && linkage.connected?
  }
  ps.results.uniq!
  if satisfaction
    # Log.debug( "find_linkages finished - %d results" % ps.results.length )
  else
    # Log.debug( "find_linkages finished - unsatisfied" )
  end
  return ps.results
end

#inner_add_connection(ps) ⇒ Object

Inside of recursion, create the connection, recurse on either side, combine the results of each. This mostly just rearranges the parse state for the recursions to follow.



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
# File 'lib/linkparser.rb', line 342

def inner_add_connection(ps)
  new_ps = ParseState::new(*ps.to_a)
  new_ps.inner_set = new_ps.inner = new_ps.inner_conn = nil
  if (ps.mode & RIGHT_MODE).nonzero?
    left, right, ps.left_word, ps.right_word, ps.connection =
      ps.inner, ps.right,
      *create_connection(ps.sentence, ps.inner, ps.right,
                 ps.inner_conn, ps.right_conn)
    new_ps.update({ :results =>   [],
            :left =>    ps.inner,
            })
    if ps.inner_conn.multiple?
      new_ps.update({:left_set =>  ps.inner_set})
    else
      new_ps.update({:left_set =>  ps.inner_set - [ps.inner_conn]})
    end
    new_ps.update({:right_set =>  ps.right_set - [ps.right_conn]}) unless
      ps.right_conn.multiple?
  else # LEFT_MODE
    left, right, ps.left_word, ps.right_word, ps.connection =
      ps.left, ps.inner,
      *create_connection(ps.sentence, ps.left, ps.inner,
                 ps.left_conn, ps.inner_conn)
    new_ps.update({ :results =>   [],
              :right =>   ps.inner,
            })
    new_ps.update({:left_set => ps.left_set - [ps.left_conn]}) unless
      ps.left_conn.multiple?
    if ps.inner_conn.multiple?
      new_ps.update({:right_set => ps.inner_set})
    else
      new_ps.update({:right_set => ps.inner_set - [ps.inner_conn]})
    end
  end
  # Log.debug( "inner_add_connection start with %s" % ps.connection )
  results = re_find_linkages(new_ps)
  if results == UNSATISFIED
    # Log.debug( "re_find_linkages(%d, %d) end - unsatisfied" %
#           [new_ps.left, new_ps.right])
    return results
  end
  # Log.debug("re_find_linkages(%d, %d) end - %d results" %
#         [new_ps.left, new_ps.right, results.length])
  results << Linkage::new(ps.sentence.names.map{nil}) if results.empty?
  ps.results += results.collect {|linkage|
    linkage.insert(ps.connection, left, right,
             ps.left_word, ps.right_word)
  }
end

#inner_force_recursion(ps) ⇒ Object

Inside of a recurse, pretend there is a connection between two words to find any connections that may exist to the words in between, and if those connections are enough to satisfy the conditions of connectivity and satisfaction.



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/linkparser.rb', line 314

def inner_force_recursion(ps)
  # Log.debug( "inner_force_recursion start" )
  new_ps = ParseState::new(*ps.to_a)
  if (ps.mode & RIGHT_MODE).nonzero?
    left, right = ps.inner, ps.right
    new_ps.update({ :results =>   [],
            :left =>    ps.inner,
            })
  else # LEFT_MODE
    left, right = ps.left, ps.inner
    new_ps.update({ :results =>   [],
            :right =>   ps.inner,
            })
  end
  results = re_find_linkages(new_ps)
  if results == UNSATISFIED
    # Log.debug( "re_find_linkages(%d, %d) end - unsatisfied" %
    #     [new_ps.left, new_ps.right])
  else
    # Log.debug("re_find_linkages(%d, %d) end - %d results" %
    #     [new_ps.left, new_ps.right, results.length])
  end
  return results
end

#make_connector_hash(sentence) ⇒ Object

Creates a hash of connectors to the words that have matching connectors.



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/linkparser.rb', line 404

def make_connector_hash( sentence )
  connectors = {}
  sentence.definitions.each {|word|
    word.connector_sets.each {|set|
      set.each {|connector|
        # :TODO: add in pruning somewhere around here
        connectors[connector] = nil
      }
    }
  }
  connectors.each {|connector,val|
    connectors[connector] = connectors.keys.find_all {|conn| conn.match(connector)}
  }
  return connectors
end

#outer_add_connection(ps) ⇒ Object

In the outer call of find_linkages, a connection has been found, so create it and recurse into the inner words.



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
# File 'lib/linkparser.rb', line 266

def outer_add_connection(ps)
  ps.left_word, ps.right_word, ps.connection =
    create_connection( ps.sentence, ps.left, ps.right, ps.left_conn,
               ps.right_conn )
  # Log.debug( "outer_add_connection with %s." % ps.connection )
  new_ps = ParseState::new(*ps.to_a)
  new_ps.update( {:results =>    []} )
  new_ps.update( {:left_set => ps.left_set - [ps.left_conn]} ) unless
    ps.left_conn.multiple?
  new_ps.update( {:right_set =>  ps.right_set - [ps.right_conn]} ) unless
    ps.right_conn.multiple?
  results = re_find_linkages(new_ps)
  if results == UNSATISFIED
    # Log.debug("re_find_linkages(%d, %d) end - unsatisfied" %
    #     [new_ps.left, new_ps.right])
    return results
  end
  # Log.debug("re_find_linkages(%d, %d) end - %d results" %
  #        [new_ps.left, new_ps.right, results.length])
  results << Linkage::new(ps.sentence.names.map{nil}) if results.empty?
  ps.results += results.collect {|linkage|
    linkage.insert(ps.connection, ps.left, ps.right,
             ps.left_word, ps.right_word)
  }
end

#outer_force_recursion(ps) ⇒ Object

In the outer call of find_linkages, no connection was found between a pair of sets, but recurse anyway into the inner words.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/linkparser.rb', line 294

def outer_force_recursion(ps)
  # Log.debug( "outer_force_recursion on '%s' and '%s'" %
  #        [ps.left_set, ps.right_set] )
  new_ps = ParseState::new(*ps.to_a)
  new_ps.results = []
  results = re_find_linkages(new_ps)
  if results == UNSATISFIED
    # Log.debug( "re_find_linkages(%d, %d) end - unsatisfied" %
    #      [new_ps.left, new_ps.right])
    return results
  end
  # Log.debug( "re_find_linkages(%d, %d) end - %d results" %
  #       [new_ps.left, new_ps.right, new_ps.results.length] )
  ps.results += results
end

#parse(string) ⇒ Object

Takes a string and tries to parse it into a Sentence object

Raises:



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
# File 'lib/linkparser.rb', line 72

def parse( string )
    raise ParseError.new("Unable to parse nothing.") unless
      string && !string.empty?
    words = string.split
    
    words = @dictionary.affix(words)
    
    # Create LinkParser::Word objects out of the words and their definitions
    sentence = Sentence::new
#     if @dictionary.has_key?('LEFT-WALL')
#       sentence.definitions << @dictionary['LEFT-WALL']
#       sentence.names << 'LEFT-WALL'
#     end
    words.each {|word|
      # :!: This should be doing something to incorporate all the different "word.*"'s :!:
#if(found = @dictionary.dict.find {|w,d| %r$#{word}(\.\w)?$.match(w)})
      #  sentence.definitions << found[1]
      if @dictionary.has_key?(word)
sentence.definitions << @dictionary[word]
sentence.names << word
      else
#       raise ParseError::new("The word '#{word}' is not in the dictionary.")
      sentence.definitions << @dictionary["UNKNOWN"]
sentence.names << "UNKNOWN"
end
    }
#     if @dictionary.has_key?('RIGHT-WALL')
#       sentence.definitions << @dictionary['RIGHT-WALL']
#       sentence.names << 'RIGHT-WALL'
#     end
    
    # Find the linkages
    sentence.linkages = find_linkages(sentence)
    
    return sentence
end

#postProcess(sentence) ⇒ Object

does post-processing of a sentence



421
422
423
# File 'lib/linkparser.rb', line 421

def postProcess( sentence )
    sentence #:TODO:
end

#re_find_linkages(ps) ⇒ Object

Recursive body of the find_linkages method. See presentation for a general algorithm explaination.



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
# File 'lib/linkparser.rb', line 165

def re_find_linkages(ps)
  # Log.debug("re_find_linkages(%d, %d) start - (%s, %s)" % [
  #        ps.left, ps.right, ps.left_set.right, ps.right_set.left])
  # test for stopping recursion.
  if(ps.left == (ps.right - 1))
    if( ! (ps.left_set.right.all_pass?(:optional?) and
         ps.right_set.left.all_pass?(:optional?)) )
      return UNSATISFIED
    else
      return []
    end
  end
  results = []
  ps.right_conn = ps.left_conn = ps.inner_conn = nil
  satisfied = false
  for ps.inner in (ps.left+1)..(ps.right-1) do
    for ps.inner_set in ps.sentence.definitions[ps.inner].connector_sets do
      # :MC: For pruning.
      next if ps.inner_set.find {|c| (! c.optional?) and (ps.all_connectors[c].empty? or c.cost > 0)}
      for ps.inner_conn in ps.inner_set.left do
        for ps.left_conn in ps.left_set.right do
          if ps.inner_conn.match(ps.left_conn)
            # Log.debug( "(left)Connecting %s and %s" % [ps.left_conn, ps.inner_conn])
            ps.mode = LEFT_MODE | INNER_MODE
            # in the following call to add_connection, ps is
            # modified to include all the valid partial linkages
            # on this particular connection made using one of
            # the inner word's connectors on the left side.
            satisfied = true unless add_connection(ps) == UNSATISFIED
          end
        end
      end
      lefties = ps.results
      # check for needed recursion.
      if( lefties.empty? and (ps.inner != ps.left + 1) and
         ( ! (ps.left_set.right.all_pass?(:optional?) and
          ps.inner_set.left.all_pass?(:optional?) ) ) )
        ps.mode = LEFT_MODE | INNER_MODE | FORCE_MODE
        lefties = add_connection(ps)
      end
      ps.results = []
      ps.left_conn = nil
      for ps.inner_conn in ps.inner_set.right do
        for ps.right_conn in ps.right_set.left do
          if ps.inner_conn.match(ps.right_conn)
            # Log.debug( "(right)Connecting %s and %s" % [ps.inner_conn, ps.right_conn] )
            ps.mode = RIGHT_MODE | INNER_MODE
            # add_conneciton here makes ps.results include all
            # valid partial linkages between the inner word and
            # the right side word.
            satisfied = true unless add_connection(ps) == UNSATISFIED
          end
        end
      end
      righties = ps.results
      # check for needed recursion.
      if( righties.empty? and (ps.inner != ps.right - 1) and
         ( ! (ps.inner_set.right.all_pass?(:optional?) and
          ps.right_set.left.all_pass?(:optional?)) ) )
        ps.mode = RIGHT_MODE | INNER_MODE | FORCE_MODE
        righties = add_connection(ps)
      end
      ps.results = []
      unless( (lefties == UNSATISFIED) or (righties == UNSATISFIED) )
        results += lefties.set_combine(righties)
      end
    end
  end
  return UNSATISFIED unless satisfied
  return ps.results = results
end