aboutsummaryrefslogtreecommitdiffstats
path: root/fsa/src/vespa/fsa/segmenter.h
blob: 7502a887f651037a27008ff189df25d36cc148c5 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * @author  Peter Boros
 * @date    2004/09/13
 * @version $Id$
 * @file    segmenter.h
 * @brief   Query segmenter based on %FSA (%Finite %State %Automaton)
 *
 */

#pragma once

#include <string>
#include <map>
#include <vector>
#include <list>

#include <stdio.h>

#include "fsa.h"
#include "ngram.h"
#include "detector.h"


namespace fsa {

// {{{ class Segmenter

/**
 * @class Segmenter
 * @brief Query segmenter based on %FSA.
 */
class Segmenter {

public:

  // {{{ enum Segmenter::SegmentationMethod

  /**
   * @brief Enumerated type of supported segmentation method IDs
   *
   * The segmentation methods currently supported are the following:
   *   - SEGMENTATION_WEIGHTED - gives the segmentation where the sum
   *     of the scores of nontrivial (more than one word) segments is
   *     the highest
   *   - SEGMENTATION_WEIGHTED_BIASxx - (xx can be 10,20,50 or 100)
   *     gives the segmentation where the sum of the scores of
   *     nontrivial (more than one word) segments is the highest. The
   *     scores are biased based on segment length, xx% extra for each
   *     term over 2
   *   - SEGMENTATION_WEIGHTED_LEFTMOST - picks the segment with
   *     highest score first, if there are several possibilities, picks
   *     the leftmost, then repeats for the rest of the query
   *   - SEGMENTATION_WEIGHTED_RIGHTMOST - picks the segment with
   *     highest score first, if there are several possibilities, picks
   *     the rightmost, then repeats for the rest of the query
   *   - SEGMENTATION_WEIGHTED_LONGEST - picks the segment with
   *     highest score first, if there are several possibilities, picks
   *     the longest, then repeats for the rest of the query
   *   - SEGMENTATION_LEFTMOST_LONGEST - picks the leftmost segment
   *     first, if there are several possibilities, picks the longest,
   *     then repeats for the rest of the query
   *   - SEGMENTATION_LEFTMOST_WEIGHTED - picks the leftmost segment
   *     first, if there are several possibilities, picks the one with
   *     highest score, then repeats for the rest of the query
   *   - SEGMENTATION_RIGHTMOST_LONGEST - picks the rightmost segment
   *     first, if there are several possibilities, picks the longest,
   *     then repeats for the rest of the query
   *   - SEGMENTATION_RIGHTMOST_WEIGHTED - picks the rightmost segment
   *     first, if there are several possibilities, picks the one with
   *     highest score, then repeats for the rest of the query
   *   - SEGMENTATION_LONGEST_WEIGHTED - picks the longest segment
   *     first, if there are several possibilities, picks the one with
   *     highest score, then repeats for the rest of the query
   *   - SEGMENTATION_LONGEST_LEFTMOST - picks the longest segment
   *     first, if there are several possibilities, picks leftmost,
   *     then repeats for the rest of the query
   *   - SEGMENTATION_LONGEST_RIGHTMOST - picks the longest segment
   *     first, if there are several possibilities, picks the rightmost,
   *     then repeats for the rest of the query
   */
  enum SegmentationMethod {
    SEGMENTATION_WEIGHTED,
    SEGMENTATION_WEIGHTED_BIAS10,
    SEGMENTATION_WEIGHTED_BIAS20,
    SEGMENTATION_WEIGHTED_BIAS50,
    SEGMENTATION_WEIGHTED_BIAS100,
    SEGMENTATION_WEIGHTED_LEFTMOST,
    SEGMENTATION_WEIGHTED_RIGHTMOST,
    SEGMENTATION_WEIGHTED_LONGEST,
    SEGMENTATION_LEFTMOST_LONGEST,
    SEGMENTATION_LEFTMOST_WEIGHTED,
    SEGMENTATION_RIGHTMOST_LONGEST,
    SEGMENTATION_RIGHTMOST_WEIGHTED,
    SEGMENTATION_LONGEST_WEIGHTED,
    SEGMENTATION_LONGEST_LEFTMOST,
    SEGMENTATION_LONGEST_RIGHTMOST,
    SEGMENTATION_METHODS };

  // }}}

  // {{{ typedef Segmenter::Segmentation

  /** %Segmentation type */
  using Segmentation = std::list<int>;
  /** Iterator for %segmentation type */
  using SegmentationIterator = std::list<int>::iterator;
  /** Const iterator for %segmentation type */
  using SegmentationConstIterator = std::list<int>::const_iterator;

  // }}}

  // {{{ class Segmenter::Segments

  /**
   * @class Segments
   * @brief Class for storing segmentation results.
   *
   * Class for storing segmentation results. It is a subclass of
   * Detector::Hits, so it can be used directly by a Detector.
   */
  class Segments : public Detector::Hits {

  private:

    // {{{ class Segmenter::Segments::Segment

    /**
     * @class Segment
     * @brief Simple segment class.
     *
     * Simple segment class. A segment is defined by its beginning and
     * end, and it has a connexity. Beginning and end refer to indices
     * in the original text.
     */
    class Segment {

    private:
      unsigned int  _beg;    /**< Beginning of the segment. */
      unsigned int  _end;    /**< End of the segment. */
      unsigned int  _conn;   /**< Connexity of the segment. */

    public:

      /**
       * @brief Default constructor.
       *
       * Null segment at postion zero.
       */
      Segment() noexcept : _beg(0), _end(0), _conn(0) {}

      /**
       * @brief Constructor.
       *
       * @param b Beginning of the segment.
       * @param e End of the segment (the position after the last term).
       * @param c Connexity of the segment.
       */
      Segment(unsigned int b, unsigned int e, unsigned int c) noexcept :
        _beg(b), _end(e), _conn(c) {}

      /**
       * @brief Copy constructor.
       *
       * @param s Segment object to copy.
       */
      Segment(const Segment &s) noexcept : _beg(s._beg), _end(s._end), _conn(s._conn) {}

      /**
       * @brief Destructor.
       */
      ~Segment() = default;

      /**
       * @brief Set the segment parameters.
       *
       * @param b Beginning of the segment.
       * @param e End of the segment (the position after the last term).
       * @param c Connexity of the segment.
       */
      void set(unsigned int b, unsigned int e, unsigned int c)
      {
        _beg=b;
        _end=e;
        _conn=c;
      }

    public:
      /**
       * @brief Get the beginning of the segment.
       *
       * @return Beginning of the segment.
       */
      unsigned int beg()  const { return _beg; }

      /**
       * @brief Get the end of the segment.
       *
       * @return End of the segment. (Position after last term.)
       */
      unsigned int end()  const { return _end; }

      /**
       * @brief Get the length of the segment.
       *
       * @return Length of the segment (number of terms).
       */
      unsigned int len()  const { return _end-_beg; }

      /**
       * @brief Get the connexity of the segment.
       *
       * @return Connexity of the segment.
       */
      unsigned int conn() const { return _conn; }
    };

    // }}}

    // {{{ class Segmenter::Segments::SegmentMap

    /**
     * @class SegmentMap
     * @brief Class for mapping (beg,end) pairs to segment idx.
     */
    class SegmentMap {

    private:
      /** Size of current map. */
      unsigned int       _size;
      /** %Segment map */
      std::vector<int>   _map;

    public:
      /** Default constructor, creates empty map of zero size. */
      SegmentMap() : _size(0), _map() {}

      /**
       * @brief Constructor.
       *
       * Creates an empty map of given size.
       *
       * @param n Map size.
       */
      SegmentMap(unsigned int n) : _size(n+1), _map(_size*_size,-1) {}

      /** Destructor */
      ~SegmentMap() {}

      /**
       * @brief Initialize the map.
       *
       * Initialize the map to an empty map of given size.
       *
       * @param n Map size.
       */
      void init(unsigned int n)
      {
        _size = n+1;
        _map.assign(_size*_size,-1);
      }

      /**
       * @brief Clear the map.
       *
       * Reset the map to an empty map of zero size.
       */
      void clear()
      {
        _size = 0;
        _map.clear();
      }

      /**
       * @brief Get current map size.
       *
       * @return Map size.
       */
      unsigned int size() const { return _size; }

      /**
       * @brief Set an element in the map.
       *
       * @param i Beginning of the segment.
       * @param j End of the segment.
       * @param idx %Segment index.
       */
      void set(unsigned int i, unsigned int j, int idx)
      {
        if(i<_size && j<_size)
          _map[i*_size+j] = idx;
      }

      /**
       * @brief Get an element from the map.
       *
       * @param i Beginning of the segment.
       * @param j End of the segment.
       * @return %Segment index (-1 if segment does not exist).
       */
      int get(unsigned int i, unsigned int j) const
      {
        if(i<_size && j<_size)
          return _map[i*_size+j];
        return -1;
      }

      /**
       * @brief Check if a segment exists.
       *
       * @param i Beginning of the segment.
       * @param j End of the segment.
       * @return True if segment exists.
       */
      bool isValid(unsigned int i, unsigned int j) const
      {
        return i<_size && j<_size && _map[i*_size+j]!=-1;
      }
    };

    // }}}

  private:
    NGram                          _text;             /**< Tokenized text (e.g. query). */
    std::vector<Segment>           _segments;         /**< Detected segments.           */
    SegmentMap                     _map;              /**< Map of segments.             */
    std::vector<Segmentation*>     _segmentation;     /**< Pre-built segmentations.     */


    /**
     * @brief Insert all single term segments.
     *
     * Insert all single term segments as detected with zero
     * connexity. This is important for some of the segentation
     * algorithms.
     */
    void initSingles();

    /**
     * @brief Build a segmentation.
     *
     * @param method %Segmentation method.
     */
    void buildSegmentation(Segmenter::SegmentationMethod method);

    /**
     * @brief Build a segmentation recursively.
     *
     * Some of the segmentation methods are implemented
     * recursively.
     *
     * @param method %Segmentation method.
     * @param segmentation Segmentation object which holds results.
     * @param beg Beginning of the subquery to process.
     * @param end End the subquery to process.
     */
    void buildSegmentationRecursive(Segmenter::SegmentationMethod method,
                                    Segmentation& segmentation,
                                    unsigned int beg,
                                    unsigned int end);

  public:
    Segments();
    ~Segments();

    /**
     * @brief Set input text, and clear all results.
     *
     * @param text Input text.
     */
    void setText(const NGram &text)
    {
      _text.set(text);
      clear();
    }

    /**
     * @brief Set input text, and clear all results.
     *
     * @param text Input text.
     */
    void setText(const std::string &text)
    {
      _text.set(text);
      clear();
    }

    /**
     * @brief Set input text, and clear all results.
     *
     * @param text Input text.
     */
    void setText(const char *text)
    {
      _text.set(text);
      clear();
    }

    /**
     * @brief Get a reference to the input text.
     *
     * Get a reference to the input text. Valid as long as the
     * Segments object is valid and not modified.
     *
     * return Reference to input text.
     */
    const NGram& getText() const { return _text; }

    /**
     * @brief Clear all detected segments and built segmentations.
     */
    void clear();

    /**
     * @brief Insert a detected segment.
     *
     * This method will be called by the detector for each detected
     * segment.
     *
     * @param text Input text.
     * @param from Index of first token.
     * @param length Number of tokens.
     * @param state Final state after detected phrase.
     */
    void add(const NGram &text,
             unsigned int from, int length,
             const FSA::State &state) override
    {
      (void)text;
      unsigned int to=from+length;
      int id=_map.get(from,to);
      if(id==-1){
        _map.set(from,to,_segments.size());
        _segments.push_back(Segment(from,to,state.nData()));
      }
      else{
        _segments[id].set(from,to,state.nData());
      }
    }

    /**
     * @brief Get the size (number of segments).
     *
     * @return Number of segments.
     */
    unsigned int size() const { return _segments.size(); }

    /**
     * @brief Get a segment as a string.
     *
     * @param i %Segment index.
     * @return %Segment string.
     */
    const std::string operator[](unsigned int i) const { return sgm(i); }

    /**
     * @brief Get a segment as a string.
     *
     * @param i %Segment index.
     * @return %Segment string.
     */
    const std::string sgm(unsigned int i) const
    {
      if(i<_segments.size())
        return _text.join(" ",_segments[i].beg(),_segments[i].len());
      return std::string();
    }

    /**
     * @brief Get the beginning of a segment.
     *
     * @param i %Segment index.
     * @return Beginning of the segment.
     */
    unsigned beg(unsigned int i) const
    {
      if(i<_segments.size())
        return _segments[i].beg();
      return 0;
    }

    /**
     * @brief Get the end of a segment.
     *
     * @param i %Segment index.
     * @return End of the segment.
     */
    unsigned end(unsigned int i) const
    {
      if(i<_segments.size())
        return _segments[i].end();
      return 0;
    }

    /**
     * @brief Get the length of a segment.
     *
     * @param i %Segment index.
     * @return Length of the segment.
     */
    unsigned len(unsigned int i) const
    {
      if(i<_segments.size())
        return _segments[i].len();
      return 0;
    }

    /**
     * @brief Get the connexity of a segment.
     *
     * @param i %Segment index.
     * @return Connexity of the segment.
     */
    unsigned conn(unsigned int i) const
    {
      if(i<_segments.size())
        return _segments[i].conn();
      return 0;
    }

    /**
     * @brief Get the a segmentation of the query using the given method.
     *
     * @param method %Segmentation method
     * @return Pointer to the Segmentation object, valid as long as the
     *         Segments object is valid and not modified.
     */
    const Segmenter::Segmentation* segmentation(Segmenter::SegmentationMethod method)
    {
      if(method<SEGMENTATION_WEIGHTED || method>=SEGMENTATION_METHODS)
        method=SEGMENTATION_WEIGHTED;
      if(_segmentation[method]==NULL){
        buildSegmentation(method);
      }
      return _segmentation[method];
    }

  };

  // }}}


private:

  const FSA&    _dictionary;  /**< Dictionary. */
  Detector      _detector;    /**< Detector.   */

  /** Unimplemented private default constructor */
  Segmenter();
  /** Unimplemented private copy constructor */
  Segmenter(const Segmenter&);

public:

  /**
   * @brief Constructor.
   *
   * Create Segmeneter object and initialize dictionary and detector.
   *
   * @param dict Dictionary to use.
   */
  Segmenter(const FSA& dict) : _dictionary(dict), _detector(_dictionary) {}

  /**
   * @brief Constructor.
   *
   * Create Segmeneter object and initialize dictionary and detector.
   *
   * @param dict Dictionary to use.
   */
  Segmenter(const FSA* dict) : _dictionary(*dict), _detector(_dictionary) {}

  /** Destructor */
  ~Segmenter() {}

  /**
   * @brief %Segment a query.
   *
   * @param segments %Segments object, input text already initialized.
   */
  void segment(Segmenter::Segments &segments) const;

  /**
   * @brief %Segment a query.
   *
   * @param text Input text.
   * @param segments %Segments object to hold the results.
   */
  void segment(const NGram &text, Segmenter::Segments &segments) const;

  /**
   * @brief %Segment a query.
   *
   * @param text Input text.
   * @param segments %Segments object to hold the results.
   */
  void segment(const std::string &text, Segmenter::Segments &segments) const;

  /**
   * @brief %Segment a query.
   *
   * @param text Input text.
   * @param segments %Segments object to hold the results.
   */
  void segment(const char *text, Segmenter::Segments &segments) const;

  /**
   * @brief %Segment a query.
   *
   * @param text Input text.
   * @param segments %Segments object to hold the results.
   */
  void segment(const char *text, Segmenter::Segments *segments) const
  {
    segment(text,*segments);
  }

};

// }}}

} // namespace fsa