Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::TopNHeap Class Reference
Collaboration diagram for duckdb::TopNHeap:

Public Member Functions

 TopNHeap (ClientContext &context, const vector< LogicalType > &payload_types, const vector< BoundOrderByNode > &orders, idx_t limit, idx_t offset)
 TopNHeap (ExecutionContext &context, const vector< LogicalType > &payload_types, const vector< BoundOrderByNode > &orders, idx_t limit, idx_t offset)
 TopNHeap (ClientContext &context, Allocator &allocator, const vector< LogicalType > &payload_types, const vector< BoundOrderByNode > &orders, idx_t limit, idx_t offset)
void Sink (DataChunk &input, optional_ptr< TopNBoundaryValue > boundary_value=nullptr)
void Combine (TopNHeap &other)
void Reduce ()
void Finalize ()
void InitializeScan (TopNScanState &state, bool exclude_offset)
void Scan (TopNScanState &state, DataChunk &chunk, idx_t &pos)
bool CheckBoundaryValues (DataChunk &sort_chunk, DataChunk &payload, TopNBoundaryValue &boundary_val)
void AddSmallHeap (DataChunk &input, Vector &sort_keys_vec)
void AddLargeHeap (DataChunk &input, Vector &sort_keys_vec)
idx_t ReduceThreshold () const
idx_t InitialHeapAllocSize () const

Public Attributes

Allocator & allocator
BufferManager & buffer_manager
ArenaAllocator arena_allocator
unsafe_arena_vector< TopNEntry > heap
const vector< LogicalType > & payload_types
const vector< BoundOrderByNode > & orders
vector< OrderModifiers > modifiers
idx_t limit
idx_t offset
idx_t heap_size
ExpressionExecutor executor
DataChunk sort_chunk
DataChunk heap_data
DataChunk payload_chunk
DataChunk sort_keys
StringHeap sort_key_heap
SelectionVector matching_sel
DataChunk compare_chunk
DataChunk boundary_values
 Cached global boundary value as a set of constant vectors.
string boundary_val
 Cached global boundary value in sort-key format.
SelectionVector final_sel
SelectionVector true_sel
SelectionVector false_sel
SelectionVector new_remaining_sel

Private Member Functions

bool EntryShouldBeAdded (const string_t &sort_key)
void AddEntryToHeap (const TopNEntry &entry)

Constructor & Destructor Documentation

◆ TopNHeap() [1/3]

duckdb::TopNHeap::TopNHeap ( ClientContext & context,
const vector< LogicalType > & payload_types,
const vector< BoundOrderByNode > & orders,
idx_t limit,
idx_t offset )
191042 : TopNHeap(context, BufferAllocator::Get(context), payload_types, orders, limit, offset) {
191043}

◆ TopNHeap() [2/3]

duckdb::TopNHeap::TopNHeap ( ExecutionContext & context,
const vector< LogicalType > & payload_types,
const vector< BoundOrderByNode > & orders,
idx_t limit,
idx_t offset )
191047 : TopNHeap(context.client, BufferAllocator::Get(context.client), payload_types, orders, limit, offset) {
191048}

◆ TopNHeap() [3/3]

duckdb::TopNHeap::TopNHeap ( ClientContext & context,
Allocator & allocator,
const vector< LogicalType > & payload_types,
const vector< BoundOrderByNode > & orders,
idx_t limit,
idx_t offset )
191017 : allocator(allocator), buffer_manager(BufferManager::GetBufferManager(context)), arena_allocator(allocator),
191018 heap(arena_allocator), payload_types(payload_types_p), orders(orders_p), limit(limit), offset(offset),
191019 heap_size(limit + offset), executor(context), sort_key_heap(allocator), matching_sel(STANDARD_VECTOR_SIZE),
191020 final_sel(STANDARD_VECTOR_SIZE), true_sel(STANDARD_VECTOR_SIZE), false_sel(STANDARD_VECTOR_SIZE),
191021 new_remaining_sel(STANDARD_VECTOR_SIZE) {
191022 // initialize the executor and the sort_chunk
191023 vector<LogicalType> sort_types;
191024 for (auto &order : orders) {
191025 auto &expr = order.expression;
191026 sort_types.push_back(expr->return_type);
191027 executor.AddExpression(*expr);
191028 modifiers.emplace_back(order.type, order.null_order);
191029 }
191030 heap.reserve(InitialHeapAllocSize());
191031 vector<LogicalType> sort_keys_type {LogicalType::BLOB};
191032 sort_keys.Initialize(allocator, sort_keys_type);
191033 heap_data.Initialize(allocator, payload_types, InitialHeapAllocSize());
191034 payload_chunk.Initialize(allocator, payload_types);
191035 sort_chunk.Initialize(allocator, sort_types);
191036 compare_chunk.Initialize(allocator, sort_types);
191037 boundary_values.Initialize(allocator, sort_types);
191038}
DataChunk boundary_values
Cached global boundary value as a set of constant vectors.
Definition duckdb.cpp:190958

Member Function Documentation

◆ Sink()

void duckdb::TopNHeap::Sink ( DataChunk & input,
optional_ptr< TopNBoundaryValue > boundary_value = nullptr )
191199 {
191200 static constexpr idx_t SMALL_HEAP_THRESHOLD = 100;
191201
191202 // compute the ordering values for the new chunk
191203 sort_chunk.Reset();
191204 executor.Execute(input, sort_chunk);
191205
191206 if (global_boundary) {
191207 // if we have a global boundary value check which rows pass before doing anything
191208 if (!CheckBoundaryValues(sort_chunk, input, *global_boundary)) {
191209 // nothing in this chunk can be in the final result
191210 return;
191211 }
191212 }
191213
191214 // construct the sort key from the sort chunk
191215 sort_keys.Reset();
191216 auto &sort_keys_vec = sort_keys.data[0];
191217 CreateSortKeyHelpers::CreateSortKey(sort_chunk, modifiers, sort_keys_vec);
191218
191219 if (heap_size <= SMALL_HEAP_THRESHOLD) {
191220 AddSmallHeap(input, sort_keys_vec);
191221 } else {
191222 AddLargeHeap(input, sort_keys_vec);
191223 }
191224
191225 // if we modified the heap we might be able to update the global boundary
191226 // note that the global boundary only applies to FULL heaps
191227 if (heap.size() >= heap_size && global_boundary) {
191228 global_boundary->UpdateValue(heap.front().sort_key);
191229 }
191230}
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ Combine()

void duckdb::TopNHeap::Combine ( TopNHeap & other)
191232 {
191233 // "other" is sorted at this point
191234 idx_t match_count = 0;
191235 // merge the heap of other into this
191236 for (idx_t i = 0; i < other.heap.size(); i++) {
191237 // heap is full - check the latest entry
191238 auto &other_entry = other.heap[i];
191239 auto &sort_key = other_entry.sort_key;
191240 if (!EntryShouldBeAdded(sort_key)) {
191241 break; // We can break out of the loop here since we sorted the heap
191242 }
191243 // add this entry
191244 TopNEntry new_entry;
191245 new_entry.sort_key = sort_key.IsInlined() ? sort_key : sort_key_heap.AddBlob(sort_key);
191246 new_entry.index = heap_data.size() + match_count;
191247 AddEntryToHeap(new_entry);
191248
191249 matching_sel.set_index(match_count++, other_entry.index);
191250 if (match_count >= STANDARD_VECTOR_SIZE) {
191251 // flush
191252 heap_data.Append(other.heap_data, true, &matching_sel, match_count);
191253 match_count = 0;
191254 }
191255 }
191256 if (match_count > 0) {
191257 // flush
191258 heap_data.Append(other.heap_data, true, &matching_sel, match_count);
191259 match_count = 0;
191260 }
191261 Reduce();
191262}

◆ Reduce()

void duckdb::TopNHeap::Reduce ( )
191268 {
191269 if (heap_data.size() < ReduceThreshold()) {
191270 // only reduce when we pass the reduce threshold
191271 return;
191272 }
191273 // we have too many values in the heap - reduce them
191274 StringHeap new_sort_heap;
191275 DataChunk new_heap_data;
191276 new_heap_data.Initialize(allocator, payload_types, heap.size());
191277
191278 SelectionVector new_payload_sel(heap.size());
191279 for (idx_t i = 0; i < heap.size(); i++) {
191280 auto &entry = heap[i];
191281 // the entry is not inlined - move the sort key to the new sort heap
191282 if (!entry.sort_key.IsInlined()) {
191283 entry.sort_key = new_sort_heap.AddBlob(entry.sort_key);
191284 }
191285 // move this heap entry to position X in the payload chunk
191286 new_payload_sel.set_index(i, entry.index);
191287 entry.index = i;
191288 }
191289
191290 // copy over the data from the current payload chunk to the new payload chunk
191291 new_heap_data.Slice(heap_data, new_payload_sel, heap.size());
191292 new_heap_data.Flatten();
191293
191294 sort_key_heap.Destroy();
191295 sort_key_heap.Move(new_sort_heap);
191296 heap_data.Reference(new_heap_data);
191297}
DUCKDB_API void Initialize(ClientContext &context, const vector< LogicalType > &types, idx_t capacity=STANDARD_VECTOR_SIZE)
Definition duckdb.cpp:116791
DUCKDB_API void Flatten()
Turn all the vectors from the chunk into flat vectors.
Definition duckdb.cpp:116989

◆ Finalize()

void duckdb::TopNHeap::Finalize ( )
191264 {
191265 std::sort(heap.begin(), heap.end());
191266}

◆ InitializeScan()

void duckdb::TopNHeap::InitializeScan ( TopNScanState & state,
bool exclude_offset )
191299 {
191300 auto heap_copy = heap;
191301 state.scan_order.resize(heap_copy.size());
191302
191303 // we sorted the heap in Finalize(), so we can sequentially here
191304 // we do this because sorting the heap is much more efficient than popping one by one
191305 for (idx_t i = 0; i < heap_copy.size(); i++) {
191306 state.scan_order[i] = UnsafeNumericCast<sel_t>(heap_copy[i].index);
191307 }
191308
191309 state.pos = exclude_offset ? offset : 0;
191310}

◆ Scan()

void duckdb::TopNHeap::Scan ( TopNScanState & state,
DataChunk & chunk,
idx_t & pos )
191312 {
191313 if (pos >= state.scan_order.size()) {
191314 return;
191315 }
191316 SelectionVector sel(state.scan_order.data() + pos);
191317 idx_t count = MinValue<idx_t>(STANDARD_VECTOR_SIZE, state.scan_order.size() - pos);
191318 pos += STANDARD_VECTOR_SIZE;
191319
191320 chunk.Reset();
191321 chunk.Slice(heap_data, sel, count);
191322}
DUCKDB_API void Reset()
Definition duckdb.cpp:116840

◆ CheckBoundaryValues()

bool duckdb::TopNHeap::CheckBoundaryValues ( DataChunk & sort_chunk,
DataChunk & payload,
TopNBoundaryValue & boundary_val )
191119 {
191120 // get the global boundary value
191121 auto current_boundary_val = global_boundary.GetBoundaryValue();
191122 if (current_boundary_val.empty()) {
191123 // no boundary value (yet) - don't do anything
191124 return true;
191125 }
191126 if (current_boundary_val != boundary_val) {
191127 // new boundary value - decode
191128 boundary_val = std::move(current_boundary_val);
191129 boundary_values.Reset();
191130 CreateSortKeyHelpers::DecodeSortKey(string_t(boundary_val), boundary_values, 0, modifiers);
191131 for (auto &col : boundary_values.data) {
191132 col.SetVectorType(VectorType::CONSTANT_VECTOR);
191133 }
191134 }
191135 boundary_values.SetCardinality(sort_chunk.size());
191136
191137 // we have boundary values
191138 // from these boundary values, determine which values we should insert (if any)
191139 idx_t final_count = 0;
191140
191141 SelectionVector remaining_sel(nullptr);
191142 idx_t remaining_count = sort_chunk.size();
191143 sort_chunk.Flatten();
191144 for (idx_t i = 0; i < orders.size(); i++) {
191145 if (remaining_sel.data()) {
191146 compare_chunk.data[i].Slice(sort_chunk.data[i], remaining_sel, remaining_count);
191147 } else {
191148 compare_chunk.data[i].Reference(sort_chunk.data[i]);
191149 }
191150 bool is_last = i + 1 == orders.size();
191151 idx_t true_count;
191152 if (orders[i].null_order == OrderByNullType::NULLS_LAST) {
191153 if (orders[i].type == OrderType::ASCENDING) {
191154 true_count = VectorOperations::DistinctLessThan(compare_chunk.data[i], boundary_values.data[i],
191155 &remaining_sel, remaining_count, &true_sel, &false_sel);
191156 } else {
191157 true_count = VectorOperations::DistinctGreaterThanNullsFirst(compare_chunk.data[i],
191158 boundary_values.data[i], &remaining_sel,
191159 remaining_count, &true_sel, &false_sel);
191160 }
191161 } else {
191162 D_ASSERT(orders[i].null_order == OrderByNullType::NULLS_FIRST);
191163 if (orders[i].type == OrderType::ASCENDING) {
191164 true_count = VectorOperations::DistinctLessThanNullsFirst(compare_chunk.data[i],
191165 boundary_values.data[i], &remaining_sel,
191166 remaining_count, &true_sel, &false_sel);
191167 } else {
191168 true_count =
191169 VectorOperations::DistinctGreaterThan(compare_chunk.data[i], boundary_values.data[i],
191170 &remaining_sel, remaining_count, &true_sel, &false_sel);
191171 }
191172 }
191173
191174 if (true_count > 0) {
191175 memcpy(final_sel.data() + final_count, true_sel.data(), true_count * sizeof(sel_t));
191176 final_count += true_count;
191177 }
191178 idx_t false_count = remaining_count - true_count;
191179 if (!is_last && false_count > 0) {
191180 // check what we should continue to check
191181 compare_chunk.data[i].Slice(sort_chunk.data[i], false_sel, false_count);
191182 remaining_count = VectorOperations::NotDistinctFrom(compare_chunk.data[i], boundary_values.data[i],
191183 &false_sel, false_count, &new_remaining_sel, nullptr);
191184 remaining_sel.Initialize(new_remaining_sel);
191185 } else {
191186 break;
191187 }
191188 }
191189 if (final_count == 0) {
191190 return false;
191191 }
191192 if (final_count < sort_chunk.size()) {
191193 sort_chunk.Slice(final_sel, final_count);
191194 payload.Slice(final_sel, final_count);
191195 }
191196 return true;
191197}
string boundary_val
Cached global boundary value in sort-key format.
Definition duckdb.cpp:190960
uint32_t sel_t
Type used for the selection vector.
Definition duckdb.hpp:251

◆ AddSmallHeap()

void duckdb::TopNHeap::AddSmallHeap ( DataChunk & input,
Vector & sort_keys_vec )
191050 {
191051 // insert the sort keys into the priority queue
191052 constexpr idx_t BASE_INDEX = NumericLimits<uint32_t>::Maximum();
191053
191054 bool any_added = false;
191055 auto sort_key_values = FlatVector::GetData<string_t>(sort_keys_vec);
191056 for (idx_t r = 0; r < input.size(); r++) {
191057 auto &sort_key = sort_key_values[r];
191058 if (!EntryShouldBeAdded(sort_key)) {
191059 continue;
191060 }
191061 // replace the previous top entry with the new entry
191062 TopNEntry entry;
191063 entry.sort_key = sort_key;
191064 entry.index = BASE_INDEX + r;
191065 AddEntryToHeap(entry);
191066 any_added = true;
191067 }
191068 if (!any_added) {
191069 // early-out: no matches
191070 return;
191071 }
191072
191073 // for all matching entries we need to copy over the corresponding payload values
191074 idx_t match_count = 0;
191075 for (auto &entry : heap) {
191076 if (entry.index < BASE_INDEX) {
191077 continue;
191078 }
191079 // this entry was added in this chunk
191080 // if not inlined - copy over the string to the string heap
191081 if (!entry.sort_key.IsInlined()) {
191082 entry.sort_key = sort_key_heap.AddBlob(entry.sort_key);
191083 }
191084 // to finalize the addition of this entry we need to move over the payload data
191085 matching_sel.set_index(match_count, entry.index - BASE_INDEX);
191086 entry.index = heap_data.size() + match_count;
191087 match_count++;
191088 }
191089
191090 // copy over the input rows to the payload chunk
191091 heap_data.Append(input, true, &matching_sel, match_count);
191092}

◆ AddLargeHeap()

void duckdb::TopNHeap::AddLargeHeap ( DataChunk & input,
Vector & sort_keys_vec )
191094 {
191095 auto sort_key_values = FlatVector::GetData<string_t>(sort_keys_vec);
191096 idx_t base_index = heap_data.size();
191097 idx_t match_count = 0;
191098 for (idx_t r = 0; r < input.size(); r++) {
191099 auto &sort_key = sort_key_values[r];
191100 if (!EntryShouldBeAdded(sort_key)) {
191101 continue;
191102 }
191103 // replace the previous top entry with the new entry
191104 TopNEntry entry;
191105 entry.sort_key = sort_key.IsInlined() ? sort_key : sort_key_heap.AddBlob(sort_key);
191106 entry.index = base_index + match_count;
191107 AddEntryToHeap(entry);
191108 matching_sel.set_index(match_count++, r);
191109 }
191110 if (match_count == 0) {
191111 // early-out: no matches
191112 return;
191113 }
191114
191115 // copy over the input rows to the payload chunk
191116 heap_data.Append(input, true, &matching_sel, match_count);
191117}

◆ ReduceThreshold()

idx_t duckdb::TopNHeap::ReduceThreshold ( ) const
inline
190980 {
190981 return MaxValue<idx_t>(STANDARD_VECTOR_SIZE * 5ULL, 2ULL * heap_size);
190982 }

◆ InitialHeapAllocSize()

idx_t duckdb::TopNHeap::InitialHeapAllocSize ( ) const
inline
190984 {
190985 return MinValue<idx_t>(STANDARD_VECTOR_SIZE * 100ULL, ReduceThreshold()) + STANDARD_VECTOR_SIZE;
190986 }

◆ EntryShouldBeAdded()

bool duckdb::TopNHeap::EntryShouldBeAdded ( const string_t & sort_key)
inlineprivate
190989 {
190990 if (heap.size() < heap_size) {
190991 // heap is full - check the latest entry
190992 return true;
190993 }
190994 if (sort_key < heap.front().sort_key) {
190995 // sort key is smaller than current max value
190996 return true;
190997 }
190998 // heap is full and there is no room for the entry
190999 return false;
191000 }

◆ AddEntryToHeap()

void duckdb::TopNHeap::AddEntryToHeap ( const TopNEntry & entry)
inlineprivate
191002 {
191003 if (heap.size() >= heap_size) {
191004 std::pop_heap(heap.begin(), heap.end());
191005 heap.pop_back();
191006 }
191007 heap.push_back(entry);
191008 std::push_heap(heap.begin(), heap.end());
191009 }

The documentation for this class was generated from the following file: