106 float acc_square = 0.0;
107 float acc_peak = 0.0;
108 float acc_cross = 0.0;
109 for (uint k = lane; k < window_length; k += lanes) {
110 float v = sample_at(window, k);
113 acc_peak = max(acc_peak, abs(v));
114 if (k + 1u < window_length) {
115 float w = sample_at(window, k + 1u);
116 acc_cross += ((v >= 0.0) != (w >= 0.0)) ? 1.0 : 0.0;
119 float total = lane_reduce_sum(acc_sum);
120 float energy = lane_reduce_sum(acc_square);
121 float peak = lane_reduce_max(acc_peak);
122 float crossings = lane_reduce_sum(acc_cross);
123 float mean = total / float(window_length);
125 float acc_zero = 0.0;
126 for (uint k = lane; k < window_length; k += lanes) {
127 float c = sample_at(window, k) - mean;
130 float at_zero = lane_reduce_sum(acc_zero);
132 uint first_lag = uint(parameters[0]);
133 uint last_lag = uint(parameters[1]);
136 for (uint lag = first_lag + lane; lag <= last_lag; lag += lanes) {
138 for (uint k = 0u; k + lag < window_length; ++k) {
139 acc += (sample_at(window, k) - mean) * (sample_at(window, k + lag) - mean);
146 float top = lane_reduce_max(best);
147 float mine = (best == top && best > 0.0) ? float(best_lag) : 3.0e38;
148 float chosen = lane_reduce_min(mine);
150 results[result_base] = energy;
151 results[result_base + 1u] = total;
152 results[result_base + 2u] = peak;
153 results[result_base + 3u] = crossings;
154 results[result_base + 4u] = at_zero;
155 results[result_base + 5u] = top;
156 results[result_base + 6u] = top > 0.0 ? chosen : 0.0;
179 [[nodiscard]] std::shared_ptr<Kakshya::TensorContainer>
to_tensor(std::string name)
const
185 return data ? std::make_shared<Kakshya::TensorContainer>(std::move(*data)) :
nullptr;
264template <ComputeData InputType = std::vector<Kakshya::DataVariant>, ComputeData OutputType = Eigen::MatrixXd>
295 return safe_any_cast_or_throw<WaveformAnalysis>(result);
313 [[nodiscard]] std::string
get_name()
const override
315 return "WaveformAnalyzer";
335 if (cfg.native_float) {
345 analysis.
channels.resize(data_span.size());
347 std::vector<std::vector<double>> channel_values;
348 channel_values.reserve(data_span.size());
350 for (
size_t channel = 0; channel < data_span.size(); ++channel) {
351 const std::span<const double> samples { data_span[channel].data(), data_span[channel].size() };
352 const size_t windows = samples.size() < cfg.window_size
354 : (samples.size() - cfg.window_size) / cfg.hop_size + 1;
356 auto& result = analysis.
channels[channel];
357 if (cfg.keep_profiles) {
358 result.autocorrelation.first_lag = 0;
359 result.autocorrelation.lag_count = max_lag + 1;
360 result.mean_difference.first_lag = min_lag;
361 result.mean_difference.lag_count = max_lag - min_lag + 1;
365 if (cfg.native_float) {
368 measure_chunk(result, samples, first, count, min_lag, max_lag, cfg);
373 channel_values.push_back(result.values);
383 }
catch (
const std::exception& e) {
400 mutable std::unique_ptr<SegmentedReductionContext>
m_energy;
401 mutable std::unique_ptr<SegmentedReductionContext>
m_sum;
402 mutable std::unique_ptr<SegmentedReductionContext>
m_peak;
405 std::unique_ptr<WordPairExecutionContext>
context;
417 mutable std::unique_ptr<ShaderExecutionContext<>>
m_native;
446 std::source_location::current(),
"The native waveform kernel did not compile; the shader log has the compiler's message");
464 const auto fail = [](std::string_view message) {
466 std::source_location::current(),
"{}", message);
469 fail(
"Sample rate must be finite and greater than 0");
474 fail(
"Frequencies must satisfy 0 < low < high < sample rate / 2");
478 if (min_lag >= max_lag) {
479 fail(
"The frequency range spans fewer than two lags");
481 if (max_lag >= std::numeric_limits<uint16_t>::max()) {
482 fail(
"The longest period is too long to search");
485 fail(
"The window must hold at least twice the longest period");
488 fail(
"The hop size must be greater than 0");
491 fail(
"Profiles are kept only by the double passes, not with native_float");
504 m_recording = std::make_shared<GpuDispatchRecorder>(
true);
505 m_energy = std::make_unique<SegmentedReductionContext>(KernelOp::Sum, ReductionMap::Square);
506 m_sum = std::make_unique<SegmentedReductionContext>(KernelOp::Sum, ReductionMap::Identity);
507 m_peak = std::make_unique<SegmentedReductionContext>(KernelOp::Max, ReductionMap::Abs);
513 for (
GpuDispatchCore* context : std::initializer_list<GpuDispatchCore*> {
521 for (
GpuDispatchCore* context : std::initializer_list<GpuDispatchCore*> {
543 return { std::move(context), std::move(
config) };
550 auto context = std::make_unique<WordPairExecutionContext>(
config,
bindings_from_spec(spec),
false,
"SegmentedArgMax");
551 return { std::move(context), std::move(
config) };
556 pass.context->record_stages({
lagged_pair_stage(*pass.context, pass.config, geometry, first_lag, lag_count) });
559 static std::vector<double>
download_lagged(WordPass& pass,
size_t windows, uint32_t lag_count)
561 return pass.context->download_words(1, windows * lag_count);
564 template <
typename Context>
565 static std::vector<double>
collect(Context& context)
567 return context.decode_primary(context.collect_result());
573 const size_t begin = first * cfg.
hop_size;
575 const auto chunk = samples.subspan(begin, end - begin);
578 const uint32_t first_lag = full_row ? 0 : min_lag;
579 const uint32_t correlation_lags = max_lag + 1 - first_lag;
580 const uint32_t distance_lags = max_lag - min_lag + 1;
584 m_sum->stage(geometry);
588 static_cast<void>(
m_energy->dispatch_async(none));
589 static_cast<void>(
m_sum->dispatch_async(none));
590 static_cast<void>(
m_peak->dispatch_async(none));
595 .length = max_lag - min_lag + 1,
596 .stride = correlation_lags,
597 .offset = min_lag - first_lag,
598 .count =
static_cast<uint32_t
>(count)
608 ChunkMeasures measures;
617 measures.correlation_lags = correlation_lags;
618 measures.distance_lags = distance_lags;
627 const size_t begin = first * cfg.
hop_size;
629 const auto chunk = samples.subspan(begin, end - begin);
630 const std::vector<float> floats(chunk.begin(), chunk.end());
631 const std::array<float, 2> parameters {
static_cast<float>(min_lag),
static_cast<float>(max_lag) };
637 ChunkMeasures measures;
638 for (
size_t w = 0; w < count; ++w) {
640 measures.energy.push_back(r[0]);
641 measures.sum.push_back(r[1]);
642 measures.peak.push_back(r[2]);
643 measures.crossings.push_back(r[3]);
644 measures.zero.push_back(r[4]);
645 const auto lag =
static_cast<uint32_t
>(r[6]);
646 measures.picks.push_back({ .value = r[5], .index = lag >= min_lag && r[5] > 0.0F ? lag - min_lag :
no_argmax_index });
648 measures.correlation_lags = max_lag + 1 - min_lag;
649 measures.distance_lags = max_lag - min_lag + 1;
658 const uint32_t correlation_lags = m.correlation_lags;
659 const uint32_t distance_lags = m.distance_lags;
660 const double window =
static_cast<double>(cfg.
window_size);
661 for (
size_t w = 0; w < count; ++w) {
662 const size_t start = (first + w) * cfg.
hop_size;
665 const double level = std::sqrt(m.energy[w] / window);
666 out.
level.push_back(level);
667 out.
crossing_rate.push_back(m.crossings[w] / (window - 1.0));
668 out.
peak.push_back(m.peak[w]);
669 out.
dc_offset.push_back(m.sum[w] / window);
670 out.
crest_factor.push_back(level > 0.0 ? m.peak[w] / level : 0.0);
672 const double* row = full_row ? m.rows.data() + w * correlation_lags :
nullptr;
673 const double at_zero = full_row ? row[0] : m.zero[w];
676 uint32_t best_lag = 0;
677 if (varying && m.picks[w].found() && m.picks[w].value > 0.0) {
678 best = m.picks[w].value / at_zero;
679 best_lag = min_lag + m.picks[w].index;
681 best *= window / (window -
static_cast<double>(best_lag));
686 out.
period.push_back(
static_cast<double>(best_lag));
688 out.
harmonicity.push_back(best > 0.0 ? bounded / (1.0 - bounded) : 0.0);
691 for (uint32_t lag = 0; lag < correlation_lags; ++lag) {
694 const double* gaps = m.distance.data() + w * distance_lags;
695 for (uint32_t column = 0; column < distance_lags; ++column) {
696 out.
mean_difference.
values.push_back(gaps[column] / (window -
static_cast<double>(min_lag + column)));
704 const size_t windows = out.
level.size();
707 for (
size_t w = 1; w < windows; ++w) {
Modern, digital-first analyzer framework for Maya Flux.
#define MF_ERROR(comp, ctx,...)
#define MF_DESCRIBE(...)
Requests a generated member description for a struct at namespace scope.
Lagged pairwise sums of doubles on the GPU, exactly, with no fp64 on the device.
The largest value of each segment of doubles and where it is, on the GPU, with no fp64 on the device.
Reduces segments of doubles on the GPU, exactly, with no fp64 on the device.
Runs a supplied compute kernel over every window of a sequence.
void set(T value)
Stores a struct under its type identity.
static std::optional< TensorData > from_values(std::span< const T > values, std::vector< uint64_t > shape={}, std::string name={})
Contiguous tensor holding a copy of typed values.
bool is_initialized() const
Check if compiler is initialized.
void store_current_analysis(AnalysisResultType &&result) const
std::any get_current_analysis() const
Access cached analysis from last operation.
std::any analyze_data(const input_type &data)
User-facing analysis method - returns analysis results directly.
Template-flexible analyzer base with instance-defined I/O types.
const Config & config() const
void set_config(Config config)
Stores a config struct, whole, under its own type.
ConfigRefs stored_configs(Supports< Configs... >) const
The stored configs among those listed, in listed order.
output_type convert_result(std::vector< std::vector< double > > &result_data, DataStructureInfo &metadata)
Convert processed double data back to OutputType using metadata and optional callback.
Non-template base that owns all type-independent GPU dispatch logic.
static std::tuple< NumericChannels, DataStructureInfo > extract_structured_double(T &compute_data)
Extract structured double data from Datum container or direct ComputeData with automatic container ha...
static std::vector< uint8_t > encode_word_pairs(std::span< const double > values, size_t padded_words=0, bool order_key=false, bool complement=false)
Encode doubles as little-endian 64-bit words, two 32-bit lanes each.
@ ComputeMatrix
Compute operations (Yantra - algorithms, matrices, DSP).
@ Yantra
DSP algorithms, computational units, matrix operations, Grammar.
constexpr ShaderID INVALID_SHADER
MAYAFLUX_API ShaderFoundry & get_shader_foundry()
Get the global shader compiler instance.
ReductionMap
Pointwise map applied to each element before a SegmentedReduction combines it.
PairMap
Map of two elements, x[i] and x[i + lag], summed by a LaggedPair kernel.
KernelOp
Named operation the SPIR-V emitter knows how to lower to opcodes.
constexpr const char * waveform_native_kernel
Body of the native kernel in the windowed kernel layout, 128 lanes per window.
GpuComputeConfig windowed_kernel_config(const std::string &body, const WindowedKernelShape &shape={})
Config of a GLSL body wrapped in the layout.
constexpr uint32_t no_argmax_index
The index reported for a segment that holds no value to select.
std::vector< float > run_windowed_kernel(ShaderExecutionContext<> &context, const GpuComputeConfig &config, const WindowedKernelShape &shape, std::span< const WindowedInput > inputs, uint32_t window_length, uint32_t window_count, uint32_t outputs, std::span< const float > parameters)
Run a windowed kernel over every window of one or more sequences.
AnalysisType
Categories of analysis operations for discovery and organization.
@ TEMPORAL
Time-based patterns, onset detection.
std::vector< ArgMaxResult > read_argmax(WordPairExecutionContext &context, size_t segments)
Read the selections of the segments of the last recorded stage.
Portal::Graphics::ShaderSpec lagged_pair_spec(Portal::Graphics::PairMap map, bool centred, uint32_t workgroup=256)
The spec of a LaggedPair kernel.
DependencyStage lagged_pair_stage(WordPairExecutionContext &context, const GpuComputeConfig &config, const SegmentGeometry &geometry, uint32_t first_lag, uint32_t lag_count)
The stage that sums every window at every lag in a range, over values already on the device.
WaveformMethod
The per-window value a WaveformAnalyzer reports as its output data.
@ FREQUENCY
Sample rate over the best lag in Hz, zero when no lag qualified.
@ CREST_FACTOR
Peak over level, zero for a silent window.
@ CROSSING_RATE
Sign changes between neighbours per sample pair, 0 to 1.
@ HARMONICITY
Periodicity over one minus periodicity, zero when no lag qualified.
@ LEVEL_CHANGE
Level minus the previous window's level, zero for the first window.
@ PERIODICITY
Strength of the best repetition lag in the searched range, as a normalised correlation.
@ PEAK
Largest absolute sample.
@ PERIOD_CHANGE
Relative change of the period since the previous window, zero unless both have one.
@ PERIOD
Best repetition lag in samples, zero when no lag qualified.
@ LEVEL
Root mean square of the window.
WaveformAnalyzer< std::vector< Kakshya::DataVariant >, Eigen::MatrixXd > StandardWaveformAnalyzer
Standard waveform analyzer: DataVariant -> MatrixXd.
std::vector< GpuBufferBinding > windowed_kernel_layout(const WindowedKernelShape &shape={})
The binding layout of a windowed kernel.
DependencyStage segmented_argmax_stage(WordPairExecutionContext &context, const GpuComputeConfig &config, const SegmentGeometry &geometry)
The stage that selects the largest value of every segment of values already on the device.
GpuComputeConfig config_from_spec(const Portal::Graphics::ShaderSpec &spec)
Derive a GpuComputeConfig from a ShaderSpec.
std::vector< std::reference_wrapper< const OperationConfig > > ConfigRefs
Borrowed views of the configs an operation holds.
std::vector< GpuBufferBinding > bindings_from_spec(const Portal::Graphics::ShaderSpec &spec)
Derive a GpuBufferBinding list from a ShaderSpec.
Portal::Graphics::ShaderSpec segmented_argmax_spec(uint32_t workgroup=256)
The spec of a SegmentedArgMax kernel.
WaveformAnalyzer< std::shared_ptr< Kakshya::SignalSourceContainer >, Eigen::MatrixXd > ContainerWaveformAnalyzer
Container waveform analyzer: SignalContainer -> MatrixXd.
Plain-data description of the compute shader to dispatch.
Stores a scoped enum in its underlying integer type.
uint32_t window_size
Analysis window length in samples.
uint32_t hop_size
Distance between successive windows in samples.
Settings every analyzer family accepts.
Facets facets
Typed results that travel with the data, read by type.
std::unordered_map< std::string, std::any > metadata
Associated metadata.
Input/Output container for computation pipeline data flow with structure preservation.
uint32_t lag_count
Columns per window.
std::shared_ptr< Kakshya::TensorContainer > to_tensor(std::string name) const
The profile as a windows by lags float64 tensor.
uint32_t first_lag
Lag of the first column, in samples.
std::vector< double > values
Window major: window w, column c is values[w * lag_count + c].
One row of values per window, one column per consecutive lag.
Where the windows of a GPU pass sit in the value array.
The config structs an operation class accepts, declared as using supports.
A set of (device, runtime) pairs.
How many lanes share a window and how many sequences a kernel reads.