summaryrefslogtreecommitdiff
path: root/elki/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/heap/UpdatableHeap.java
blob: be089725957381dbdcacd2257dca42814a2c6c51 (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
package de.lmu.ifi.dbs.elki.utilities.datastructures.heap;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2015
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;

import java.util.Comparator;

/**
 * A heap as used in OPTICS that allows updating entries.
 * 
 * @author Erich Schubert
 * 
 * @param <O> object type
 */
public class UpdatableHeap<O> extends Heap<O> {
  /**
   * Constant for "not in heap".
   */
  protected static final int NO_VALUE = Integer.MIN_VALUE;

  /**
   * Constant for "in ties list", for tied heaps.
   */
  protected static final int IN_TIES = -1;

  /**
   * Holds the indices in the heap of each element.
   */
  protected final TObjectIntMap<Object> index = new TObjectIntHashMap<>(100, 0.5f, NO_VALUE);

  /**
   * Simple constructor with default size.
   */
  public UpdatableHeap() {
    super();
  }

  /**
   * Constructor with predefined size.
   * 
   * @param size Size
   */
  public UpdatableHeap(int size) {
    super(size);
  }

  /**
   * Constructor with comparator.
   * 
   * @param comparator Comparator
   */
  public UpdatableHeap(Comparator<? super O> comparator) {
    super(comparator);
  }

  /**
   * Constructor with predefined size and comparator.
   * 
   * @param size Size
   * @param comparator Comparator
   */
  public UpdatableHeap(int size, Comparator<? super O> comparator) {
    super(size, comparator);
  }

  @Override
  public void clear() {
    super.clear();
    index.clear();
  }

  @Override
  public void add(O e) {
    final int pos = index.get(e);
    offerAt(pos, e);
  }

  /**
   * Offer element at the given position.
   * 
   * @param pos Position
   * @param e Element
   */
  protected void offerAt(final int pos, O e) {
    if (pos == NO_VALUE) {
      // resize when needed
      if (size + 1 > queue.length) {
        resize(size + 1);
      }
      index.put(e, size);
      size++;
      heapifyUp(size - 1, e);
      heapModified();
      return;
    } else {
      assert (pos >= 0) : "Unexpected negative position.";
      assert (queue[pos].equals(e));
      // Did the value improve?
      if (comparator == null) {
        @SuppressWarnings("unchecked")
        Comparable<Object> c = (Comparable<Object>) e;
        if (c.compareTo(queue[pos]) >= 0) {
          return;
        }
      } else {
        if (comparator.compare(e, queue[pos]) >= 0) {
          return;
        }
      }
      heapifyUp(pos, e);
      heapModified();
      return;
    }
  }

  @Override
  protected O removeAt(int pos) {
    if (pos < 0 || pos >= size) {
      return null;
    }
    @SuppressWarnings("unchecked")
    final O ret = (O) queue[pos];
    // Replacement object:
    final Object reinsert = queue[size - 1];
    queue[size - 1] = null;
    // Keep heap in sync?
    size--;
    if (comparator != null) {
      if (comparator.compare(ret, reinsert) > 0) {
        heapifyUpComparator(pos, reinsert);
      } else {
        heapifyDownComparator(pos, reinsert);
      }
    } else {
      @SuppressWarnings("unchecked")
      Comparable<Object> comp = (Comparable<Object>) ret;
      if (comp.compareTo(reinsert) > 0) {
        heapifyUpComparable(pos, reinsert);
      } else {
        heapifyDownComparable(pos, reinsert);
      }
    }
    heapModified();
    // Keep index up to date
    index.remove(ret);
    return ret;
  }

  /**
   * Remove the given object from the queue.
   * 
   * @param e Object to remove
   * @return Existing entry
   */
  public O removeObject(O e) {
    int pos = index.get(e);
    if (pos >= 0) {
      return removeAt(pos);
    } else {
      return null;
    }
  }

  @Override
  public O poll() {
    O node = super.poll();
    index.remove(node);
    return node;
  }

  @Override
  public O replaceTopElement(O e) {
    O node = super.replaceTopElement(e);
    index.remove(node);
    return node;
  }

  /**
   * Execute a "Heapify Upwards" aka "SiftUp". Used in insertions.
   * 
   * @param pos insertion position
   * @param elem Element to insert
   */
  @Override
  @SuppressWarnings("unchecked")
  protected void heapifyUpComparable(int pos, Object elem) {
    final Comparable<Object> cur = (Comparable<Object>) elem; // queue[pos];
    while (pos > 0) {
      final int parent = (pos - 1) >>> 1;
      Object par = queue[parent];

      if (cur.compareTo(par) >= 0) {
        break;
      }
      queue[pos] = par;
      index.put(par, pos);
      pos = parent;
    }
    queue[pos] = cur;
    index.put(cur, pos);
  }

  /**
   * Execute a "Heapify Upwards" aka "SiftUp". Used in insertions.
   * 
   * @param pos insertion position
   * @param cur Element to insert
   */
  @Override
  protected void heapifyUpComparator(int pos, Object cur) {
    while (pos > 0) {
      final int parent = (pos - 1) >>> 1;
      Object par = queue[parent];

      if (comparator.compare(cur, par) >= 0) {
        break;
      }
      queue[pos] = par;
      index.put(par, pos);
      pos = parent;
    }
    queue[pos] = cur;
    index.put(cur, pos);
  }

  @SuppressWarnings("unchecked")
  @Override
  protected boolean heapifyDownComparable(final int ipos, Object reinsert) {
    Comparable<Object> cur = (Comparable<Object>) reinsert;
    int pos = ipos;
    final int half = size >>> 1;
    while (pos < half) {
      // Get left child (must exist!)
      int cpos = (pos << 1) + 1;
      Object child = queue[cpos];
      // Test right child, if present
      final int rchild = cpos + 1;
      if (rchild < size) {
        Object right = queue[rchild];
        if (((Comparable<Object>) child).compareTo(right) > 0) {
          cpos = rchild;
          child = right;
        }
      }

      if (cur.compareTo(child) <= 0) {
        break;
      }
      queue[pos] = child;
      index.put(child, pos);
      pos = cpos;
    }
    queue[pos] = cur;
    index.put(cur, pos);
    return (pos != ipos);
  }

  @Override
  protected boolean heapifyDownComparator(final int ipos, Object cur) {
    int pos = ipos;
    final int half = size >>> 1;
    while (pos < half) {
      int min = pos;
      Object best = cur;

      final int lchild = (pos << 1) + 1;
      Object left = queue[lchild];
      if (comparator.compare(best, left) > 0) {
        min = lchild;
        best = left;
      }
      final int rchild = lchild + 1;
      if (rchild < size) {
        Object right = queue[rchild];
        if (comparator.compare(best, right) > 0) {
          min = rchild;
          best = right;
        }
      }
      if (min == pos) {
        break;
      }
      queue[pos] = best;
      index.put(best, pos);
      pos = min;
    }
    queue[pos] = cur;
    index.put(cur, pos);
    return (pos != ipos);
  }
}