summaryrefslogtreecommitdiff
path: root/sa-extract/csuf.pyx
blob: 64c447882734cbda24bf7acf6cdb6350f86a5389 (plain)
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
# csuf.pyx
# Defines suffix arrays that can be directly written to/read from disk in binary format
# Adam Lopez <alopez@cs.umd.edu>

import sys
import log
import cdat
import cintlist
import monitor

from libc.stdio cimport FILE, fclose, fopen

cdef class SuffixArray:

  def __init__(self, filename, from_binary=False):
    self.darray = cdat.DataArray()
    self.sa = cintlist.CIntList()
    self.ha = cintlist.CIntList()
    if from_binary:
      self.read_binary(filename)
    else:
      self.read_text(filename)


  def __getitem__(self, i):
    return self.sa.arr[i]


  def getSentId(self, i):
    return self.darray.getSentId(i)


  def getSent(self, i):
    return self.darray.getSent(i)


  def getSentPos(self, loc):
    return self.darray.getSentPos(loc)

  def read_text(self, filename):
    '''Constructs suffix array using the algorithm
    of Larsson & Sadahkane (1999)'''
    cdef int V, N, i, j, h, a_i, n, current_run, skip
    cdef cintlist.CIntList isa, word_count

    self.darray = cdat.DataArray(filename, from_binary=False, use_sent_id=True)
    N = len(self.darray)
    V = len(self.darray.id2word)

    self.sa = cintlist.CIntList(initial_len=N)
    self.ha = cintlist.CIntList(initial_len=V+1)

    isa = cintlist.CIntList(initial_len=N)
    word_count = cintlist.CIntList(initial_len=V+1)

    '''Step 1: bucket sort data'''
    sort_start_time = monitor.cpu()
    start_time = sort_start_time
    for i from 0 <= i < N:
      a_i = self.darray.data.arr[i]
      word_count.arr[a_i] = word_count.arr[a_i] + 1

    n = 0
    for i from 0 <= i < V+1:
      self.ha.arr[i] = n
      n = n + word_count.arr[i]
      word_count.arr[i] = 0

    for i from 0 <= i < N:
      a_i = self.darray.data.arr[i]
      self.sa.arr[self.ha.arr[a_i] + word_count.arr[a_i]] = i
      isa.arr[i] = self.ha.arr[a_i + 1] - 1 # bucket pointer is last index in bucket
      word_count.arr[a_i] = word_count.arr[a_i] + 1

    '''Determine size of initial runs'''
    current_run = 0
    for i from 0 <= i < V+1:
      if i < V and self.ha.arr[i+1] - self.ha.arr[i] == 1:
        current_run = current_run + 1
      else:
        if current_run > 0:
          self.sa.arr[self.ha.arr[i] - current_run] = -current_run
          current_run = 0

    sys.stderr.write("  Bucket sort took %f seconds\n" % (monitor.cpu() - sort_start_time))

    '''Step 2: prefix-doubling sort'''
    h = 1
    while self.sa.arr[0] != -N:
      sort_start_time = monitor.cpu()
      sys.stderr.write("  Refining, sort depth = %d\n" % (h,))
      i = 0
      skip = 0
      while i < N:
        if self.sa.arr[i] < 0:
          #sys.stderr.write("Skip from %d to %d\n" % (i, i-self.sa.arr[i]-1))
          skip = skip + self.sa.arr[i]
          i = i - self.sa.arr[i]
        else:
          if skip < 0:
            self.sa.arr[i+skip] = skip
            skip = 0
          j = isa.arr[self.sa.arr[i]]
          #sys.stderr.write("Process from %d to %d (%d, %d, %d)\n" % (i, j, self.sa.arr[i], self.darray.data.arr[self.sa.arr[i]], isa.arr[self.sa.arr[i]]))
          self.q3sort(i, j, h, isa)
          i = j+1
      if skip < 0:
        self.sa.arr[i+skip] = skip
      h = h * 2
      sys.stderr.write("  Refinement took %f seconds\n" % (monitor.cpu() - sort_start_time))

    '''Step 3: read off suffix array from inverse suffix array''' 
    sys.stderr.write("  Finalizing sort...\n")
    for i from 0 <= i < N:
      j = isa.arr[i]
      self.sa.arr[j] = i
    sys.stderr.write("Suffix array construction took %f seconds\n" % (monitor.cpu() - start_time))

  def q3sort(self, int i, int j, int h, cintlist.CIntList isa, pad=""):
    '''This is a ternary quicksort. It divides the array into
    three partitions: items less than the pivot, items equal
    to pivot, and items greater than pivot.  The first and last
    of these partitions are then recursively sorted'''
    cdef int k, midpoint, pval, phead, ptail, tmp

    if j-i < -1:
      raise Exception("Unexpected condition found in q3sort: sort from %d to %d" % (i,j))
    if j-i == -1:  # recursive base case -- empty interval
      return
    if (j-i == 0):  # recursive base case -- singleton interval
      isa.arr[self.sa.arr[i]] = i
      self.sa.arr[i] = -1
      return 

    # NOTE: choosing the first item as a pivot value resulted in 
    # stack overflow for some very large buckets.  I think there
    # is a natural bias towards order due the way the word ids are
    # assigned; thus this resulted in the range to the left of the 
    # pivot being nearly empty.   Therefore, choose the middle item.
    # If the method of assigning word_id's is changed, this method
    # may need to be reconsidered as well.
    midpoint = (i+j)/2
    pval = isa.arr[self.sa.arr[midpoint] + h]
    if i != midpoint:
      tmp = self.sa.arr[midpoint]
      self.sa.arr[midpoint] = self.sa.arr[i]
      self.sa.arr[i] = tmp
    phead = i
    ptail = i

    # find the three partitions.  phead marks the first element
    # of the middle partition, and ptail marks the last element
    for k from i+1 <= k < j+1:
      if isa.arr[self.sa.arr[k] + h] < pval:
        if k > ptail+1:
          tmp = self.sa.arr[phead]
          self.sa.arr[phead] = self.sa.arr[k]
          self.sa.arr[k] = self.sa.arr[ptail+1]
          self.sa.arr[ptail+1] = tmp
        else: # k == ptail+1
          tmp = self.sa.arr[phead]
          self.sa.arr[phead] = self.sa.arr[k]
          self.sa.arr[k] = tmp
        phead = phead + 1
        ptail = ptail + 1
      else:
        if isa.arr[self.sa.arr[k] + h] == pval:
          if k > ptail+1:
            tmp = self.sa.arr[ptail+1]
            self.sa.arr[ptail+1] = self.sa.arr[k]
            self.sa.arr[k] = tmp
          ptail = ptail + 1

    # recursively sort smaller suffixes
    self.q3sort(i, phead-1, h, isa, pad+"  ")

    # update suffixes with pivot value
    # corresponds to update_group function in Larsson & Sadakane
    for k from phead <= k < ptail+1:
      isa.arr[self.sa.arr[k]] = ptail
    if phead == ptail:
      self.sa.arr[phead] = -1

    # recursively sort larger suffixes
    self.q3sort(ptail+1, j, h, isa, pad+"  ")


  def write_text(self, filename):
    self.darray.write_text(filename)


  def read_binary(self, filename):
    cdef FILE *f
    cdef bytes bfilename = filename
    cdef char* cfilename = bfilename
    f = fopen(cfilename, "r")
    self.darray.read_handle(f)
    self.sa.read_handle(f)
    self.ha.read_handle(f)
    fclose(f)


  def write_binary(self, filename):
    cdef FILE* f
    cdef bytes bfilename = filename
    cdef char* cfilename = bfilename
    f = fopen(cfilename, "w")
    self.darray.write_handle(f)
    self.sa.write_handle(f)
    self.ha.write_handle(f)
    fclose(f)


  def write_enhanced(self, filename):
    f = open(filename, "w")
    self.darray.write_enhanced_handle(f)
    for a_i in self.sa:
      f.write("%d " % a_i)
    f.write("\n")
    for w_i in self.ha:
      f.write("%d " % w_i)
    f.write("\n")
    f.close()


  cdef __search_high(self, word_id, offset, low, high):
    cdef int midpoint

    if low >= high:
      return high
    midpoint = (high + low) / 2
    if self.darray.data.arr[self.sa.arr[midpoint] + offset] == word_id:
      return self.__search_high(word_id, offset, midpoint+1, high)
    else:
      return self.__search_high(word_id, offset, low, midpoint)


  cdef __search_low(self, int word_id, int offset, int low, int high):
    cdef int midpoint

    if low >= high:
      return high
    midpoint = (high + low) / 2
    if self.darray.data.arr[self.sa.arr[midpoint] + offset] == word_id:
      return self.__search_low(word_id, offset, low, midpoint)
    else:
      return self.__search_low(word_id, offset, midpoint+1, high)


  cdef __get_range(self, int word_id, int offset, int low, int high, int midpoint):
    return (self.__search_low(word_id, offset, low, midpoint),
        self.__search_high(word_id, offset, midpoint, high))


  cdef __lookup_helper(self, int word_id, int offset, int low, int high):
    cdef int midpoint

    if offset == 0:
      return (self.ha.arr[word_id], self.ha.arr[word_id+1])
    if low >= high:
      return None

    midpoint = (high + low) / 2
    if self.darray.data.arr[self.sa.arr[midpoint] + offset] == word_id:
      return self.__get_range(word_id, offset, low, high, midpoint)
    if self.darray.data.arr[self.sa.arr[midpoint] + offset] > word_id:
      return self.__lookup_helper(word_id, offset, low, midpoint)
    else:
      return self.__lookup_helper(word_id, offset, midpoint+1, high)


  def lookup(self, word, offset, int low, int high):
    if low == -1: 
      low = 0
    if high == -1:
      high = len(self.sa)
    if word in self.darray.word2id:
      word_id = self.darray.word2id[word]
      return self.__lookup_helper(word_id, offset, low, high)
    else:
      return None



  def print_sa(self, isa):
    '''Slow; Use only in case of emergency'''
    cdef int i, j, k, N
    cdef cintlist.CIntList tmp_sa

    N = len(self.sa)
    for i from 0 <= i < N:
      sys.stderr.write("%2d " % i)
    sys.stderr.write("\n")
    for i from 0 <= i < N:
      sys.stderr.write("%2d " % self.darray.data.arr[i])
    sys.stderr.write("\n")
    for i from 0 <= i < N:
      sys.stderr.write("%2d " % isa.arr[i])
    sys.stderr.write("\n\n\n")

    # Recover partially sorted array
    tmp_sa = cintlist.CIntList(initial_len=N)
    for i from 0 <= i < N:
      j = isa.arr[i]
      tmp_sa.arr[j] = i
    for i from 0 <= i < N:
      if self.sa.arr[i] > 0:
        tmp_sa.arr[i] = self.sa.arr[i]

    for i from 0 <= i < N:
      j = tmp_sa.arr[i]
      sys.stderr.write("%2d %2d | " % (i, self.sa.arr[i]))
      for k from j <= k < N:
        sys.stderr.write("%2d " % self.darray.data.arr[k])
      sys.stderr.write("\n")
    sys.stderr.write("\n")