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::ReservoirSample Class Reference
Inheritance diagram for duckdb::ReservoirSample:
Collaboration diagram for duckdb::ReservoirSample:

Public Member Functions

 ReservoirSample (Allocator &allocator, idx_t sample_count, int64_t seed=1)
 ReservoirSample (idx_t sample_count, unique_ptr< ReservoirChunk >=nullptr)
void EvictOverBudgetSamples ()
 methods used to help with serializing and deserializing
void ExpandSerializedSample ()
SamplingState GetSamplingState () const
void Vacuum ()
 Vacuum the Reservoir Sample so it throws away tuples that are not in the reservoir weights or in the selection vector.
void ConvertToReservoirSample ()
 Transform To sample based on reservoir sampling paper.
template<typename T>
T GetReservoirChunkCapacity () const
 Get the capactiy of the data chunk reserved for storing samples.
unique_ptr< BlockingSample > Copy () const override
 If for_serialization=true then the sample_chunk is not padded with extra spaces for future sampling values.
idx_t FillReservoir (DataChunk &chunk)
 create the first chunk called by AddToReservoir()
void AddToReservoir (DataChunk &input) override
 Add a chunk of data to the sample.
void Merge (unique_ptr< BlockingSample > other)
 Merge two Reservoir Samples. Other must be a reservoir sample.
void ShuffleSel (SelectionVector &sel, idx_t range, idx_t size) const
void UpdateSampleAppend (DataChunk &this_, DataChunk &other, SelectionVector &other_sel, idx_t append_count) const
 Update the sample by pushing new sample rows to the end of the sample_chunk. The new sample rows are the tuples rows resulting from applying sel to other.
idx_t GetTuplesSeen () const
idx_t NumSamplesCollected () const
idx_t GetActiveSampleCount () const
DataChunk & Chunk ()
unique_ptr< DataChunk > GetChunk () override
 Fetches a chunk from the sample. Note that this method is destructive and should only be used after the sample is completely built.
void Destroy () override
void Finalize () override
void Verify ()
idx_t GetSampleCount ()
SelectionVectorHelper GetReplacementIndexes (idx_t sample_chunk_offset, idx_t theoretical_chunk_length)
 Get indexes from current sample that can be replaced.
void Serialize (Serializer &serializer) const override
Public Member Functions inherited from duckdb::BlockingSample
 BlockingSample (int64_t seed=-1)
std::pair< double, idx_t > PopFromWeightQueue ()
 Helper functions needed to merge two reservoirs while respecting weights of sampled rows.
double GetMinWeightThreshold ()
idx_t GetPriorityQueueSize ()
template<class TARGET>
TARGET & Cast ()
template<class TARGET>
const TARGET & Cast () const

Static Public Member Functions

static bool ValidSampleType (const LogicalType &type)
static unique_ptr< BlockingSample > Deserialize (Deserializer &deserializer)
Static Public Member Functions inherited from duckdb::BlockingSample
static unique_ptr< BlockingSample > Deserialize (Deserializer &deserializer)

Static Public Attributes

static constexpr const SampleType TYPE = SampleType::RESERVOIR_SAMPLE
static constexpr idx_t FIXED_SAMPLE_SIZE_MULTIPLIER = 10
static constexpr idx_t FAST_TO_SLOW_THRESHOLD = MinValue<idx_t>(STANDARD_VECTOR_SIZE, 60)
static constexpr double SAVE_PERCENTAGE = 0.01
Static Public Attributes inherited from duckdb::BlockingSample
static constexpr const SampleType TYPE = SampleType::BLOCKING_SAMPLE

Private Member Functions

void NormalizeWeights ()
SelectionVectorHelper GetReplacementIndexesSlow (const idx_t sample_chunk_offset, const idx_t chunk_length)
SelectionVectorHelper GetReplacementIndexesFast (const idx_t sample_chunk_offset, const idx_t chunk_length)
void SimpleMerge (ReservoirSample &other)
void WeightedMerge (ReservoirSample &other_sample)
unique_ptr< ReservoirChunk > CreateNewSampleChunk (vector< LogicalType > &types, idx_t size) const
vector< uint32_t > GetRandomizedVector (uint32_t range, uint32_t size) const

Private Attributes

idx_t sample_count
Allocator & allocator
unique_ptr< ReservoirChunk > reservoir_chunk
bool stats_sample
SelectionVector sel
idx_t sel_size

Additional Inherited Members

Public Attributes inherited from duckdb::BlockingSample
unique_ptr< BaseReservoirSampling > base_reservoir_sample
SampleType type
 The sample type.
bool destroyed
 has the sample been destroyed due to updates to the referenced table

Constructor & Destructor Documentation

◆ ReservoirSample() [1/2]

duckdb::ReservoirSample::ReservoirSample ( Allocator & allocator,
idx_t sample_count,
int64_t seed = 1 )
208216 : BlockingSample(seed), sample_count(sample_count), allocator(allocator) {
208217 base_reservoir_sample = make_uniq<BaseReservoirSampling>(seed);
208218 type = SampleType::RESERVOIR_SAMPLE;
208219 reservoir_chunk = nullptr;
208220 stats_sample = false;
208221 sel = SelectionVector(sample_count);
208222 sel_size = 0;
208223}
SampleType type
The sample type.
Definition duckdb.hpp:47809

◆ ReservoirSample() [2/2]

duckdb::ReservoirSample::ReservoirSample ( idx_t sample_count,
unique_ptr< ReservoirChunk > reservoir_chunk = nullptr )
explicit
208202 : ReservoirSample(Allocator::DefaultAllocator(), sample_count, 1) {
208203 if (reservoir_chunk) {
208204 this->reservoir_chunk = std::move(reservoir_chunk);
208205 sel_size = this->reservoir_chunk->chunk.size();
208206 sel = SelectionVector(FIXED_SAMPLE_SIZE);
208207 for (idx_t i = 0; i < sel_size; i++) {
208208 sel.set_index(i, i);
208209 }
208210 ExpandSerializedSample();
208211 }
208212 stats_sample = true;
208213}
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

Member Function Documentation

◆ EvictOverBudgetSamples()

void duckdb::ReservoirSample::EvictOverBudgetSamples ( )

methods used to help with serializing and deserializing

208631 {
208632 Verify();
208633 if (!reservoir_chunk || destroyed) {
208634 return;
208635 }
208636
208637 // since this is for serialization, we really need to make sure keep a
208638 // minimum of 1% of the rows or 2048 rows
208639 idx_t num_samples_to_keep =
208640 MinValue<idx_t>(FIXED_SAMPLE_SIZE, static_cast<idx_t>(SAVE_PERCENTAGE * static_cast<double>(GetTuplesSeen())));
208641
208642 if (num_samples_to_keep <= 0) {
208643 reservoir_chunk->chunk.SetCardinality(0);
208644 return;
208645 }
208646
208647 if (num_samples_to_keep == sample_count) {
208648 return;
208649 }
208650
208651 // if we over sampled, make sure we only keep the highest percentage samples
208652 std::unordered_set<idx_t> selections_to_delete;
208653
208654 while (num_samples_to_keep < GetPriorityQueueSize()) {
208655 auto top = PopFromWeightQueue();
208656 D_ASSERT(top.second < sel_size);
208657 selections_to_delete.emplace(top.second);
208658 }
208659
208660 // set up reservoir chunk for the reservoir sample
208661 D_ASSERT(reservoir_chunk->chunk.size() <= sample_count);
208662 // create a new sample chunk to store new samples
208663 auto types = reservoir_chunk->chunk.GetTypes();
208664 D_ASSERT(num_samples_to_keep <= sample_count);
208665 D_ASSERT(stats_sample);
208666 D_ASSERT(sample_count == FIXED_SAMPLE_SIZE);
208667 auto new_reservoir_chunk = CreateNewSampleChunk(types, sample_count);
208668
208669 // The current selection vector can potentially have 2048 valid mappings.
208670 // If we need to save a sample with less rows than that, we need to do the following
208671 // 1. Create a new selection vector that doesn't point to the rows we are evicting
208672 SelectionVector new_sel(num_samples_to_keep);
208673 idx_t offset = 0;
208674 for (idx_t i = 0; i < num_samples_to_keep + selections_to_delete.size(); i++) {
208675 if (selections_to_delete.find(i) == selections_to_delete.end()) {
208676 D_ASSERT(i - offset < num_samples_to_keep);
208677 new_sel.set_index(i - offset, sel.get_index(i));
208678 } else {
208679 offset += 1;
208680 }
208681 }
208682 // 2. Update row_ids in our weights so that they don't store rows ids to
208683 // indexes in the selection vector that have been evicted.
208684 if (!selections_to_delete.empty()) {
208685 NormalizeWeights();
208686 }
208687
208688 D_ASSERT(reservoir_chunk->chunk.GetTypes() == new_reservoir_chunk->chunk.GetTypes());
208689
208690 UpdateSampleAppend(new_reservoir_chunk->chunk, reservoir_chunk->chunk, new_sel, num_samples_to_keep);
208691 // set the cardinality
208692 new_reservoir_chunk->chunk.SetCardinality(num_samples_to_keep);
208693 reservoir_chunk = std::move(new_reservoir_chunk);
208694 sel_size = num_samples_to_keep;
208695 base_reservoir_sample->UpdateMinWeightThreshold();
208696}
std::pair< double, idx_t > PopFromWeightQueue()
Helper functions needed to merge two reservoirs while respecting weights of sampled rows.
Definition duckdb.cpp:208161
bool destroyed
has the sample been destroyed due to updates to the referenced table
Definition duckdb.hpp:47811
void UpdateSampleAppend(DataChunk &this_, DataChunk &other, SelectionVector &other_sel, idx_t append_count) const
Update the sample by pushing new sample rows to the end of the sample_chunk. The new sample rows are ...
Definition duckdb.cpp:208849
Here is the call graph for this function:

◆ ExpandSerializedSample()

void duckdb::ReservoirSample::ExpandSerializedSample ( )
208698 {
208699 if (!reservoir_chunk) {
208700 return;
208701 }
208702
208703 auto types = reservoir_chunk->chunk.GetTypes();
208704 auto new_res_chunk = CreateNewSampleChunk(types, GetReservoirChunkCapacity<idx_t>());
208705 auto copy_count = reservoir_chunk->chunk.size();
208706 SelectionVector tmp_sel = SelectionVector(0, copy_count);
208707 UpdateSampleAppend(new_res_chunk->chunk, reservoir_chunk->chunk, tmp_sel, copy_count);
208708 new_res_chunk->chunk.SetCardinality(copy_count);
208709 std::swap(reservoir_chunk, new_res_chunk);
208710}
T GetReservoirChunkCapacity() const
Get the capactiy of the data chunk reserved for storing samples.
Definition duckdb.cpp:208713

◆ GetSamplingState()

SamplingState duckdb::ReservoirSample::GetSamplingState ( ) const
208236 {
208237 if (base_reservoir_sample->reservoir_weights.empty()) {
208238 return SamplingState::RANDOM;
208239 }
208240 return SamplingState::RESERVOIR;
208241}

◆ Vacuum()

void duckdb::ReservoirSample::Vacuum ( )

Vacuum the Reservoir Sample so it throws away tuples that are not in the reservoir weights or in the selection vector.

208320 {
208321 Verify();
208322 bool do_vacuum = false;
208323 // when it's not a stats sample, sometimes we neverr collect more than FIXED_SAMPLE_SIZE tuples
208324 // but we still need to vacuum, so the rules are a little bit different.
208325 if (!stats_sample && GetActiveSampleCount() <= static_cast<idx_t>(GetReservoirChunkCapacity<double>() * 0.8)) {
208326 do_vacuum = true;
208327 }
208328 if (!do_vacuum && (NumSamplesCollected() <= FIXED_SAMPLE_SIZE || !reservoir_chunk || destroyed)) {
208329 // sample is destroyed or too small to shrink
208330 // sample does not need to be vacuumed.
208331 return;
208332 }
208333
208334 auto ret = Copy();
208335 auto ret_reservoir = duckdb::unique_ptr_cast<BlockingSample, ReservoirSample>(std::move(ret));
208336 reservoir_chunk = std::move(ret_reservoir->reservoir_chunk);
208337 sel = std::move(ret_reservoir->sel);
208338 sel_size = ret_reservoir->sel_size;
208339
208340 Verify();
208341 // We should only have one sample chunk now.
208342 D_ASSERT(Chunk().size() > 0 && Chunk().size() <= sample_count);
208343}
unique_ptr< BlockingSample > Copy() const override
If for_serialization=true then the sample_chunk is not padded with extra spaces for future sampling v...
Definition duckdb.cpp:208345
GOpaque< Size > size(const GMat &src)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ConvertToReservoirSample()

void duckdb::ReservoirSample::ConvertToReservoirSample ( )

Transform To sample based on reservoir sampling paper.

208379 {
208380 D_ASSERT(sel_size <= sample_count);
208381 base_reservoir_sample->FillWeights(sel, sel_size);
208382}
Here is the caller graph for this function:

◆ GetReservoirChunkCapacity()

template<typename T>
T duckdb::ReservoirSample::GetReservoirChunkCapacity ( ) const

Get the capactiy of the data chunk reserved for storing samples.

208713 {
208714 return static_cast<T>(sample_count +
208715 (FIXED_SAMPLE_SIZE_MULTIPLIER * MinValue<idx_t>(sample_count, FIXED_SAMPLE_SIZE)));
208716}
Here is the caller graph for this function:

◆ Copy()

unique_ptr< BlockingSample > duckdb::ReservoirSample::Copy ( ) const
overridevirtual

If for_serialization=true then the sample_chunk is not padded with extra spaces for future sampling values.

Implements duckdb::BlockingSample.

208345 {
208346 auto ret = make_uniq<ReservoirSample>(sample_count);
208347 ret->stats_sample = stats_sample;
208348
208349 ret->base_reservoir_sample = base_reservoir_sample->Copy();
208350 ret->destroyed = destroyed;
208351
208352 if (!reservoir_chunk || destroyed) {
208353 return unique_ptr_cast<ReservoirSample, BlockingSample>(std::move(ret));
208354 }
208355
208356 D_ASSERT(reservoir_chunk);
208357
208358 // create a new sample chunk to store new samples
208359 auto types = reservoir_chunk->chunk.GetTypes();
208360 // how many values should be copied
208361 idx_t values_to_copy = MinValue<idx_t>(GetActiveSampleCount(), sample_count);
208362
208363 auto new_sample_chunk = CreateNewSampleChunk(types, GetReservoirChunkCapacity<idx_t>());
208364
208365 SelectionVector sel_copy(sel);
208366
208367 ret->reservoir_chunk = std::move(new_sample_chunk);
208368 ret->UpdateSampleAppend(ret->reservoir_chunk->chunk, reservoir_chunk->chunk, sel_copy, values_to_copy);
208369 ret->sel = SelectionVector(values_to_copy);
208370 for (idx_t i = 0; i < values_to_copy; i++) {
208371 ret->sel.set_index(i, i);
208372 }
208373 ret->sel_size = sel_size;
208374 D_ASSERT(ret->reservoir_chunk->chunk.size() <= sample_count);
208375 ret->Verify();
208376 return unique_ptr_cast<ReservoirSample, BlockingSample>(std::move(ret));
208377}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FillReservoir()

idx_t duckdb::ReservoirSample::FillReservoir ( DataChunk & chunk)

create the first chunk called by AddToReservoir()

208718 {
208719 idx_t ingested_count = 0;
208720 if (!reservoir_chunk) {
208721 if (chunk.size() > FIXED_SAMPLE_SIZE) {
208722 throw InternalException("Creating sample with DataChunk that is larger than the fixed sample size");
208723 }
208724 auto types = chunk.GetTypes();
208725 // create a new sample chunk to store new samples
208726 reservoir_chunk = CreateNewSampleChunk(types, GetReservoirChunkCapacity<idx_t>());
208727 }
208728
208729 idx_t actual_sample_index_start = GetActiveSampleCount();
208730 D_ASSERT(reservoir_chunk->chunk.ColumnCount() == chunk.ColumnCount());
208731
208732 if (reservoir_chunk->chunk.size() < sample_count) {
208733 ingested_count = MinValue<idx_t>(sample_count - reservoir_chunk->chunk.size(), chunk.size());
208734 auto random_other_sel =
208735 GetRandomizedVector(static_cast<uint32_t>(ingested_count), static_cast<uint32_t>(ingested_count));
208736 SelectionVector sel_for_input_chunk(ingested_count);
208737 for (idx_t i = 0; i < ingested_count; i++) {
208738 sel.set_index(actual_sample_index_start + i, actual_sample_index_start + i);
208739 sel_for_input_chunk.set_index(i, random_other_sel[i]);
208740 }
208741 UpdateSampleAppend(reservoir_chunk->chunk, chunk, sel_for_input_chunk, ingested_count);
208742 sel_size += ingested_count;
208743 }
208744 D_ASSERT(GetActiveSampleCount() <= sample_count);
208745 D_ASSERT(GetActiveSampleCount() >= ingested_count);
208746 // always return how many tuples were ingested
208747 return ingested_count;
208748}
DUCKDB_API vector< LogicalType > GetTypes() const
Returns a list of types of the vectors of this data chunk.
Definition duckdb.cpp:116995
::uint32_t uint32_t
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AddToReservoir()

void duckdb::ReservoirSample::AddToReservoir ( DataChunk & input)
overridevirtual

Add a chunk of data to the sample.

Implements duckdb::BlockingSample.

208868 {
208869 if (destroyed || chunk.size() == 0) {
208870 return;
208871 }
208872
208873 if (!reservoir_chunk && GetReservoirChunkCapacity<idx_t>() == 0) {
208874 return;
208875 }
208876 idx_t tuples_consumed = FillReservoir(chunk);
208877 base_reservoir_sample->num_entries_seen_total += tuples_consumed;
208878 D_ASSERT(sample_count == 0 || reservoir_chunk->chunk.size() >= 1);
208879
208880 if (tuples_consumed == chunk.size()) {
208881 return;
208882 }
208883
208884 // the chunk filled the first FIXED_SAMPLE_SIZE chunk but still has tuples remaining
208885 // slice the chunk and call AddToReservoir again.
208886 if (tuples_consumed != chunk.size() && tuples_consumed != 0) {
208887 // Fill reservoir consumed some of the chunk to reach FIXED_SAMPLE_SIZE
208888 // now we need to
208889 // So we slice it and call AddToReservoir
208890 auto slice = make_uniq<DataChunk>();
208891 auto samples_remaining = chunk.size() - tuples_consumed;
208892 auto types = chunk.GetTypes();
208893 SelectionVector input_sel(samples_remaining);
208894 for (idx_t i = 0; i < samples_remaining; i++) {
208895 input_sel.set_index(i, tuples_consumed + i);
208896 }
208897 slice->Initialize(Allocator::DefaultAllocator(), types, samples_remaining);
208898 slice->Slice(chunk, input_sel, samples_remaining);
208899 slice->SetCardinality(samples_remaining);
208900 AddToReservoir(*slice);
208901 return;
208902 }
208903
208904 // at this point we should have collected at least sample count samples
208905 D_ASSERT(GetActiveSampleCount() >= sample_count);
208906
208907 auto chunk_sel = GetReplacementIndexes(reservoir_chunk->chunk.size(), chunk.size());
208908
208909 if (chunk_sel.size == 0) {
208910 // not adding any samples
208911 base_reservoir_sample->num_entries_seen_total += chunk.size();
208912 return;
208913 }
208914
208915 idx_t size = chunk_sel.size;
208916 D_ASSERT(size <= chunk.size());
208917 D_ASSERT(reservoir_chunk->chunk.size() < GetReservoirChunkCapacity<idx_t>());
208918
208919 UpdateSampleAppend(reservoir_chunk->chunk, chunk, chunk_sel.sel, size);
208920
208921 base_reservoir_sample->num_entries_seen_total += chunk.size();
208922 D_ASSERT(base_reservoir_sample->reservoir_weights.size() == 0 ||
208923 base_reservoir_sample->reservoir_weights.size() == sample_count);
208924
208925 Verify();
208926
208927 // if we are over the threshold, we ned to switch to slow sampling.
208928 if (GetSamplingState() == SamplingState::RANDOM && GetTuplesSeen() >= FIXED_SAMPLE_SIZE * FAST_TO_SLOW_THRESHOLD) {
208930 }
208931 if (static_cast<int64_t>(reservoir_chunk->chunk.size()) >=
208932 GetReservoirChunkCapacity<int64_t>() - (static_cast<int64_t>(FIXED_SAMPLE_SIZE) * 3)) {
208933 Vacuum();
208934 }
208935}
idx_t FillReservoir(DataChunk &chunk)
create the first chunk called by AddToReservoir()
Definition duckdb.cpp:208718
void AddToReservoir(DataChunk &input) override
Add a chunk of data to the sample.
Definition duckdb.cpp:208868
SelectionVectorHelper GetReplacementIndexes(idx_t sample_chunk_offset, idx_t theoretical_chunk_length)
Get indexes from current sample that can be replaced.
Definition duckdb.cpp:208754
void ConvertToReservoirSample()
Transform To sample based on reservoir sampling paper.
Definition duckdb.cpp:208379
void Vacuum()
Vacuum the Reservoir Sample so it throws away tuples that are not in the reservoir weights or in the ...
Definition duckdb.cpp:208320
::int64_t int64_t
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Merge()

void duckdb::ReservoirSample::Merge ( unique_ptr< BlockingSample > other)

Merge two Reservoir Samples. Other must be a reservoir sample.

Both samples are still in "fast sampling" method

208569 {
208570 if (destroyed || other->destroyed) {
208571 Destroy();
208572 return;
208573 }
208574
208575 D_ASSERT(other->type == SampleType::RESERVOIR_SAMPLE);
208576 auto &other_sample = other->Cast<ReservoirSample>();
208577
208578 // if the other sample has not collected anything yet return
208579 if (!other_sample.reservoir_chunk || other_sample.reservoir_chunk->chunk.size() == 0) {
208580 return;
208581 }
208582
208583 // this has not collected samples, take over the other
208584 if (!reservoir_chunk || reservoir_chunk->chunk.size() == 0) {
208585 base_reservoir_sample = std::move(other->base_reservoir_sample);
208586 reservoir_chunk = std::move(other_sample.reservoir_chunk);
208587 sel = SelectionVector(other_sample.sel);
208588 sel_size = other_sample.sel_size;
208589 Verify();
208590 return;
208591 }
208593 if (GetSamplingState() == SamplingState::RANDOM && other_sample.GetSamplingState() == SamplingState::RANDOM) {
208594 SimpleMerge(other_sample);
208595 return;
208596 }
208597
208598 // One or none of the samples are in "Fast Sampling" method.
208599 // When this is the case, switch both to slow sampling
208601 other_sample.ConvertToReservoirSample();
208602 WeightedMerge(other_sample);
208603}
Here is the call graph for this function:

◆ ShuffleSel()

void duckdb::ReservoirSample::ShuffleSel ( SelectionVector & sel,
idx_t range,
idx_t size ) const
208605 {
208606 auto randomized = GetRandomizedVector(static_cast<uint32_t>(range), static_cast<uint32_t>(size));
208607 SelectionVector original_sel(range);
208608 for (idx_t i = 0; i < range; i++) {
208609 original_sel.set_index(i, sel.get_index(i));
208610 }
208611 for (idx_t i = 0; i < size; i++) {
208612 sel.set_index(i, original_sel.get_index(randomized[i]));
208613 }
208614}

◆ UpdateSampleAppend()

void duckdb::ReservoirSample::UpdateSampleAppend ( DataChunk & this_,
DataChunk & other,
SelectionVector & other_sel,
idx_t append_count ) const

Update the sample by pushing new sample rows to the end of the sample_chunk. The new sample rows are the tuples rows resulting from applying sel to other.

208850 {
208851 idx_t new_size = this_.size() + append_count;
208852 if (other.size() == 0) {
208853 return;
208854 }
208855 D_ASSERT(this_.GetTypes() == other.GetTypes());
208856 auto types = reservoir_chunk->chunk.GetTypes();
208857
208858 for (idx_t i = 0; i < reservoir_chunk->chunk.ColumnCount(); i++) {
208859 auto col_type = types[i];
208860 if (ValidSampleType(col_type) || !stats_sample) {
208861 D_ASSERT(this_.data[i].GetVectorType() == VectorType::FLAT_VECTOR);
208862 VectorOperations::Copy(other.data[i], this_.data[i], other_sel, append_count, 0, this_.size());
208863 }
208864 }
208865 this_.SetCardinality(new_size);
208866}
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetTuplesSeen()

idx_t duckdb::ReservoirSample::GetTuplesSeen ( ) const
208254 {
208255 return base_reservoir_sample->num_entries_seen_total;
208256}

◆ NumSamplesCollected()

idx_t duckdb::ReservoirSample::NumSamplesCollected ( ) const
208229 {
208230 if (!reservoir_chunk) {
208231 return 0;
208232 }
208233 return reservoir_chunk->chunk.size();
208234}

◆ GetActiveSampleCount()

idx_t duckdb::ReservoirSample::GetActiveSampleCount ( ) const
208243 {
208244 switch (GetSamplingState()) {
208245 case SamplingState::RANDOM:
208246 return sel_size;
208247 case SamplingState::RESERVOIR:
208248 return base_reservoir_sample->reservoir_weights.size();
208249 default:
208250 throw InternalException("Sampling State is INVALID");
208251 }
208252}

◆ ValidSampleType()

bool duckdb::ReservoirSample::ValidSampleType ( const LogicalType & type)
static
208845 {
208846 return type.IsNumeric();
208847}

◆ Chunk()

DataChunk & duckdb::ReservoirSample::Chunk ( )
208258 {
208259 D_ASSERT(reservoir_chunk);
208260 return reservoir_chunk->chunk;
208261}

◆ GetChunk()

unique_ptr< DataChunk > duckdb::ReservoirSample::GetChunk ( )
overridevirtual

Fetches a chunk from the sample. Note that this method is destructive and should only be used after the sample is completely built.

Implements duckdb::BlockingSample.

208263 {
208264 if (destroyed || !reservoir_chunk || Chunk().size() == 0) {
208265 return nullptr;
208266 }
208267 // cannot destory internal samples.
208268 auto ret = make_uniq<DataChunk>();
208269
208270 SelectionVector ret_sel(STANDARD_VECTOR_SIZE);
208271 idx_t collected_samples = GetActiveSampleCount();
208272
208273 if (collected_samples == 0) {
208274 return nullptr;
208275 }
208276
208277 idx_t samples_remaining;
208278 idx_t return_chunk_size;
208279 if (collected_samples > STANDARD_VECTOR_SIZE) {
208280 samples_remaining = collected_samples - STANDARD_VECTOR_SIZE;
208281 return_chunk_size = STANDARD_VECTOR_SIZE;
208282 } else {
208283 samples_remaining = 0;
208284 return_chunk_size = collected_samples;
208285 }
208286
208287 for (idx_t i = samples_remaining; i < collected_samples; i++) {
208288 // pop samples and reduce size of selection vector.
208289 if (GetSamplingState() == SamplingState::RESERVOIR) {
208290 auto top = PopFromWeightQueue();
208291 ret_sel.set_index(i - samples_remaining, sel.get_index(top.second));
208292 } else {
208293 ret_sel.set_index(i - samples_remaining, sel.get_index(i));
208294 }
208295 sel_size -= 1;
208296 }
208297
208298 auto reservoir_types = Chunk().GetTypes();
208299
208300 ret->Initialize(allocator, reservoir_types, STANDARD_VECTOR_SIZE);
208301 ret->Slice(Chunk(), ret_sel, return_chunk_size);
208302 ret->SetCardinality(return_chunk_size);
208303 return ret;
208304}
Here is the call graph for this function:

◆ Destroy()

void duckdb::ReservoirSample::Destroy ( )
overridevirtual

Reimplemented from duckdb::BlockingSample.

208750 {
208751 destroyed = true;
208752}

◆ Finalize()

void duckdb::ReservoirSample::Finalize ( )
overridevirtual

Implements duckdb::BlockingSample.

208842 {
208843}

◆ Verify()

void duckdb::ReservoirSample::Verify ( )
208937 {
208938#ifdef DEBUG
208939 if (destroyed) {
208940 return;
208941 }
208942 if (GetPriorityQueueSize() == 0) {
208943 D_ASSERT(GetActiveSampleCount() <= sample_count);
208944 D_ASSERT(GetTuplesSeen() >= GetActiveSampleCount());
208945 return;
208946 }
208947 if (NumSamplesCollected() > sample_count) {
208948 D_ASSERT(GetPriorityQueueSize() == sample_count);
208949 } else if (NumSamplesCollected() <= sample_count && GetPriorityQueueSize() > 0) {
208950 // it's possible to collect more samples than your priority queue size.
208951 // see sample_converts_to_reservoir_sample.test
208952 D_ASSERT(NumSamplesCollected() >= GetPriorityQueueSize());
208953 }
208954 auto base_reservoir_copy = base_reservoir_sample->Copy();
208955 std::unordered_map<idx_t, idx_t> index_count;
208956 while (!base_reservoir_copy->reservoir_weights.empty()) {
208957 auto &pair = base_reservoir_copy->reservoir_weights.top();
208958 if (index_count.find(pair.second) == index_count.end()) {
208959 index_count[pair.second] = 1;
208960 base_reservoir_copy->reservoir_weights.pop();
208961 } else {
208962 index_count[pair.second] += 1;
208963 base_reservoir_copy->reservoir_weights.pop();
208964 throw InternalException("Duplicate selection index in reservoir weights");
208965 }
208966 }
208967 // TODO: Verify the Sel as well. No duplicate indices.
208968
208969 if (reservoir_chunk) {
208970 reservoir_chunk->chunk.Verify();
208971 }
208972#endif
208973}

◆ GetSampleCount()

idx_t duckdb::ReservoirSample::GetSampleCount ( )
208225 {
208226 return sample_count;
208227}

◆ GetReplacementIndexes()

SelectionVectorHelper duckdb::ReservoirSample::GetReplacementIndexes ( idx_t sample_chunk_offset,
idx_t theoretical_chunk_length )

Get indexes from current sample that can be replaced.

208755 {
208756 if (GetSamplingState() == SamplingState::RANDOM) {
208757 return GetReplacementIndexesFast(sample_chunk_offset, theoretical_chunk_length);
208758 }
208759 return GetReplacementIndexesSlow(sample_chunk_offset, theoretical_chunk_length);
208760}
Here is the caller graph for this function:

◆ Serialize()

void duckdb::ReservoirSample::Serialize ( Serializer & serializer) const
overridevirtual

Reimplemented from duckdb::BlockingSample.

417626 {
417627 BlockingSample::Serialize(serializer);
417628 serializer.WritePropertyWithDefault<idx_t>(200, "sample_count", sample_count);
417629 serializer.WritePropertyWithDefault<unique_ptr<ReservoirChunk>>(201, "reservoir_chunk", reservoir_chunk);
417630}

◆ Deserialize()

unique_ptr< BlockingSample > duckdb::ReservoirSample::Deserialize ( Deserializer & deserializer)
static
417632 {
417633 auto sample_count = deserializer.ReadPropertyWithDefault<idx_t>(200, "sample_count");
417634 auto reservoir_chunk = deserializer.ReadPropertyWithDefault<unique_ptr<ReservoirChunk>>(201, "reservoir_chunk");
417635 auto result = duckdb::unique_ptr<ReservoirSample>(new ReservoirSample(sample_count, std::move(reservoir_chunk)));
417636 return std::move(result);
417637}

◆ NormalizeWeights()

void duckdb::ReservoirSample::NormalizeWeights ( )
private
208616 {
208617 vector<std::pair<double, idx_t>> tmp_weights;
208618 while (!base_reservoir_sample->reservoir_weights.empty()) {
208619 auto top = base_reservoir_sample->reservoir_weights.top();
208620 tmp_weights.push_back(std::move(top));
208621 base_reservoir_sample->reservoir_weights.pop();
208622 }
208623 std::sort(tmp_weights.begin(), tmp_weights.end(),
208624 [&](std::pair<double, idx_t> a, std::pair<double, idx_t> b) { return a.second < b.second; });
208625 for (idx_t i = 0; i < tmp_weights.size(); i++) {
208626 base_reservoir_sample->reservoir_weights.emplace(tmp_weights.at(i).first, i);
208627 }
208628 base_reservoir_sample->SetNextEntry();
208629}

◆ GetReplacementIndexesSlow()

SelectionVectorHelper duckdb::ReservoirSample::GetReplacementIndexesSlow ( const idx_t sample_chunk_offset,
const idx_t chunk_length )
private
208796 {
208797 idx_t remaining = chunk_length;
208798 std::unordered_map<idx_t, idx_t> ret_map;
208799 idx_t sample_chunk_index = 0;
208800
208801 idx_t base_offset = 0;
208802
208803 while (true) {
208804 idx_t offset =
208805 base_reservoir_sample->next_index_to_sample - base_reservoir_sample->num_entries_to_skip_b4_next_sample;
208806 if (offset >= remaining) {
208807 // not in this chunk! increment current count and go to the next chunk
208808 base_reservoir_sample->num_entries_to_skip_b4_next_sample += remaining;
208809 break;
208810 }
208811 // in this chunk! replace the element
208812 // ret[index_in_new_chunk] = index_in_sample_chunk (the sample chunk offset will be applied later)
208813 // D_ASSERT(sample_chunk_index == ret.size());
208814 ret_map[base_offset + offset] = sample_chunk_index;
208815 double r2 = base_reservoir_sample->random.NextRandom32(base_reservoir_sample->min_weight_threshold, 1);
208816 // replace element in our max_heap
208817 // first get the top most pair
208818 const auto top = PopFromWeightQueue();
208819 const auto index = top.second;
208820 const auto index_in_sample_chunk = sample_chunk_offset + sample_chunk_index;
208821 sel.set_index(index, index_in_sample_chunk);
208822 base_reservoir_sample->ReplaceElementWithIndex(index, r2, false);
208823
208824 sample_chunk_index += 1;
208825 // shift the chunk forward
208826 remaining -= offset;
208827 base_offset += offset;
208828 }
208829
208830 // create selection vector to return
208831 SelectionVector ret_sel(ret_map.size());
208832 D_ASSERT(sel_size == sample_count);
208833 for (auto &kv : ret_map) {
208834 ret_sel.set_index(kv.second, kv.first);
208835 }
208836 SelectionVectorHelper ret;
208837 ret.sel = SelectionVector(ret_sel);
208838 ret.size = static_cast<uint32_t>(ret_map.size());
208839 return ret;
208840}
index

◆ GetReplacementIndexesFast()

SelectionVectorHelper duckdb::ReservoirSample::GetReplacementIndexesFast ( const idx_t sample_chunk_offset,
const idx_t chunk_length )
private
208762 {
208763 // how much weight to the other tuples have compared to the ones in this chunk?
208764 auto weight_tuples_other = static_cast<double>(chunk_length) / static_cast<double>(GetTuplesSeen() + chunk_length);
208765 auto num_to_pop = static_cast<uint32_t>(round(weight_tuples_other * static_cast<double>(sample_count)));
208766 D_ASSERT(num_to_pop <= sample_count);
208767 D_ASSERT(num_to_pop <= sel_size);
208768 SelectionVectorHelper ret;
208769
208770 if (num_to_pop == 0) {
208771 ret.sel = SelectionVector(num_to_pop);
208772 ret.size = 0;
208773 return ret;
208774 }
208775 std::unordered_map<idx_t, idx_t> replacement_indexes;
208776 SelectionVector chunk_sel(num_to_pop);
208777
208778 auto random_indexes_chunk = GetRandomizedVector(static_cast<uint32_t>(chunk_length), num_to_pop);
208779 auto random_sel_indexes = GetRandomizedVector(static_cast<uint32_t>(sel_size), num_to_pop);
208780 for (idx_t i = 0; i < num_to_pop; i++) {
208781 // update the selection vector for the reservoir sample
208782 chunk_sel.set_index(i, random_indexes_chunk[i]);
208783 // sel is not guaratneed to be random, so we update the indexes according to our
208784 // random sel indexes.
208785 sel.set_index(random_sel_indexes[i], sample_chunk_offset + i);
208786 }
208787
208788 D_ASSERT(sel_size == sample_count);
208789
208790 ret.sel = SelectionVector(chunk_sel);
208791 ret.size = num_to_pop;
208792 return ret;
208793}

◆ SimpleMerge()

void duckdb::ReservoirSample::SimpleMerge ( ReservoirSample & other)
private
208404 {
208405 D_ASSERT(GetPriorityQueueSize() == 0);
208406 D_ASSERT(other.GetPriorityQueueSize() == 0);
208407 D_ASSERT(GetSamplingState() == SamplingState::RANDOM);
208408 D_ASSERT(other.GetSamplingState() == SamplingState::RANDOM);
208409
208410 if (other.GetActiveSampleCount() == 0 && other.GetTuplesSeen() == 0) {
208411 return;
208412 }
208413
208414 if (GetActiveSampleCount() == 0 && GetTuplesSeen() == 0) {
208415 sel = SelectionVector(other.sel);
208416 sel_size = other.sel_size;
208417 base_reservoir_sample->num_entries_seen_total = other.GetTuplesSeen();
208418 return;
208419 }
208420
208421 idx_t total_seen = GetTuplesSeen() + other.GetTuplesSeen();
208422
208423 auto weight_tuples_this = static_cast<double>(GetTuplesSeen()) / static_cast<double>(total_seen);
208424 auto weight_tuples_other = static_cast<double>(other.GetTuplesSeen()) / static_cast<double>(total_seen);
208425
208426 // If weights don't add up to 1, most likely a simple merge occurred and no new samples were added.
208427 // if that is the case, add the missing weight to the lower weighted sample to adjust.
208428 // this is to avoid cases where if you have a 20k row table and add another 20k rows row by row
208429 // then eventually the missing weights will add up, and get you a more even distribution
208430 if (weight_tuples_this + weight_tuples_other < 1) {
208431 weight_tuples_other += 1 - (weight_tuples_other + weight_tuples_this);
208432 }
208433
208434 idx_t keep_from_this = 0;
208435 idx_t keep_from_other = 0;
208436 D_ASSERT(stats_sample);
208437 D_ASSERT(sample_count == FIXED_SAMPLE_SIZE);
208438 D_ASSERT(sample_count == other.sample_count);
208439 auto sample_count_double = static_cast<double>(sample_count);
208440
208441 if (weight_tuples_this > weight_tuples_other) {
208442 keep_from_this = MinValue<idx_t>(static_cast<idx_t>(round(sample_count_double * weight_tuples_this)),
208443 GetActiveSampleCount());
208444 keep_from_other = MinValue<idx_t>(sample_count - keep_from_this, other.GetActiveSampleCount());
208445 } else {
208446 keep_from_other = MinValue<idx_t>(static_cast<idx_t>(round(sample_count_double * weight_tuples_other)),
208447 other.GetActiveSampleCount());
208448 keep_from_this = MinValue<idx_t>(sample_count - keep_from_other, GetActiveSampleCount());
208449 }
208450
208451 D_ASSERT(keep_from_this <= GetActiveSampleCount());
208452 D_ASSERT(keep_from_other <= other.GetActiveSampleCount());
208453 D_ASSERT(keep_from_other + keep_from_this <= FIXED_SAMPLE_SIZE);
208454 idx_t size_after_merge = MinValue<idx_t>(keep_from_other + keep_from_this, FIXED_SAMPLE_SIZE);
208455
208456 // Check if appending the other samples to this will go over the sample chunk size
208457 if (reservoir_chunk->chunk.size() + keep_from_other > GetReservoirChunkCapacity<idx_t>()) {
208458 Vacuum();
208459 }
208460
208461 D_ASSERT(size_after_merge <= other.GetActiveSampleCount() + GetActiveSampleCount());
208462 SelectionVector chunk_sel(keep_from_other);
208463 auto offset = reservoir_chunk->chunk.size();
208464 for (idx_t i = keep_from_this; i < size_after_merge; i++) {
208465 if (i >= GetActiveSampleCount()) {
208466 D_ASSERT(sel_size >= GetActiveSampleCount());
208467 sel.set_index(GetActiveSampleCount(), offset);
208468 sel_size += 1;
208469 } else {
208470 sel.set_index(i, offset);
208471 }
208472 chunk_sel.set_index(i - keep_from_this, other.sel.get_index(i - keep_from_this));
208473 offset += 1;
208474 }
208475
208476 D_ASSERT(GetActiveSampleCount() == size_after_merge);
208477
208478 // Copy the rows that make it to the sample from other and put them into this.
208479 UpdateSampleAppend(reservoir_chunk->chunk, other.reservoir_chunk->chunk, chunk_sel, keep_from_other);
208480 base_reservoir_sample->num_entries_seen_total += other.GetTuplesSeen();
208481
208482 // if THIS has too many samples now, we conver it to a slower sample.
208483 if (GetTuplesSeen() >= FIXED_SAMPLE_SIZE * FAST_TO_SLOW_THRESHOLD) {
208485 }
208486 Verify();
208487}

◆ WeightedMerge()

void duckdb::ReservoirSample::WeightedMerge ( ReservoirSample & other_sample)
private
208489 {
208490 D_ASSERT(GetSamplingState() == SamplingState::RESERVOIR);
208491 D_ASSERT(other_sample.GetSamplingState() == SamplingState::RESERVOIR);
208492
208493 // Find out how many samples we want to keep.
208494 idx_t total_samples = GetActiveSampleCount() + other_sample.GetActiveSampleCount();
208495 idx_t total_samples_seen =
208496 base_reservoir_sample->num_entries_seen_total + other_sample.base_reservoir_sample->num_entries_seen_total;
208497 idx_t num_samples_to_keep = MinValue<idx_t>(total_samples, MinValue<idx_t>(sample_count, total_samples_seen));
208498
208499 D_ASSERT(GetActiveSampleCount() <= num_samples_to_keep);
208500 D_ASSERT(total_samples <= FIXED_SAMPLE_SIZE * 2);
208501
208502 // pop from base base_reservoir weights until there are num_samples_to_keep left.
208503 vector<idx_t> this_indexes_to_replace;
208504 for (idx_t i = num_samples_to_keep; i < total_samples; i++) {
208505 auto min_weight_this = base_reservoir_sample->min_weight_threshold;
208506 auto min_weight_other = other_sample.base_reservoir_sample->min_weight_threshold;
208507 // min weight threshol is always positive
208508 if (min_weight_this > min_weight_other) {
208509 // pop from other
208510 other_sample.base_reservoir_sample->reservoir_weights.pop();
208511 other_sample.base_reservoir_sample->UpdateMinWeightThreshold();
208512 } else {
208513 auto top_this = PopFromWeightQueue();
208514 this_indexes_to_replace.push_back(top_this.second);
208515 base_reservoir_sample->UpdateMinWeightThreshold();
208516 }
208517 }
208518
208519 D_ASSERT(other_sample.GetPriorityQueueSize() + GetPriorityQueueSize() <= FIXED_SAMPLE_SIZE);
208520 D_ASSERT(other_sample.GetPriorityQueueSize() + GetPriorityQueueSize() == num_samples_to_keep);
208521 D_ASSERT(other_sample.reservoir_chunk->chunk.GetTypes() == reservoir_chunk->chunk.GetTypes());
208522
208523 // Prepare a selection vector to copy data from the other sample chunk to this sample chunk
208524 SelectionVector sel_other(other_sample.GetPriorityQueueSize());
208525 D_ASSERT(GetPriorityQueueSize() <= num_samples_to_keep);
208526 D_ASSERT(other_sample.GetPriorityQueueSize() >= this_indexes_to_replace.size());
208527 idx_t chunk_offset = 0;
208528
208529 // Now push weights from other.base_reservoir_sample to this
208530 // Depending on how many sample values "this" has, we either need to add to the selection vector
208531 // Or replace values in "this'" selection vector
208532 idx_t i = 0;
208533 while (other_sample.GetPriorityQueueSize() > 0) {
208534 auto other_top = other_sample.PopFromWeightQueue();
208535 idx_t index_for_new_pair = chunk_offset + reservoir_chunk->chunk.size();
208536
208537 // update the sel used to copy values from other to this
208538 sel_other.set_index(chunk_offset, other_top.second);
208539 if (i < this_indexes_to_replace.size()) {
208540 auto replacement_index = this_indexes_to_replace[i];
208541 sel.set_index(replacement_index, index_for_new_pair);
208542 other_top.second = replacement_index;
208543 } else {
208544 sel.set_index(sel_size, index_for_new_pair);
208545 other_top.second = sel_size;
208546 sel_size += 1;
208547 }
208548
208549 // make sure that the sample indexes are (this.sample_chunk.size() + chunk_offfset)
208550 base_reservoir_sample->reservoir_weights.push(other_top);
208551 chunk_offset += 1;
208552 i += 1;
208553 }
208554
208555 D_ASSERT(GetPriorityQueueSize() == num_samples_to_keep);
208556
208557 base_reservoir_sample->UpdateMinWeightThreshold();
208558 D_ASSERT(base_reservoir_sample->min_weight_threshold > 0);
208559 base_reservoir_sample->num_entries_seen_total = GetTuplesSeen() + other_sample.GetTuplesSeen();
208560
208561 UpdateSampleAppend(reservoir_chunk->chunk, other_sample.reservoir_chunk->chunk, sel_other, chunk_offset);
208562 if (reservoir_chunk->chunk.size() > FIXED_SAMPLE_SIZE * (FIXED_SAMPLE_SIZE_MULTIPLIER - 3)) {
208563 Vacuum();
208564 }
208565
208566 Verify();
208567}

◆ CreateNewSampleChunk()

unique_ptr< ReservoirChunk > duckdb::ReservoirSample::CreateNewSampleChunk ( vector< LogicalType > & types,
idx_t size ) const
private
208306 {
208307 auto new_sample_chunk = make_uniq<ReservoirChunk>();
208308 new_sample_chunk->chunk.Initialize(Allocator::DefaultAllocator(), types, size);
208309
208310 // set the NULL columns correctly
208311 for (idx_t col_idx = 0; col_idx < types.size(); col_idx++) {
208312 if (!ValidSampleType(types[col_idx]) && stats_sample) {
208313 new_sample_chunk->chunk.data[col_idx].SetVectorType(VectorType::CONSTANT_VECTOR);
208314 ConstantVector::SetNull(new_sample_chunk->chunk.data[col_idx], true);
208315 }
208316 }
208317 return new_sample_chunk;
208318}

◆ GetRandomizedVector()

vector< uint32_t > duckdb::ReservoirSample::GetRandomizedVector ( uint32_t range,
uint32_t size ) const
private
208384 {
208385 vector<uint32_t> ret;
208386 ret.reserve(range);
208387 for (uint32_t i = 0; i < range; i++) {
208388 ret.push_back(i);
208389 }
208390 for (uint32_t i = 0; i < size; i++) {
208391 uint32_t random_shuffle = base_reservoir_sample->random.NextRandomInteger32(i, range);
208392 if (random_shuffle == i) {
208393 // leave the value where it is
208394 continue;
208395 }
208396 uint32_t tmp = ret[random_shuffle];
208397 // basically replacing the tuple that was at index actual_sample_indexes[random_shuffle]
208398 ret[random_shuffle] = ret[i];
208399 ret[i] = tmp;
208400 }
208401 return ret;
208402}

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